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

时间:2020-10-30 16:03:08

标签: django django-channels django-testing channels

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})', consumers.GameConsumer),
        ])

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

        self.assertTrue(connected)

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

        communicator.disconnect()

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

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

0 个答案:

没有答案