1

我的 Flask 应用程序上有一个测试装置,它启动开发服务器来测试一些用户交互。对于第一个测试,我只想确保服务器已启动。一般情况下执行此操作的最佳方法是什么(无需测试特定响应代码)?我希望我可以使用self.assertTrue(response),但即使我更改了端口,这似乎也通过了。

这是有问题的测试用例:

class TestAuth(TestCase):

    def create_app(self):
        db.init_app(app)
        return app

    @classmethod
    def setUpClass(cls):
        cls.server_proc = subprocess.Popen(
            [sys.executable, 'run.py'],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)
        time.sleep(5)

    @classmethod
    def TearDownLcass(cls):
        os.kill(cls.server_proc.pid, signal.SIGINT)

    def setUp(self):
        selenium_logger = logging.getLogger(
            'selenium.webdriver.remote.remote_connection')
        selenium_logger.setLevel(logging.WARN)
        self.browser = webdriver.Firefox()

        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.browser.quit()

    def test_server_up(self):
        response = self.client.get('http://localhost:5000/')
        self.assertTrue(response)
4

2 回答 2

2

您可以使用Requests向自己发送请求,甚至可以使用 urllib2。启动您的开发服务器并从另一个指向您的 ip:port 的实例发出请求。

于 2013-08-30T18:29:59.990 回答
1

You are mixing up two different ways to test.

The testing style exposed by Flask-Testing does not require a separate server to be started. The self.client.get call does not really request a URL from a server, it just routes requests internally into the same process that is running the test.

If you want to work with a separate server, then you cannot use self.client to request URLs, in that case you have to use a proper HTTP client. It seems you already instantiated a Selenium browser, so that would work just fine. Replace self.client.get() with self.browser.get().

If, on the other side, you don't specifically want to start a separate web server and are okay testing your app using the default facilities provided by Flask and Flask-Testing, then remove all the server process start up code and the Selenium stuff and just use self.client to make requests. But be aware that self.client is not a real web client, so there is no point in testing if the server is up, because there is no server when testing this way.

于 2013-09-01T19:17:13.720 回答