關於HTTP協議,我考慮了一下以爲不必再花一節內容來介紹,由於網上關於HTTP協議的介紹很是詳細。本着以儘可能避免介紹一空洞了概念與理論來介紹接口測試,我這裏仍然會給出具體實例。html
在此以前先簡單的介紹一下基本概念:咱們想要打開一個網站,首先是須要往瀏覽器的地址的URL輸入框架中輸入網地址。當我敲下回車後,經過HTTP協議,將網址傳送到域名解析服務器,域名解析服務器根據網址找到對應的IP主機(系統服務器)。這個過程叫request,即請求;當IP主機拿到請求後,將相應的資源返回給用戶瀏覽器。這個過程叫response,即響應。web
當用戶瀏覽器向系統服務器請求時,有幾種方法,最經常使用的就是GET和POST兩種方法。sql
在此咱們來開發這樣一個能夠接收GET和POST請求的web應用。固然,這裏就要求讀者具有必定的web開發基礎了。但不編程語言與web框架不是咱們討論的重點。編程
以flask框架的代碼爲例。json
GET請求 flask
pyfl/瀏覽器
|---- /hello.py安全
|----/templates/服務器
|----|-----------/index.htmlapp
|----|-----------/user.html
hello.py
from flask import Flask,render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") if __name__ == '__main__': app.run(debug=True)
index.html
<h1> This is index page <h1>
啓動flask容器:
經過firebug查看GET請求信息:
固然,這個返回只是一個靜態的頁面,而且不須要任何參數,咱們只須要判斷返回是否爲200便可。
擴充hello.py以下:
from flask import Flask,render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") @app.route("/user/<name>") def user(name): return render_template("user.html",name=name) if __name__ == '__main__': app.run(debug=True)
user.html
<h1> Hell, {{name}} !<h1>
訪問:http://127.0.0.1:5000/user/aaa
相比較來講,這個GET請求就複雜了一些,在請求的時候跟了一些參數(aaa),後臺(hello.py)對參數了進行了接收,而且將其反回到了user.html頁面中。
這個時候,咱們就能夠對這個參數作一些簡單的測試,比較參數爲空,字符,數字,腳本,sql 之類的。其實,安全測試的sql注入也是經過輸參中帶入sql語句入手的。
POST請求
pyfl/
|---- /hello.py
|----/templates/
|----|-----------/index.html
hello.py
from flask import Flask,render_template,request app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") @app.route("/login",methods = ['GET', 'POST']) def login(): if request.method == "POST": username = request.form.get('username') password = request.form.get('password') if username=="zhangsan" and password=="123": return "<h1>welcome, %s !</h1>" %username else: return "<h1>login Failure !</h1>"
else: return "<h1>login Failure !</h1>"
if __name__ == '__main__': app.run(debug=True)
index.html
<form action="/login" method="post"> username: <input type="text" name="username"> password: <input type="password" name="password">
<input type="submit" id="submit">
</form>
輸入用戶名,密碼登陸(後臺hello.py斷定,用戶名爲「zhangsan」,密碼爲「123」登陸成功,其它賬號失敗。)
Python的有一個requests庫,能夠很方便的模擬測試POST請求。
#coding=utf-8
import requests s = requests data={"username":"zhangsan","password":"123",} r = s.post('http://127.0.0.1:5000/login', data) print r.status_code print r.headers['content-type'] print r.encoding print r.text
執行結果:
200 text/html; charset=utf-8 utf-8
<h1>welcome, zhangsan !</h1>
POST接口的測試也同樣,經過不輸入爲空,或錯誤的用戶名密碼,檢查返回的內容。
===================
本文算是入門,可討論的問題還有不少,例如接口返回的是json格式的數據,例如接口爲了安全加了數字簽名。從測試的角度,有哪一個工做能夠模擬這些請求,如何組織和運行測試用例。後面有時間再討論。