简体   繁体   中英

How do I unit test Django views on the Google App Engine?

I am struggling to run unit tests using the Django Client class on the Google App Engine. I downloaded GAEUnit (v2.0a for Django) and I am trying to use that as my testing framework (maybe I should rather be using something else?)

I copy all the GAEUnit files into my project root as instructed, and I modify my app.yaml file. Currently app.yaml looks as follows:

application: myapp
version: 1
runtime: python
api_version: 1

handlers:
- url: /static
  static_dir: static

- url: /.*
  script: django_bootstrap.py

- url: /test.*
  script: gaeunit.py

I also modified settings.py to add gaeunit as an application... (snippet from settings.py)

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'gaeunit',
)

My unit test class resides in the 'test' folder and looks as follows (very simple):

import unittest

class Test(unittest.TestCase):

    def testName(self):
        self.assertTrue(False)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

However, when I try to run my application by navigating to http://localhost:8080 , it fails with the following error:

ViewDoesNotExist at /
Could not import gaeunit.gaeunit. Error was: No module named gaeunit

gaeunit.py does definitely exist in the folder. What am I doing wrong?

I managed to figure out what was wrong here. I made two mistakes:

  1. In app.yaml , url: /test.* had to be before url:/.* (otherwise the /test URL would be matched to /.* before getting to the /test.* handler)
  2. Beware of copying all the files from the GAEUnit package into your project root! The GAEUnit folder contains a urls.py file that will overwrite your one if you are not paying attention. This was happening in my case. I simply restored my original urls.py.
  3. When working with the django test Client , and if you intend to access the response.template or response.context properties, you need to ensure that you call django.test.utils.setup_test_environment() , otherwise template and context will be Nothing . I call this in my test module, right at the bottom.

Result: working unit tests!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM