作为我的单元测试的一部分,我正在使用奇妙的请求库测试一些响应.你可以用这个库做的很酷的事情就是测试一个200OK状态代码的响应,只需调用:
r = requests.get("http://example.com")
if r:
# success code, do something...
else:
# error code, handle the error.
Run Code Online (Sandbox Code Playgroud)
这种方式在幕后工作的方式是请求更新__bool__()根据状态代码类型返回的响应的协议方法.
我想做的是能够requests.get()足够好地模拟响应对象,这样我不仅可以修补我有兴趣检查(status_code,json())的方法/属性,而且False每当我选择时都可以返回.
以下对我不起作用,因为一旦我r从上面的示例代码调用它,它返回<Mock id='2998569132'>计算结果的Mock对象True.
with mock.patch.object(requests, 'get', return_value=mock.MagicMock(
# False, # didn't work
# __bool__=mock.Mock(return_value=False), # throws AttributeError, might be Python2.7 problem
# ok=False, # works if I call if r.ok: instead, but it's not what I want
status_code=401,
json=mock.Mock(
return_value={
u'error': {
u'code': …Run Code Online (Sandbox Code Playgroud) 我有一个模拟授权API访问的网页.用户输入API URL和授权密钥(假设为"true"或"false").在Go方面,这个路径有一个处理函数,它读取表单并根据授权密钥生成一个令牌.
理想情况下,我想将令牌保存为标头,并根据输入的API网址将请求重定向到正确的处理程序.但是,当我使用http.Redirect()时,我的标头不会作为请求的一部分发送.
func createTokenHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
path := r.FormValue("path")
auth := r.FormValue("auth") // let's say "true" or "false"
w.Header().Set("auth", auth)
http.Redirect(w, r, path, http.StatusFound) // is this the correct http code?
}
// path redirects to this handler
func otherPathHandler(w http.ResponseWriter, r *http.Request) {
// these were necessary for cross-domain requests to work with custom header, keeping them
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "auth")
auth = r.Header.Get("auth")
if auth == "true" {
w.Write([]byte("Validated, here's the API response."))
// …Run Code Online (Sandbox Code Playgroud)