Given a simple Flask app in main.py
:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hi():
return 'hi', 200
I want to write a unit test for it, but I'm not sure how to import main.py
into test.py
. I get NameError: name 'app' is not defined
for the code below.
import unittest
class MyTestCase(unittest.TestCase):
def test_hi(self):
self.app = app.test_client()
r = self.app.get('/')
assert b'hi' in r.data
Is there a way to write this test while keeping the same directory structure (basically main.py
and test.py
in the same directory)?
If both of your files are in the same folder, then your test file just needs to import the app from the main
module:
import unittest
from main import app
class MyTestCase(unittest.TestCase):
def test_hi(self):
self.app = app.test_client()
r = self.app.get('/')
assert b'hi' in r.data
=>
python -m unittest test.py
.
----------------------------------------------------------------------
Ran 1 test in 0.009s
OK
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.