Skip to content
Myr

test_testserver.py

This file

Path

tests/test_testserver.py

196 lines · 6.7 KiB · Python

Last changed by

Merge pull request #4976 from eduardomourar/feature/strip-utf8-bomKenneth Reitzbefore adoptiona71e224

History of this file

Take it

1# -*- coding: utf-8 -*-23import threading4import socket5import time67import pytest8import requests9from tests.testserver.server import Server101112class TestTestServer:1314    def test_basic(self):15        """messages are sent and received properly"""16        question = b"success?"17        answer = b"yeah, success"1819        def handler(sock):20            text = sock.recv(1000)21            assert text == question22            sock.sendall(answer)2324        with Server(handler) as (host, port):25            sock = socket.socket()26            sock.connect((host, port))27            sock.sendall(question)28            text = sock.recv(1000)29            assert text == answer30            sock.close()3132    def test_server_closes(self):33        """the server closes when leaving the context manager"""34        with Server.basic_response_server() as (host, port):35            sock = socket.socket()36            sock.connect((host, port))3738            sock.close()3940        with pytest.raises(socket.error):41            new_sock = socket.socket()42            new_sock.connect((host, port))4344    def test_text_response(self):45        """the text_response_server sends the given text"""46        server = Server.text_response_server(47            "HTTP/1.1 200 OK\r\n" +48            "Content-Length: 6\r\n" +49            "\r\nroflol"50        )5152        with server as (host, port):53            r = requests.get('http://{}:{}'.format(host, port))5455            assert r.status_code == 20056            assert r.text == u'roflol'57            assert r.headers['Content-Length'] == '6'5859    def test_text_bom_response(self):60        """the text_response_server sends the given text with UTF-8 BOM"""61        server = Server.text_response_server(62            "HTTP/1.1 200 OK\r\n" +63            "Content-Type: text/html; charset=UTF-8\r\n" +64            u'\r\n\ufeff<doctype html><html><body>ジェーピーニック</body></html>'65        )6667        with server as (host, port):68            r = requests.get('http://{}:{}'.format(host, port))6970            assert r.status_code == 20071            assert r.text == u'<doctype html><html><body>ジェーピーニック</body></html>'72            assert r.headers['Content-Type'] == 'text/html; charset=UTF-8'7374    def test_json_bom_response(self):75        """the text_response_server sends the given JSON with UTF-8 BOM"""76        server = Server.text_response_server(77            "HTTP/1.1 200 OK\r\n" +78            "Content-Type: application/json; charset=utf-8\r\n" +79            u'\r\n\ufeff{"success": true}'80        )8182        with server as (host, port):83            r = requests.get('http://{}:{}'.format(host, port))8485            assert r.status_code == 20086            assert r.json() == {'success': True}87            assert r.headers['Content-Type'] == 'application/json; charset=utf-8'8889    def test_basic_response(self):90        """the basic response server returns an empty http response"""91        with Server.basic_response_server() as (host, port):92            r = requests.get('http://{}:{}'.format(host, port))93            assert r.status_code == 20094            assert r.text == u''95            assert r.headers['Content-Length'] == '0'9697    def test_basic_waiting_server(self):98        """the server waits for the block_server event to be set before closing"""99        block_server = threading.Event()100101        with Server.basic_response_server(wait_to_close_event=block_server) as (host, port):102            sock = socket.socket()103            sock.connect((host, port))104            sock.sendall(b'send something')105            time.sleep(2.5)106            sock.sendall(b'still alive')107            block_server.set()  # release server block108109    def test_multiple_requests(self):110        """multiple requests can be served"""111        requests_to_handle = 5112113        server = Server.basic_response_server(requests_to_handle=requests_to_handle)114115        with server as (host, port):116            server_url = 'http://{}:{}'.format(host, port)117            for _ in range(requests_to_handle):118                r = requests.get(server_url)119                assert r.status_code == 200120121            # the (n+1)th request fails122            with pytest.raises(requests.exceptions.ConnectionError):123                r = requests.get(server_url)124125    @pytest.mark.skip(reason="this fails non-deterministically under pytest-xdist")126    def test_request_recovery(self):127        """can check the requests content"""128        # TODO: figure out why this sometimes fails when using pytest-xdist.129        server = Server.basic_response_server(requests_to_handle=2)130        first_request = b'put your hands up in the air'131        second_request = b'put your hand down in the floor'132133        with server as address:134            sock1 = socket.socket()135            sock2 = socket.socket()136137            sock1.connect(address)138            sock1.sendall(first_request)139            sock1.close()140141            sock2.connect(address)142            sock2.sendall(second_request)143            sock2.close()144145        assert server.handler_results[0] == first_request146        assert server.handler_results[1] == second_request147148    def test_requests_after_timeout_are_not_received(self):149        """the basic response handler times out when receiving requests"""150        server = Server.basic_response_server(request_timeout=1)151152        with server as address:153            sock = socket.socket()154            sock.connect(address)155            time.sleep(1.5)156            sock.sendall(b'hehehe, not received')157            sock.close()158159        assert server.handler_results[0] == b''160161    def test_request_recovery_with_bigger_timeout(self):162        """a biggest timeout can be specified"""163        server = Server.basic_response_server(request_timeout=3)164        data = b'bananadine'165166        with server as address:167            sock = socket.socket()168            sock.connect(address)169            time.sleep(1.5)170            sock.sendall(data)171            sock.close()172173        assert server.handler_results[0] == data174175    def test_server_finishes_on_error(self):176        """the server thread exits even if an exception exits the context manager"""177        server = Server.basic_response_server()178        with pytest.raises(Exception):179            with server:180                raise Exception()181182        assert len(server.handler_results) == 0183184        # if the server thread fails to finish, the test suite will hang185        # and get killed by the jenkins timeout.186187    def test_server_finishes_when_no_connections(self):188        """the server thread exits even if there are no connections"""189        server = Server.basic_response_server()190        with server:191            pass192193        assert len(server.handler_results) == 0194195        # if the server thread fails to finish, the test suite will hang196        # and get killed by the jenkins timeout.