当前位置: 首页 > 面试题库 >

带有selenium测试的Django通道2失败

祁刚毅
2023-03-14
问题内容

我正在尝试遵循Django频道教程。我能够实现此处所述的聊天功能。但是从此页面粘贴的单元测试完全复制失败,并出现以下错误AttributeError: Can't pickle local object 'DaphneProcess.__init__.<locals>.<lambda>'

完整回溯:

Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\django_channels_test\venv35\lib\site-packages\django\test\testcases.py", line 202, in __call__
    self._pre_setup()
  File "C:\Users\user\PycharmProjects\django_channels_test\venv35\lib\site-packages\channels\testing\live.py", line 42, in _pre_setup
    self._server_process.start()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\context.py", line 212, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\context.py", line 313, in _Popen
    return Popen(process_obj)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\popen_spawn_win32.py", line 66, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35\Lib\multiprocessing\reduction.py", line 59, in dump
    ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'DaphneProcess.__init__.<locals>.<lambda>'

我的消费阶层:

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

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))

我的测试模块:

from channels.testing import ChannelsLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait


class ChatTests(ChannelsLiveServerTestCase):
    serve_static = True  # emulate StaticLiveServerTestCase

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        try:
            # NOTE: Requires "chromedriver" binary to be installed in $PATH
            cls.driver = webdriver.Chrome()
        except:
            super().tearDownClass()
            raise

    @classmethod
    def tearDownClass(cls):
        cls.driver.quit()
        super().tearDownClass()

    def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self):
        try:
            self._enter_chat_room('room_1')

            self._open_new_window()
            self._enter_chat_room('room_1')

            self._switch_to_window(0)
            self._post_message('hello')
            WebDriverWait(self.driver, 2).until(lambda _:
                'hello' in self._chat_log_value,
                'Message was not received by window 1 from window 1')
            self._switch_to_window(1)
            WebDriverWait(self.driver, 2).until(lambda _:
                'hello' in self._chat_log_value,
                'Message was not received by window 2 from window 1')
        finally:
            self._close_all_new_windows()

    def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self):
        try:
            self._enter_chat_room('room_1')

            self._open_new_window()
            self._enter_chat_room('room_2')

            self._switch_to_window(0)
            self._post_message('hello')
            WebDriverWait(self.driver, 2).until(lambda _:
                'hello' in self._chat_log_value,
                'Message was not received by window 1 from window 1')

            self._switch_to_window(1)
            self._post_message('world')
            WebDriverWait(self.driver, 2).until(lambda _:
                'world' in self._chat_log_value,
                'Message was not received by window 2 from window 2')
            self.assertTrue('hello' not in self._chat_log_value,
                'Message was improperly received by window 2 from window 1')
        finally:
            self._close_all_new_windows()

    # === Utility ===

    def _enter_chat_room(self, room_name):
        self.driver.get(self.live_server_url + '/chat/')
        ActionChains(self.driver).send_keys(room_name + '\n').perform()
        WebDriverWait(self.driver, 2).until(lambda _:
            room_name in self.driver.current_url)

    def _open_new_window(self):
        self.driver.execute_script('window.open("about:blank", "_blank");')
        self.driver.switch_to.window(self.driver.window_handles[-1])

    def _close_all_new_windows(self):
        while len(self.driver.window_handles) > 1:
            self.driver.switch_to.window(self.driver.window_handles[-1])
            self.driver.execute_script('window.close();')
        if len(self.driver.window_handles) == 1:
            self.driver.switch_to.window(self.driver.window_handles[0])

    def _switch_to_window(self, window_index):
        self.driver.switch_to.window(self.driver.window_handles[window_index])

    def _post_message(self, message):
        ActionChains(self.driver).send_keys(message + '\n').perform()

    @property
    def _chat_log_value(self):
        return self.driver.find_element_by_css_selector('#chat-log').get_property('value')

我正在使用Python 3.5和Django 2.0。


问题答案:

reduction.py无法序列化包含lambda的对象。经过一些研究,这似乎与Windows环境中的多处理问题有关(并且不仅限于此示例)。

解决此问题的一种方法是 reduction.py

替换import pickleimport dill as pickle

莳萝包可以在腌制失败的地方序列化这些对象。但是,在不深入研究以确保此更改不会破坏其他任何内容的情况下,我不建议在生产环境中使用此功能。



 类似资料:
  • 问题内容: 在使用selenium(没有远程,没有xvfb)运行django测试时,我总是得到以下异常: 使用django 1.4和带有Firefox WebDriver的seleniumpython-bindings 2.28.0在LiveServerTestCase上运行测试。有人对如何解决有想法吗? 问题答案: 确保请求页面的浏览器正在等待响应。 如果我没记错的话,有和命令,请确保您正在使用

  • 问题内容: 我用Java进行了selenium测试,并且正在做一些断言: 这是Selenium从IDE导出到Java Webdriver时生成的标准方法。 (是的,我想断言该元素不存在) 在上述代码行中进行测试时,我总是会收到错误消息:错误的元素引用:元素未附加到DOM 但是,当我在该步骤之前放置一个thread.sleep时,它可以工作。我没有得到的事实是,等待1毫秒就足够了。在断言之前等待通常

  • 一个“通过”测试但配置失败的示例。 失败的配置:@afterclass tearDown java.lang.assertionerror:java.lang.assertionerror:expected[true],但在)在org.testng.internal.MethodInvocationHelper.invokeMethodCommissioningTimeout(methodInvo

  • 当我尝试执行一个新的单元测试用例时,它会显示以下错误。 注意:我没有特权设置路径,因为我已经将chrome web驱动程序放在D驱动器中。 测试在14:56开始。。。C:\Users\xxx.xxxx\PyCharm项目\Automation\venv\Scripts\python.exe“C:\Users\xx.xxx\AppData\Local\JetBrains\PyCharm社区版2019

  • 当我试图在Selenium Grid 2旁边使用TestNG并行运行测试时,我似乎遇到了一个问题。 尽管打开的浏览器数量与我正在运行的测试数量相匹配,但所有测试的所有指令都被发送到同一个浏览器窗口。例如,每个测试都会打开一个页面并尝试登录。四个浏览器窗口将打开,但一个浏览器窗口将导航到登录页面四次,然后键入用户名四次,而其余的浏览器窗口保持不活动。 以下是我如何启动网格: xml套件是这样设置的:

  • 问题内容: 我已经使用Angular 2 CLI构建了Angular 2项目,并能够使用本教程将应用程序部署到Heroku 。 现在,我想为应用程序的不同环境(开发,登台,生产等)创建管道。 在我的package.json中,它将创建我的代码的生产版本,我的应用程序将在此版本上运行。有没有一种方法可以根据我在Heroku设置中的设置进行更改?例如,它将针对开发环境或登台环境。还是我需要以其他方式设