Best Python code snippet using tempest_python
test_novnc.py
Source:test_novnc.py  
...45    @classmethod46    def resource_setup(cls):47        super(NoVNCConsoleTestJSON, cls).resource_setup()48        cls.server = cls.create_test_server(wait_until="ACTIVE")49    def _validate_novnc_html(self, vnc_url):50        """Verify we can connect to novnc and get back the javascript."""51        resp = urllib3.PoolManager().request('GET', vnc_url)52        # Make sure that the GET request was accepted by the novncproxy53        self.assertEqual(resp.status, 200, 'Got a Bad HTTP Response on the '54                         'initial call: ' + six.text_type(resp.status))55        # Do some basic validation to make sure it is an expected HTML document56        resp_data = resp.data.decode()57        self.assertIn('<html>', resp_data,58                      'Not a valid html document in the response.')59        self.assertIn('</html>', resp_data,60                      'Not a valid html document in the response.')61        # Just try to make sure we got JavaScript back for noVNC, since we62        # won't actually use it since not inside of a browser63        self.assertIn('noVNC', resp_data,64                      'Not a valid noVNC javascript html document.')65        self.assertIn('<script', resp_data,66                      'Not a valid noVNC javascript html document.')67    def _validate_rfb_negotiation(self):68        """Verify we can connect to novnc and do the websocket connection."""69        # Turn the Socket into a WebSocket to do the communication70        data = self._websocket.receive_frame()71        self.assertFalse(data is None or not data,72                         'Token must be invalid because the connection '73                         'closed.')74        # Parse the RFB version from the data to make sure it is valid75        # and belong to the known supported RFB versions.76        version = float("%d.%d" % (int(data[4:7], base=10),77                                   int(data[8:11], base=10)))78        # Add the max RFB versions supported79        supported_versions = [3.3, 3.8]80        self.assertIn(version, supported_versions,81                      'Bad RFB Version: ' + str(version))82        # Send our RFB version to the server83        self._websocket.send_frame(data)84        # Get the sever authentication type and make sure None is supported85        data = self._websocket.receive_frame()86        self.assertIsNotNone(data, 'Expected authentication type None.')87        data_length = len(data)88        if version == 3.3:89            # For RFB 3.3: in the security handshake, rather than a two-way90            # negotiation, the server decides the security type and sends a91            # single word(4 bytes).92            self.assertEqual(93                data_length, 4, 'Expected authentication type None.')94            self.assertIn(1, [ord_func(data[i]) for i in (0, 3)],95                          'Expected authentication type None.')96        else:97            self.assertGreaterEqual(98                len(data), 2, 'Expected authentication type None.')99            self.assertIn(100                1,101                [ord_func(data[i + 1]) for i in range(ord_func(data[0]))],102                'Expected authentication type None.')103            # Send to the server that we only support authentication104            # type None105            self._websocket.send_frame(six.int2byte(1))106            # The server should send 4 bytes of 0's if security107            # handshake succeeded108            data = self._websocket.receive_frame()109            self.assertEqual(110                len(data), 4,111                'Server did not think security was successful.')112            self.assertEqual(113                [ord_func(i) for i in data], [0, 0, 0, 0],114                'Server did not think security was successful.')115        # Say to leave the desktop as shared as part of client initialization116        self._websocket.send_frame(six.int2byte(1))117        # Get the server initialization packet back and make sure it is the118        # right structure where bytes 20-24 is the name length and119        # 24-N is the name120        data = self._websocket.receive_frame()121        data_length = len(data) if data is not None else 0122        self.assertFalse(data_length <= 24 or123                         data_length != (struct.unpack(">L",124                                         data[20:24])[0] + 24),125                         'Server initialization was not the right format.')126        # Since the rest of the data on the screen is arbitrary, we will127        # close the socket and end our validation of the data at this point128        # Assert that the latest check was false, meaning that the server129        # initialization was the right format130        self.assertFalse(data_length <= 24 or131                         data_length != (struct.unpack(">L",132                                         data[20:24])[0] + 24))133    def _validate_websocket_upgrade(self):134        self.assertTrue(135            self._websocket.response.startswith(b'HTTP/1.1 101 Switching '136                                                b'Protocols\r\n'),137            'Did not get the expected 101 on the websockify call: '138            + six.text_type(self._websocket.response))139        self.assertTrue(140            self._websocket.response.find(b'Server: WebSockify') > 0,141            'Did not get the expected WebSocket HTTP Response.')142    @decorators.idempotent_id('c640fdff-8ab4-45a4-a5d8-7e6146cbd0dc')143    def test_novnc(self):144        body = self.client.get_vnc_console(self.server['id'],145                                           type='novnc')['console']146        self.assertEqual('novnc', body['type'])147        # Do the initial HTTP Request to novncproxy to get the NoVNC JavaScript148        self._validate_novnc_html(body['url'])149        # Do the WebSockify HTTP Request to novncproxy to do the RFB connection150        self._websocket = compute.create_websocket(body['url'])151        # Validate that we succesfully connected and upgraded to Web Sockets152        self._validate_websocket_upgrade()153        # Validate the RFB Negotiation to determine if a valid VNC session154        self._validate_rfb_negotiation()155    @decorators.idempotent_id('f9c79937-addc-4aaa-9e0e-841eef02aeb7')156    def test_novnc_bad_token(self):157        body = self.client.get_vnc_console(self.server['id'],158                                           type='novnc')['console']159        self.assertEqual('novnc', body['type'])160        # Do the WebSockify HTTP Request to novncproxy with a bad token161        url = body['url'].replace('token=', 'token=bad')162        self._websocket = compute.create_websocket(url)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
