views:

268

answers:

2

I'm following the instructions from this post but cannot get my methods recognized globally.

The error message:

ERROR: test_suggest_performer (__builtin__.TestSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "applications/myapp/tests/test_search.py", line 24, in test_suggest_performer
    suggs = suggest_flavors("straw")
NameError: global name 'suggest_flavors' is not defined

My test file:

import unittest

from gluon.globals import Request
db = test_db

execfile("applications/myapp/controllers/search.py", globals())

class TestSearch(unittest.TestCase):
    def setUp(self):
        request = Request()

    def test_suggest_flavors(self):
        suggs = suggest_flavors("straw")
        self.assertEqual(len(suggs), 1)
        self.assertEqual(suggs[0][1], 'Strawberry')

My controller:

def suggest_flavors(term):
    return [] 

Has anyone successfully completed unit testing like this in web2py?

+1  A: 

Please see: http://web2py.com/AlterEgo/default/show/260

Note that in your example the function 'suggest_flavors' should be defined at 'applications/myapp/controllers/search.py'.

Alvaro Justen
Thanks! I had forgotten that I had the real logic one more layer deep in a module. Instead of 'controllers/search.py' I used 'myapp/search.py'.
Wraith
A: 

I don't have any experience with web2py, but used other frameworks a lot. And looking at your code I'm confused a bit. Is there an objective reason why execfile should be used? Isn't it better to use regular import statement. So instead of execfile you may write:

from applications.myapp.controllers.search import suggest_flavors

It's more clear code for pythoners.

Note, that you should place __init__.py in each directory along the path in this case, so that dirs will form package/module hierarchy.

nailxx
web2py works a bit differently because it loads some things globally. execfile "executes your controller file, bringing all of the function declarations into the local namespace. Passing globals() to the execfile() command lets your controllers see your database."
Wraith