Passed
Push — main ( 5f8723...49d37f )
by Jochen
01:39
created

tests.httpreceiver.test_receive_server   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 43
dl 0
loc 74
rs 10
c 0
b 0
f 0

6 Functions

Rating   Name   Duplication   Size   Complexity  
A test_receive_server_without_channel() 0 10 2
A server() 0 11 1
A test_receive_server_with_valid_request() 0 10 1
A test_receive_server_without_text() 0 10 2
A build_request() 0 4 1
A get_server_url() 0 3 1
1
"""
2
:Copyright: 2007-2020 Jochen Kupperschmidt
3
:License: MIT, see LICENSE for details.
4
"""
5
6
import json
7
from threading import Thread
8
from urllib.error import HTTPError
9
from urllib.request import Request, urlopen
10
11
import pytest
12
13
from weitersager.httpreceiver import ReceiveServer
14
15
16
@pytest.fixture
17
def server():
18
    address = ('', 0)  # Bind to localhost on random user port.
19
    server = ReceiveServer(*address)
20
21
    thread = Thread(target=server.handle_request)
22
    thread.start()
23
24
    yield server
25
26
    thread.join()
27
28
29
def test_receive_server_with_valid_request(server):
30
    data = {
31
        'channel': '#party',
32
        'text': 'Limbo!',
33
    }
34
    request = build_request(server, data)
35
36
    response = urlopen(request)
37
38
    assert response.code == 202
39
40
41
def test_receive_server_without_channel(server):
42
    data = {
43
        'text': 'Which channel is this?!',
44
    }
45
    request = build_request(server, data)
46
47
    with pytest.raises(HTTPError) as excinfo:
48
        response = urlopen(request)
49
50
    assert excinfo.value.code == 400
51
52
53
def test_receive_server_without_text(server):
54
    data = {
55
        'channel': '#silence',
56
    }
57
    request = build_request(server, data)
58
59
    with pytest.raises(HTTPError) as excinfo:
60
        response = urlopen(request)
61
62
    assert excinfo.value.code == 400
63
64
65
def build_request(server, data):
66
    url = get_server_url(server)
67
    json_data = json.dumps(data).encode('utf-8')
68
    return Request(url, data=json_data, method='POST')
69
70
71
def get_server_url(server):
72
    server_host, server_port = server.server_address
73
    return f'http://{server_host}:{server_port}/'
74