11import pytest
2+ import json
3+ import time
4+ import math
5+ import asyncio
26import requests
7+ from collections import Counter
8+
9+ import prometheus_push_client as ppc
10+
11+ from testutils import make_metric_fixture
12+
13+
14+ NS = "test_vic"
15+
16+
17+ def export (cfg , pattern = NS ):
18+ response = requests .get (
19+ cfg .vm_export_url ,
20+ params = {'match[]' : r'{__name__=~"%s.*"}' % pattern }
21+ )
22+
23+ found = []
24+ for line in response .iter_lines ():
25+ metric = json .loads (line )
26+ found .append (metric )
27+ return found
28+
29+
30+ def count_samples (found , pattern ):
31+ n_samples = Counter ()
32+ for metric in found :
33+ mname = metric ["metric" ]["__name__" ]
34+ if mname .startswith (pattern ):
35+ n_samples [mname ] += len (metric ["values" ])
36+ return n_samples
37+
338
439
540def test_ping (cfg ):
641 response = requests .get (cfg .vm_ping_url )
742 content = response .text
843
944 assert response .status_code == 200 , content
10- assert content == "OK" , content
45+ assert content == "OK" , content
46+
47+
48+ @pytest .fixture
49+ def counter1 (request ):
50+ return make_metric_fixture (
51+ request ,
52+ ppc .Counter ("c1" , namespace = NS , subsystem = "influx_udp" )
53+ )
54+
55+
56+ def test_vic_influx_udp_thread (cfg , counter1 ):
57+
58+ found_before = export (cfg )
59+ count_before = count_samples (found_before , counter1 ._name )
60+
61+ period = 0.4
62+ sleeps = 2
63+ sleep_sec = 1.0
64+ samples_expected = math .ceil (sleeps / period ) # + graceful one
65+
66+ @ppc .influx_udp_thread (cfg .vm_host , cfg .vm_influx_port , period = period )
67+ def _test ():
68+ for _ in range (sleeps ):
69+ counter1 .inc ()
70+ time .sleep (sleep_sec )
71+ return 1 / 0 # testing graceful stop
72+
73+ with pytest .raises (ZeroDivisionError ):
74+ _test ()
75+
76+ time .sleep (2.0 ) # let them sync
77+
78+ found_after = export (cfg )
79+ count_after = count_samples (found_after , counter1 ._name )
80+
81+ for k in count_after .keys ():
82+ assert samples_expected == count_after [k ] - count_before [k ]
83+
84+
85+ @pytest .mark .asyncio
86+ async def test_vic_influx_udp_async (cfg , counter1 ):
87+
88+ found_before = export (cfg )
89+ count_before = count_samples (found_before , counter1 ._name )
90+
91+ period = 0.4
92+ sleeps = 2
93+ sleep_sec = 1.0
94+ samples_expected = math .ceil (sleeps / period ) # + graceful one
95+
96+ @ppc .influx_udp_async (cfg .vm_host , cfg .vm_influx_port , period = period )
97+ async def _test ():
98+ for _ in range (sleeps ):
99+ counter1 .inc ()
100+ await asyncio .sleep (sleep_sec )
101+ return 1 / 0 # testing graceful stop
102+
103+ with pytest .raises (ZeroDivisionError ):
104+ await _test ()
105+
106+ await asyncio .sleep (2.0 ) # let them sync
107+
108+ found_after = export (cfg )
109+ count_after = count_samples (found_after , counter1 ._name )
110+
111+ for k in count_after .keys ():
112+ assert samples_expected == count_after [k ] - count_before [k ]
0 commit comments