Skip to content

Commit 3d3fd53

Browse files
committed
Fix tests
1 parent c44c2ec commit 3d3fd53

File tree

6 files changed

+130
-55
lines changed

6 files changed

+130
-55
lines changed

debian/zabbix-cachet.postinst

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/bin/bash
2+
# TODO: Add pytz and updated versions
23
pip3 install pyzabbix==0.7.4
34
chmod 640 /etc/zabbix-cachet.yml
45
systemctl status zabbix-cachet.service

requirements.txt

+7-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
PyYAML==5.1
2-
pyzabbix==0.7.4
3-
requests==2.20.0
4-
pytz==2019.3
1+
PyYAML>=5.4
2+
pyzabbix==1.2.1
3+
requests>=2.21.0
4+
pytz==2024.1
5+
# Dev only
6+
# pytest==8.1.1
7+
# pytest-env==1.1.3

src/zabbix_cachet/excepltions.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import logging
2+
3+
logger = logging.getLogger(__name__)
4+
5+
6+
class ZabbixCachetException(Exception):
7+
def __init__(self, message=None, errors=None):
8+
if errors:
9+
message = ', '.join(errors)
10+
self.errors = errors
11+
if message:
12+
logger.error(repr(message).rstrip())
13+
super(Exception, self).__init__(message)
14+
15+
16+
class InvalidConfig(ZabbixCachetException):
17+
pass

src/zabbix_cachet/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import pytz
1717
from operator import itemgetter
1818

19-
__author__ = 'Artem Alexandrov <qk4l()tem4uk.ru>'
19+
__author__ = 'Artem Aleksandrov <qk4l()tem4uk.ru>'
2020
__license__ = """The MIT License (MIT)"""
2121
__version__ = '2.0.0'
2222

src/zabbix_cachet/zabbix.py

+23-14
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import logging
77
from pyzabbix import ZabbixAPI, ZabbixAPIException
88

9+
from zabbix_cachet.excepltions import InvalidConfig
10+
911

1012
def pyzabbix_safe(fail_result=False):
1113

@@ -41,7 +43,7 @@ class ZabbixService:
4143
serviceid: str
4244
status: str
4345
algorithm: str
44-
triggerid: str
46+
triggerid: str = None
4547
children: List['ZabbixService'] = field(default_factory=list)
4648
# TODO: Change to parents in future if will needed
4749
is_parents: bool = False
@@ -71,8 +73,9 @@ def __init__(self, server, user, password, verify=True):
7173
self.version = self.get_version()
7274
# Zabbix made significant changes in 6.0 https://support.zabbix.com/browse/ZBXNEXT-6674
7375
try:
74-
if int(self.version.split('.')[0]) >= 6:
75-
self.get_service = self.get_service_modern
76+
self.version_major = int(self.version.split('.')[0])
77+
if self.version_major >= 6:
78+
self.get_service = self.get_service
7679
else:
7780
self.get_service = self.get_service_legacy
7881
except (TypeError, IndexError) as err:
@@ -119,20 +122,21 @@ def get_event(self, triggerid):
119122
return zbx_event[-1]
120123
return zbx_event
121124

122-
def get_service_modern(self, name: str = '', serviceid: Union[List, str] = None,
123-
parentids: str = '') -> List[Dict]:
125+
def get_service(self, name: str = '', serviceid: Union[List, str] = None,
126+
parentids: str = '') -> List[Dict]:
124127
"""
125-
For zabbix 6+
128+
For zabbix 6.0 +
129+
https://www.zabbix.com/documentation/6.0/en/manual/appendix/services_upgrade
126130
:return:
127131
"""
128132
if name:
129133
services = self.zapi.service.get(selectChildren='extend', filter={'name': name})
130134
elif serviceid:
131135
services = self.zapi.service.get(selectChildren='extend', serviceids=serviceid)
132136
elif parentids:
133-
services = self.zapi.service.get(selectDependencies='extend', parentids=parentids)
137+
services = self.zapi.service.get(selectChildren='extend', parentids=parentids)
134138
else:
135-
services = self.zapi.service.get(selectDependencies='extend')
139+
services = self.zapi.service.get(selectChildren='extend')
136140

137141
return services
138142

@@ -167,7 +171,8 @@ def _init_zabbix_it_service(self, data: Dict) -> ZabbixService:
167171
logging.debug(f"Init ZabbixITService for {data.get('name')} ")
168172
zabbix_it_service = ZabbixService(name=data.get('name'),
169173
serviceid=data.get('serviceid'),
170-
triggerid=data.get('triggerid'),
174+
# TODO: Change for zbx 6
175+
triggerid=data.get('triggerid', None),
171176
algorithm=data.get('algorithm'),
172177
status=data.get('status'))
173178
if 'parents' in data:
@@ -201,10 +206,14 @@ def get_itservices(self, root_name: str = None) -> List[ZabbixService]:
201206
sys.exit(1)
202207
monitor_services = self._init_zabbix_it_service(root_service[0]).children
203208
else:
204-
services = self.get_service()
205-
for i in services:
206-
# Do not proceed non-root services directly
207-
if len(i['parents']) == 0:
208-
monitor_services.append(self._init_zabbix_it_service(i))
209+
if self.version_major < 6:
210+
services = self.get_service()
211+
for i in services:
212+
# Do not proceed non-root services directly
213+
if len(i['parents']) == 0:
214+
monitor_services.append(self._init_zabbix_it_service(i))
215+
else:
216+
raise InvalidConfig(f"settings.root_service should be defined in you config yaml file because "
217+
f"you use Zabbix version {self.version}")
209218
return monitor_services
210219

tests/test_zabbix.py

+81-36
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import pytest
2+
import logging
23

34
from zabbix_cachet.zabbix import Zabbix
45

56
SERVICE_WITH_DEP_NAME = 'Service with dependencies'
67
SERVICE_WO_DEP_NAME = 'Single Service'
8+
SERVICE_SEPARATE_ROOT = 'Separate service under root'
79

810
TRIGGER_ID = '16199'
911
SERVICES = [
@@ -20,6 +22,15 @@
2022
'goodsla': '99.9', 'sortorder': '0', 'dependencies': []}
2123
]
2224

25+
log_level = logging.getLevelName('DEBUG')
26+
log_level_requests = logging.getLevelName('DEBUG')
27+
logging.basicConfig(
28+
level=log_level,
29+
format='%(asctime)s %(levelname)s: (%(threadName)s) %(message)s',
30+
datefmt='%Y-%m-%d %H:%M:%S %Z'
31+
)
32+
logging.getLogger("requests").setLevel(log_level_requests)
33+
2334

2435
@pytest.fixture(name='zabbix', scope='class')
2536
def zabbix_init(config):
@@ -29,50 +40,69 @@ def zabbix_init(config):
2940
zabbix = Zabbix(zabbix_config['server'], zabbix_config['user'], zabbix_config['pass'],
3041
zabbix_config['https-verify'])
3142
root_service = zabbix.zapi.service.get(filter={'name': setting_config['root_service']})
43+
root_separate = zabbix.zapi.service.get(filter={'name': SERVICE_SEPARATE_ROOT})
44+
45+
zabbix_service_template = {'name': '', 'algorithm': 0, 'sortorder': 0}
46+
if not root_separate:
47+
service = dict.copy(zabbix_service_template)
48+
service.update({'name': SERVICE_SEPARATE_ROOT})
49+
if zabbix.version_major < 6:
50+
service.update({'showsla': 0})
51+
zabbix.zapi.service.create(**service)
52+
3253
if not root_service:
33-
root_service = zabbix.zapi.service.create(
34-
name=setting_config['root_service'],
35-
algorithm=0,
36-
sortorder=0,
37-
showsla=0,
38-
)
39-
root_service_id = root_service['serviceids'][0]
40-
zabbix.zapi.service.create(
41-
name=SERVICE_WO_DEP_NAME,
42-
algorithm=1,
43-
sortorder=0,
44-
showsla=0,
45-
triggerid=TRIGGER_ID,
46-
parentid=root_service_id
47-
)
48-
second_service = zabbix.zapi.service.create(
49-
name=SERVICE_WITH_DEP_NAME,
50-
algorithm=1,
51-
sortorder=0,
52-
showsla=0,
53-
parentid=root_service_id,
54-
)
55-
second_service_id = second_service['serviceids'][0]
54+
# root_service
55+
service = dict.copy(zabbix_service_template)
56+
service.update({'name': setting_config['root_service']})
57+
if zabbix.version_major < 6:
58+
service.update({'showsla': 0})
59+
root_service = zabbix.zapi.service.create(**service)
60+
root_service_id = int(root_service['serviceids'][0])
61+
62+
# SERVICE_WO_DEP_NAME
63+
service = dict.copy(zabbix_service_template)
64+
service.update({'name': SERVICE_WO_DEP_NAME})
65+
if zabbix.version_major < 6:
66+
service.update({'showsla': 0, 'triggerid': TRIGGER_ID, 'parentid': str(root_service_id)})
67+
else:
68+
service.update({
69+
'parents': [{'serviceid': root_service_id}],
70+
'problem_tags': [{'tag': 'scope', 'value': 'availability'}],
71+
})
72+
a = zabbix.zapi.service.create(**service)
73+
print(a)
74+
# SERVICE_WITH_DEP_NAME
75+
service = dict.copy(zabbix_service_template)
76+
service.update({'name': SERVICE_WITH_DEP_NAME})
77+
if zabbix.version_major < 6:
78+
service.update({'showsla': 0, 'parentid': str(root_service_id)})
79+
else:
80+
service.update({'parents': [{'serviceid': root_service_id}]})
81+
82+
second_service = zabbix.zapi.service.create(**service)
83+
second_service_id = int(second_service['serviceids'][0])
84+
85+
# Dependency services
5686
for service_name in ('dependency1', 'dependency2'):
57-
zabbix.zapi.service.create(
58-
name=service_name,
59-
algorithm=1,
60-
sortorder=0,
61-
showsla=0,
62-
triggerid=TRIGGER_ID,
63-
parentid=second_service_id,
64-
)
87+
service = dict.copy(zabbix_service_template)
88+
service.update({'name': service_name})
89+
if zabbix.version_major < 6:
90+
service.update({'showsla': 0, 'triggerid': TRIGGER_ID, 'parentid': str(second_service_id)})
91+
else:
92+
service.update({
93+
'parents': [{'serviceid': second_service_id}],
94+
'problem_tags': [{'tag': 'scope', 'value': 'availability'}],
95+
})
96+
zabbix.zapi.service.create(**service)
97+
6598
return zabbix
6699

67100

68101
def test_get_version(zabbix):
69102
assert isinstance(zabbix.version, str)
70103

71104

72-
def test_get_itservices(zabbix, config):
73-
"""
74-
:return:
75-
"""
105+
def test_get_itservices_with_root(zabbix, config):
76106
it_services = zabbix.get_itservices(config['settings']['root_service'])
77107
assert len(it_services) == 2
78108
service_with_dep = it_services[1]
@@ -83,5 +113,20 @@ def test_get_itservices(zabbix, config):
83113
assert len(service_with_dep.children) == 2
84114
assert service_with_dep.children[0].name == 'dependency1'
85115
assert service_with_dep.children[1].name == 'dependency2'
86-
assert service_with_dep.children[1].triggerid == TRIGGER_ID
116+
if zabbix.version_major < 6:
117+
assert service_with_dep.children[1].triggerid == TRIGGER_ID
87118
# print(it_services)
119+
120+
121+
def test_get_itservices_wo_root(zabbix, config):
122+
# Not supported after 6.0
123+
if zabbix.version_major >= 6:
124+
return True
125+
it_services = zabbix.get_itservices()
126+
assert len(it_services) == 2
127+
service_cachet = it_services[1]
128+
service_separate = it_services[0]
129+
assert service_cachet.name == config['settings']['root_service']
130+
assert service_separate.name == SERVICE_SEPARATE_ROOT
131+
assert len(service_cachet.children) == 2
132+
assert len(service_separate.children) == 0

0 commit comments

Comments
 (0)