Turbogears quirks when testing controllers that use SingleSelectField
Suppose you have a User
that can be a member of a Company. In SQLObject you
model it somehow like this:
class Company(SQLObject): name = UnicodeCol(length=16, alternateID=True, alternateMethodName="by_name") display_name = UnicodeCol(length=255) class User(InheritableSQLObject): company = ForeignKey("Company", notNull=False, cascade='null')
Then you want to make a form that allows to choose what is the company of a user:
def companies(): return [ [ -1, 'None' ] ] + [ [c.id, c.display_name] for c in Company.select() ] class NewUserFields(WidgetsList): """Fields for editing general settings""" user_name = TextField(label="User name") companyID = SingleSelectField(label="Company", options=companies)
Ok. Now you want to run tests:
nosetests
imports the controller to see if there's any initialisation code.- The NewUserFields class is created.
- The SingleSelectField is created.
- The SingleSelectField constructor tries to guess the validator and peeks at the first option.
- This calls
companies
. companies
accesses the database.- The testing database has not yet been created because nosetests imported the module before giving the test code a chance to setup the test database.
- Bang.
The solution is to add an explicit validator to disable this guessing code that is a source of so many troubles:
class NewUserFields(WidgetsList): """Fields for editing general settings""" user_name = TextField(label="User name") companyID = SingleSelectField(label="Company", options=companies, validator=v.Int(not_empty=True))