Completed
Pull Request — master (#7)
by Paolo
01:37
created

tests.test_client.RootTest.mocked_get_submission()   C

Complexity

Conditions 10

Size

Total Lines 63
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 44
nop 2
dl 0
loc 63
rs 5.9999
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like tests.test_client.RootTest.mocked_get_submission() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
"""
4
Created on Fri Dec 20 11:53:11 2019
5
6
@author: Paolo Cozzi <[email protected]>
7
"""
8
9
import os
10
import json
11
import datetime
12
13
from unittest.mock import patch, Mock
14
from unittest import TestCase
15
16
from pyUSIrest.auth import Auth
17
from pyUSIrest.client import Client
18
from pyUSIrest.settings import ROOT_URL
19
from pyUSIrest.exceptions import USIConnectionError, TokenExpiredError
20
21
from .common import DATA_PATH
22
from .test_auth import generate_token
23
24
25
class ClientTest(TestCase):
26
    @classmethod
27
    def setup_class(cls):
28
        cls.mock_get_patcher = patch('requests.Session.get')
29
        cls.mock_get = cls.mock_get_patcher.start()
30
31
    @classmethod
32
    def teardown_class(cls):
33
        cls.mock_get_patcher.stop()
34
35
    def test_with_tocken_str(self):
36
        token = generate_token()
37
        client = Client(token)
38
        self.assertFalse(client.auth.is_expired())
39
40
    def test_with_auth_object(self):
41
        token = generate_token()
42
        auth = Auth(token=token)
43
        client = Client(auth)
44
        self.assertFalse(client.auth.is_expired())
45
46
    def test_expired_tocken(self):
47
        now = int(datetime.datetime.now().timestamp())
48
49
        token = generate_token(now=now-10000)
50
        client = Client(token)
51
52
        # do a generic request and get error
53
        self.assertRaisesRegex(
54
            TokenExpiredError,
55
            "Your token is expired",
56
            client.get,
57
            "https://submission-test.ebi.ac.uk/api/"
58
        )
59
60
    def test_server_error(self):
61
        """Deal with the generic 50x states"""
62
63
        token = generate_token()
64
        client = Client(token)
65
66
        # create a mock response
67
        response = Mock()
68
        response.status_code = 500
69
        response.text = (
70
            '<!DOCTYPE html>\n<html>\n<body>\n<meta http-equiv="refresh" '
71
            'content=\'0;URL=http://www.ebi.ac.uk/errors/failure.html\'>\n'
72
            '</body>\n</html>\n')
73
74
        self.mock_get.return_value = response
75
76
        self.assertRaisesRegex(
77
            USIConnectionError,
78
            "Problems with API endpoints",
79
            client.get,
80
            ROOT_URL
81
        )
82
83
    def test_get(self):
84
        """Testing a get method"""
85
86
        # create a mock response
87
        with open(os.path.join(DATA_PATH, "root.json")) as handle:
88
            data = json.load(handle)
89
90
        self.mock_get.return_value = Mock()
91
        self.mock_get.return_value.json.return_value = data
92
        self.mock_get.return_value.status_code = 200
93
94
        token = generate_token()
95
        client = Client(token)
96
97
        response = client.get(ROOT_URL, headers={'new_key': 'new_value'})
98
99
        self.assertIsInstance(response.json(), dict)
100
101
    def test_get_with_errors(self):
102
        """Deal with problems with getting URL (no 200 status code)"""
103
104
        # create a mock response
105
        response = Mock()
106
        response.status_code = 404
107
        response.text = (
108
            '<h1>Not Found</h1><p>The requested resource was not found on '
109
            'this server.</p>')
110
111
        token = generate_token()
112
        client = Client(token)
113
114
        self.mock_get.return_value = response
115
116
        self.assertRaisesRegex(
117
            USIConnectionError,
118
            "Not Found",
119
            client.get,
120
            ROOT_URL + "/meow"
121
        )
122