Passed
Branch master (dfca16)
by Emmanuel
01:28
created

TestQueueManager.test_queue_valid()   B

Complexity

Conditions 6

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 29
rs 7.5384
cc 6
1
import unittest
2
import os
3
import redis
4
import sys
5
6
from impulsare_config import Reader
7
from redis.exceptions import ConnectionError
8
9
from impulsare_distributer import QueueManager
10
base_dir = os.path.abspath(os.path.dirname(__file__))
11
sys.path.insert(0, os.path.abspath(base_dir + '/../'))
12
13
14
def fake_print(message: str, job: str):
15
    print('Message: {}'.format(message))
16
    print('Job: {}'.format(job))
17
18
19
# https://docs.python.org/3/library/unittest.html#assert-methods
20
class TestQueueManager(unittest.TestCase):
21
    def test_init_queue_invalid_conf(self):
22
        with self.assertRaisesRegex(ValueError, "Your config is not valid: 'host' is a required property"):
23
            QueueManager(base_dir + '/static/config_invalid.yml', 'testqueue')
24
25
26
    def test_init_queue_missing_subkey_queue(self):
27
        with self.assertRaisesRegex(KeyError, "You must have a key testqueue in your config with a sub-key queue"):
28
            QueueManager(base_dir + '/static/config_missing_queue.yml', 'testqueue')
29
30
31
    def test_queue_invalid_server(self):
32
        with self.assertRaisesRegex(ConnectionError, "Error.*connecting to abc:6379.*"):
33
            q = QueueManager(base_dir + '/static/config_wrong_server.yml', 'testqueue')
34
            q.add('Hello world', fake_print, 'test')
35
36
37
    def test_queue_valid(self):
38
        host = '127.0.0.1'
39
        if 'REDIS' in os.environ and os.environ['REDIS'] is not None:
40
            host = os.environ['REDIS']
41
42
        con = redis.StrictRedis(host=host)
43
        # Clean
44
        items = con.keys('rq:*')
45
        for item in items:
46
            con.delete(item)
47
        items = con.keys('rq:*')
48
        self.assertEqual(len(items), 0)
49
50
        config_file = base_dir + '/static/config_valid.yml'
51
        # Use another server, make sure to have the right configuration file
52
        if host != '127.0.0.1':
53
            config_file = base_dir + '/static/config_valid_{}.yml'.format(host)
54
55
        try:
56
            q = QueueManager(config_file, 'testqueue')
57
            job = q.add('Hello world', fake_print, 'test')
58
        except ConnectionError:
59
            print('Be careful to set the right server in config_valid')
60
            sys.exit(0)
61
62
        items = con.keys('rq:*')
63
        self.assertGreater(len(items), 0)
64
        self.assertIn(b'rq:queues', items)
65
        self.assertIn(b'rq:job:' + job.id.encode(), items)
66