Django渠道测试奇怪的数据库行为

问题描述

Django / channels新手:我正在尝试为我的应用程序编写单元测试,但是我从测试中得到了一些奇怪的行为。 我怀疑它与异步代码或Django测试数据库有关,但我迷路了。

我的消费者具有这种结构:

class GameConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['gameID']
        self.room_group_name = 'game_%s' % self.room_name

        # check something from database to decide if this connection should be rejected
        if not await self.does_game_exists():
            await self.close(4001)
        else:
            await self.accept()
            await self.channel_layer.group_add(
                self.room_group_name,self.channel_name
            )
            
            # insert data into db
            await self.add_player_to_game()
            

    @database_sync_to_async
    def does_game_exists(self):
        ....

    @database_sync_to_async
    def add_player_to_game(self):
        ....

这在正常使用应用程序时有效;数据插入到数据库中。

现在进行单元测试:

class WSConsumerTest(TransactionTestCase):
    fixtures = ['test-data.yaml']

    @database_sync_to_async
    def get_num_players(self):
        ...

    @database_sync_to_async
    def create_test_game(self):
        ...

    async def test_player_is_added_on_successful_connection(self):
        game = await self.create_test_game()

        application = URLRouter([
            url(r'ws/game/(?P<gameID>[a-zA-Z0-9]{6})',consumers.GameConsumer),])

        communicator = WebsocketCommunicator(application,f"/ws/game/{game.gameID}")
        connected,_ = await communicator.connect()

        player_count = await self.get_num_players()
        self.assertEqual(player_count,1,"Player is not added in database after successful connection")

        communicator.disconnect()

这失败。 get_num_players返回由create_test_game创建的游戏实例中的玩家人数。我确定这两个函数是正确的,它们是标准的django ORM查询

我尝试使用--keepdb选项运行测试,并且数据库为空,甚至没有创建测试游戏条目。

我在做什么错? 感谢您的建议。

编辑

通过修改测试

async def test_player_is_added_on_successful_connection(self):
        game = await self.create_test_game()

        application = URLRouter([
            url(r'ws/game/(?P<gameID>[a-zA-Z0-9]{6})',_ = await communicator.connect()

        self.assertTrue(connected)

        player_count = await self.get_num_players()
        self.assertEqual(player_count,"Player is not added in database after successful connection")

        communicator.disconnect()

由于连接被拒绝,测试失败。它被拒绝,因为使用者在db中找不到游戏条目;但是如果我以测试方法数据库搜索游戏,就会找到游戏。

测试和使用者使用不同的数据库吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...