Unittesting cherrypy webapp

后端 未结 3 1330
囚心锁ツ
囚心锁ツ 2021-02-02 18:16

I recently had to rewrite our rest api, and made the switch from Flask to Cherrypy (mostly due to Python 3 compatibility). But now I\'m stuck trying to write my unit tests, Flas

3条回答
  •  青春惊慌失措
    2021-02-02 18:42

    It seems that there is an alternate way to perform unittest. I just found and check the following recipe which works fine with cherrypy 3.5.

    http://docs.cherrypy.org/en/latest/advanced.html#testing-your-application

        import cherrypy
    
        from cherrypy.test import helper
    
        class SimpleCPTest(helper.CPWebCase):
            def setup_server():
                class Root(object):
                    @cherrypy.expose
                    def echo(self, message):
                        return message
    
                cherrypy.tree.mount(Root())
            setup_server = staticmethod(setup_server)
    
            def test_message_should_be_returned_as_is(self):
                self.getPage("/echo?message=Hello%20world")
                self.assertStatus('200 OK')
                self.assertHeader('Content-Type', 'text/html;charset=utf-8')
                self.assertBody('Hello world')
    
            def test_non_utf8_message_will_fail(self):
                """
                CherryPy defaults to decode the query-string
                using UTF-8, trying to send a query-string with
                a different encoding will raise a 404 since
                it considers it's a different URL.
                """
                self.getPage("/echo?message=A+bient%F4t",
                             headers=[
                                 ('Accept-Charset', 'ISO-8859-1,utf-8'),
                                 ('Content-Type', 'text/html;charset=ISO-8859-1')
                             ]
                )
                self.assertStatus('404 Not Found')
    

提交回复
热议问题