CKAN - 将会话绑定到测试文件中的数据库



我正在尝试测试我编写的 CKAN 扩展。基本上,我想测试给定某些参数的函数是否成功查询数据库并返回正确的数据。但是我收到此错误:

未绑定执行错误:找不到映射器映射器|用户|用户、SQL 表达式或此会话

这是测试:导入单元测试从 ckanext.matcher 导入插件

class MatcherPluginTest(unittest.TestCase):
def setUp(self):
    # Create instances
    self.plugin_instance = plugin.MatcherPlugin()
def test_func_call(self):
    user_account = ’testUser'
    user_ckan = self.plugin_instance.get_ckanuser(user_account)
    self.assertEqual(user_ckan['display_name'], 'Shani Agent')
if __name__ == '__main__':
    unittest.main()

根据我的研究,此错误是由于会话变量未附加到或绑定到数据库造成的。所以我尝试按如下方式创建一个会话,但仍然收到与上述相同的错误:

    def setUp(self):
        self.plugin_instance = plugin.MatcherPlugin()
        self.engine = create_engine('postgresql://...')
        self.Session = sessionmaker(bind=self.engine)
        self.session = self.Session()
    def test_func_call(self):
        user_account = ’testUser'
        user_ckan = self.session.add(self.plugin_instance.get_ckanuser(user_account))
        self.session.commit()
        self.assertEqual(user_ckan['display_name'], 'Shani Agent')

下面是在test_func_call测试中调用的get_ckanuser函数:

    def get_ckanuser(self, user):
      import ckan.model
      user_ckan = ckan.model.User.by_name(user)
      # If the user exists, return user dictionary, else, return None
      if user_ckan:
          user_dict = toolkit.get_action('user_show')(data_dict={'id': user_ckan.id})
          return user_dict
      else:
          return None 

有没有办法将会话绑定到测试文件中的数据库?

数据库会话和一般 Pylons 必需品由 nosetests Pylons 插件设置。因此,您需要使用鼻测试并使用其--with-pylons=../ckan/test-core.ini参数。

这方面的文档在这里:http://docs.ckan.org/en/latest/contributing/test.html#run-the-tests

还有一件事,没有必要改变,但是对于nosetests,编写测试的首选风格略有不同。您可以在主 CKAN 代码库中找到示例测试,或者例如在此处:https://github.com/datagovuk/ckanext-dgu/blob/master/ckanext/dgu/tests/functional/test_api.py