web接口测试之GET与POST请求

  关于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容器:

 

访问:http://127.0.0.1:5000/

经过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>

访问:http://127.0.0.1:5000/

输入用户名,密码登陆(后台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格式的数据,例如接口为了安全加了数字签名。从测试的角度,有哪一个工做能够模拟这些请求,如何组织和运行测试用例。后面有时间再讨论。

相关文章
相关标签/搜索