擅长:python、mysql、java
<p>如果愿意,也可以将<code>header</code>参数传递给<code>test_request_context</code>。在</p>
<p>示例:</p>
<pre class="lang-py prettyprint-override"><code>from flask import Flask, request
import unittest
app = Flask(__name__)
app.debug = True
app.testing = True
@app.route('/')
def index():
return str(request.remote_addr)
class TestApp(unittest.TestCase):
def test_headers(self):
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0"
ip_address = 127.0.0.1
headers = {
'Remote_Addr': ip_address,
'User_Agent': user_agent
}
with self.test_request_context(headers=headers):
# Do something
pass
</code></pre>
<p>当您需要使用其他模块中的<code>request</code>对象执行多个单元测试时,这很有用。在</p>
<p>参见<a href="https://flask.palletsprojects.com/en/1.0.x/testing/#other-testing-tricks" rel="nofollow noreferrer">test_request_context documentation</a>。在</p>