title = "2021年最值得測試同學使用的python庫"
description = ""
author = "乙醇"
tags = []
2021年不期而至了,我們不妨盤點一下2021年最值得測試同學使用的python庫/工具吧。
Validation
jsonschema: An(other) implementation of JSON Schema for Python
jsonschema可以用來進行json數據的校驗。試想一下這樣的場景,我們需要驗證api返回的json字符串的正確性,但如果一個字段一個字段去校驗效率自然是不高的,這時候jasonsschema就可以大展身手了。
>>> from jsonschema import validate
>>> # A sample schema, like what we'd get from json.load()
>>> schema = {
... "type" : "object",
... "properties" : {
... "price" : {"type" : "number"},
... "name" : {"type" : "string"},
... },
... }
>>> # If no exception is raised by validate(), the instance is valid.
>>> validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema)
>>> validate(
... instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema,
... ) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValidationError: 'Invalid' is not of type 'number'
我們可以自定義schema,如果api返回的結果滿足schema定義的規則的話,那么用例就通過,否則失敗,用例的編寫效率和准確性都可以得到提升。
項目地址:https://github.com/Julian/jsonschema
算法
algorithms:Minimal examples of data structures and algorithms in Python。
庫如其名,用python實現了各種常見算法,實現優雅,例子相對簡單,適合學習。
項目地址:https://github.com/keon/algorithms
命令行工具
howdoi:instant coding answers via the command line
寫代碼的時候經常會不知道某個功能怎么實現或者代碼報錯需要去搜索一下解決方案,但每次打開瀏覽器搜索的話還是比較麻煩的,這時候howdoi就有用武之地了。
howdoi是一個命令行工具,用法就是什么不會搜什么,比如我想用python讀取文件,但不知道怎么寫,那么你可以在命令行里這樣做。
$howdoi python read file
with open('C:/path/numbers.txt') as f:
lines = f.read().splitlines()
沒有任何的廢話,直接給你答案。
項目地址:https://github.com/gleitz/howdoi
thefuck: Magnificent app which corrects your previous console command.
人非聖賢,孰能無過,敲命令行的時候自然是很容易出錯的,這時候你可能需要thefuck,這個工具可以幫你自動的修正錯誤命令並且運行,能較大的提升效率。
項目地址: https://github.com/nvbn/thefuck
db
tinydb
使用json進行持久化的簡單數據庫,提供了完整的持久化,查詢等方案,數據庫文件就是一個.json文件,可以用來實現配置存儲,做一些小工具的開發等。
>>> from tinydb import TinyDB, Query
>>> db = TinyDB('/path/to/db.json')
>>> db.insert({'int': 1, 'char': 'a'})
>>> db.insert({'int': 1, 'char': 'b'})
項目地址: https://github.com/msiemens/tinydb
Deep Learning
tensorflow
最流行的機器學習框架,值得我們去學習和了解。
項目地址: https://github.com/tensorflow/tensorflow
installer
pyinstaller:Freeze (package) Python programs into stand-alone executables
很多同學寫完python腳本以后都想把python腳本打包成exe文件或者是其他可執行文件,然后發給小伙伴們一鍵運行,這時候就可以試試pyinstall庫,支持主流操作系統,推薦給有分發需求的同學。
項目地址: https://github.com/pyinstaller/pyinstaller
Downloader
you-get
命令行下載工具,支持油管和b站,特別是b站可以直接下載一個視頻的所有part,強烈推薦。
Environment Management
關於環境管理就放在一起介紹。
- pyenv - Simple Python version management. 我最常用的安裝python的工具,支持多個python版本共存和切換,強烈推薦。
- virtualenv - A tool to create isolated Python environments. 這個庫可以創建一個虛擬環境,每個虛擬環境里pip安裝的第三方依賴都是隔離的,可以完美解決不同的庫依賴同一個庫的不同版本的問題,也可以讓site pakcage 干凈整潔,適合有潔癖和強迫症的同學。
GUI
Gooey: Turn (almost) any Python command line program into a full GUI application with one line
一個可以將命令行工具轉換成gui的神奇工具,需要的代碼量很少,適合做各種小工具,測試開發同學可以考慮一下。
項目地址: https://github.com/chriskiehl/Gooey
PySimpleGUI
star很高的gui庫,沒用過,不好評論,不過看代碼的描述性很強,推薦有興趣的同學嘗試一下。
import PySimpleGUI as sg # Part 1 - The import
# Define the window's contents
layout = [ [sg.Text("What's your name?")], # Part 2 - The Layout
[sg.Input()],
[sg.Button('Ok')] ]
# Create the window
window = sg.Window('Window Title', layout) # Part 3 - Window Defintion
# Display and interact with the Window
event, values = window.read() # Part 4 - Event loop or Window.read call
# Do something with the information gathered
print('Hello', values[0], "! Thanks for trying PySimpleGUI")
# Finish up by removing from the screen
window.close() # Part 5 - Close the Window
項目地址: https://github.com/PySimpleGUI/PySimpleGUI
html/xml parser
解析html和xml工具很多,我個人用過以下兩個。
- pyquery https://github.com/gawel/pyquery: 提供了類似jquery語法的解析語法,適合像我這樣有上個世代前端開發經驗的同學。
- Beautiful Soup https://www.crummy.com/software/BeautifulSoup/bs4/doc/: 最流行的html/xml解析庫,適合大部分同學和大部分場景。
http client
requests A simple, yet elegant HTTP library.
用起來最舒服也是最流行的python http client,簡單優雅,居家常備。
>>> import requests
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
'{"type":"User"...'
>>> r.json()
{'disk_usage': 368627, 'private_gists': 484, ...}
項目地址: https://github.com/psf/requests
ORM
peewee a small, expressive orm -- supports postgresql, mysql and sqlite
peewee的代碼風格符合直覺,使用簡單,學習成本相對較低,推薦測試開發同學使用。
from peewee import *
import datetime
db = SqliteDatabase('my_database.db')
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
username = CharField(unique=True)
class Tweet(BaseModel):
user = ForeignKeyField(User, backref='tweets')
message = TextField()
created_date = DateTimeField(default=datetime.datetime.now)
is_published = BooleanField(default=True)
項目地址: https://github.com/coleifer/peewee
安全測試
fsociety Hacking Tools Pack – A Penetration Testing Framework
提供一整套解決方案的安全測試框架。
項目地址: https://github.com/Manisso/fsociety
靜態站點生成
pelican Static site generator that supports Markdown and reST syntax. Powered by Python.
python實現的靜態博客生成器,流行度很高,適合有需求的同學。
項目地址: https://github.com/getpelican/pelican
測試庫
pytest https://docs.pytest.org/en/latest/
最強大的python測試框架,特性豐富,功能強大,入門成本低,精通成本高,但基本上你需要的功能這個框架都能提供。
unittest
自帶的測試框架,基本屬於必修課了。
fake2db: create custom test databases that are populated with fake data
構建測試數據庫以及測試數據的庫。
項目地址: https://github.com/emirozer/fake2db
Faker is a Python package that generates fake data for you.
最流行的造數據的庫,很貼心的支持中文。
from faker import Faker
fake = Faker()
fake.name()
# 'Lucy Cechtelar'
fake.address()
# '426 Jordy Lodge
# Cartwrightshire, SC 88120-6700'
項目地址: https://github.com/joke2k/faker
爬蟲
requests-html Pythonic HTML Parsing for Humans
用起來非常簡單順手的爬蟲工具,簡單的爬蟲需求可以用這個。
項目地址: https://github.com/psf/requests-html
pyspider A Powerful Spider(Web Crawler) System in Python.
非常流行的爬蟲框架,適合復雜的爬蟲項目。
from pyspider.libs.base_handler import *
class Handler(BaseHandler):
crawl_config = {
}
@every(minutes=24 * 60)
def on_start(self):
self.crawl('http://scrapy.org/', callback=self.index_page)
@config(age=10 * 24 * 60 * 60)
def index_page(self, response):
for each in response.doc('a[href^="http"]').items():
self.crawl(each.attr.href, callback=self.detail_page)
def detail_page(self, response):
return {
"url": response.url,
"title": response.doc('title').text(),
}
項目地址: https://github.com/binux/pyspider
web開發
- django https://www.djangoproject.com/: python生態最豐富的MVC框架,基本是python web開發的王者。
- flask https://flask.palletsprojects.com/en/1.1.x/: 簡單的web開發框架,上手容易,性能尚可,最適合做簡單的頁面和接口。