1、自动化
from selenium import webdriver
def test_selenium():
driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
...
driver.quit()
...
2、开始测试平台
from flask import Flask app = Flask(__name__) app.run(port=5000)
@app.route(\'/\')
def index():
"show all projects in workspace dir"
workspace = pathlib.Path(app.root_path) / \'workspace\'
projects = [project.name for project in workspace.iterdir()]
return render_template(\'index.html\', projects=projects)
<h2>展示所有的项目</h2>
{% for p in projects %}
<div>
{{ p }}
<a href="/build?project={{p}}">构建</a>
</div>
{% endfor %}
@app.route("/build", methods=[\'get\', \'post\'])
def build():
project_name = request.args.get(\'project\')
pytest.main([f\'workspace/{project_name}\'])
return "build success"
3、优化
@app.route("/build")
def build():
id = uuid.uuid4().hex
project_name = request.args.get(\'project\')
with open(id, mode=\'w\', encoding=\'utf-8\') as f:
subprocess.Popen(
[\'pytest\', f\'workspace/{project_name}\'],
stdout=f
)
return redirect(f\'/build-history/{id}\')
@app.route("/build-history/<id>")
def build_history(id):
with open(id, encoding=\'utf-8\') as f:
data = f.read()
return data
4、生成器
@app.route("/build", methods=[\'get\', \'post\'])
def build():
id = uuid.uuid4().hex
project_name = request.args.get(\'project\')
with open(id, mode=\'w\', encoding=\'utf-8\') as f:
proc = subprocess.Popen(
[\'pytest\', f\'workspace/{project_name}\'],
stdout=f
)
return redirect(f\'/build-history/{id}?pid={proc.pid}\')
import psutil
@app.route("/build-history/<id>")
def build_history(id):
pid = request.args.get(\'pid\', None)
def stream():
f = open(id, encoding=\'utf-8\')
if not pid:
while True:
data = f.read(100)
if not data:
break
yield data
else:
try:
proc = psutil.Process(pid=int(pid))
except:
return \'no such pid\'
else:
while proc.is_running():
data = f.read(100)
yield data
return Response(stream())
5、总结