desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Leading whitespace confuse ConfigParser'
def testWhiteSpaceConfig(self):
agentConfig = self.get_config('bad.conf') self.assertEquals(agentConfig['dd_url'], 'https://app.datadoghq.com') self.assertEquals(agentConfig['api_key'], '1234') self.assertEquals(agentConfig['nagios_log'], '/var/log/nagios3/nagios.log') self.assertEquals(agentConfig['graphite_listen_port'], 17126) ...
'Verify that the pid file succeeds and fails appropriately'
def testGoodPidFile(self):
pid_dir = tempfile.mkdtemp() program = 'test' expected_path = os.path.join(pid_dir, ('%s.pid' % program)) pid = '666' pid_f = open(expected_path, 'w') pid_f.write(pid) pid_f.close() p = PidFile(program, pid_dir) self.assertEquals(p.get_pid(), 666) self.assertEquals(p.clean(), Tru...
'Resolve the check name from the full path. Note: Support Unix & Windows systems'
def test_conf_path_to_check_name(self, *args):
check_name = u'haproxy' unix_check_path = u'/etc/dd-agent/conf.d/haproxy.yaml' win_check_path = u'C:\\ProgramData\\Datadog\\conf.d\\haproxy.yaml' with mock.patch('config.os.path.splitext', side_effect=ntpath.splitext): with mock.patch('config.os.path.split', side_effect=ntpath.split): ...
'Starting with Agent 5.0.0, there should always be a local forwarder running and all payloads should go through it. So we should make sure that we pass the no_proxy environment variable that will be used by requests (See: https://github.com/kennethreitz/requests/pull/945 )'
def test_no_proxy(self):
from requests.utils import get_environ_proxies from os import environ as env env['http_proxy'] = 'http://localhost:3128' env['https_proxy'] = env['http_proxy'] env['HTTP_PROXY'] = env['http_proxy'] env['HTTPS_PROXY'] = env['http_proxy'] self.assertTrue(('no_proxy' in env)) self.assertEqu...
'Tests that the app tags are sent if specified so'
def test_apptags(self):
agentConfig = {'api_key': 'test_apikey', 'collect_ec2_tags': False, 'collect_orchestrator_tags': False, 'collect_instance_metadata': False, 'create_dd_check_tags': True, 'version': 'test', 'tags': ''} disk_config = {'init_config': {}, 'instances': [{}]} checks = [load_check('disk', disk_config, agentConfig)...
'Dirty patch to reset `SWbemServices.ExecQuery.call_count` and `SWbemServices._exec_query_run_time` to 0, and the wmi query params'
@classmethod def reset(cls):
cls._exec_query_call_count.reset() cls._exec_query_run_time = 0 cls._last_wmi_query = None cls._last_wmi_flags = None
'Return the last WMI query submitted via the WMI connection.'
@classmethod def get_last_wmi_query(cls):
return cls._last_wmi_query
'Return the last WMI flags submitted via the WMI connection.'
@classmethod def get_last_wmi_flags(cls):
return cls._last_wmi_flags
'Return parameters used to set up the WMI connection.'
def get_conn_args(self):
return self._wmi_conn_args
'Mocked `SWbemServices.ExecQuery` method.'
def ExecQuery(self, query, query_language, flags):
self._exec_query_call_count += 1 time.sleep(self._exec_query_run_time) SWbemServices._last_wmi_query = query SWbemServices._last_wmi_flags = flags results = [] if (query in ['Select AvgDiskBytesPerWrite,FreeMegabytes from Win32_PerfFormattedData_PerfDisk_LogicalDisk', 'Select AvgDisk...
'FIXME - Dirty patch to reset `ConnectServer.call_count` to 0.'
@classmethod def reset(cls):
cls._connect_call_count.reset()
'Add context information.'
def Add(self, *args, **kwargs):
pass
'Return a WMI connection, a.k.a. a SWbemServices object.'
def ConnectServer(self, *args, **kwargs):
Dispatch._connect_call_count += 1 wmi_conn_args = (args, kwargs) return SWbemServices(wmi_conn_args)
'Mock WMI related Python packages, so it can be tested on any environment.'
def setUp(self):
self.patcher = patch.dict('sys.modules', {'pywintypes': Mock(), 'pythoncom': Mock(), 'win32com': Mock(), 'win32com.client': Mock(Dispatch=Dispatch)}) self.patcher.start()
'Reset Mock counters'
def tearDown(self):
Dispatch.reset() SWbemServices.reset()
'Helper, assertion on the `wmi_sampler`\'s WMI connection(s): * `param`: parameters used to establish the connection'
def assertWMIConn(self, wmi_sampler, param=None):
if param: connection = wmi_sampler.get_connection() (wmi_conn_args, wmi_conn_kwargs) = connection.get_conn_args() if isinstance(param, tuple): (key, value) = param self.assertIn(key, wmi_conn_kwargs) self.assertEquals(wmi_conn_kwargs[key], value) e...
'Helper, assert that the given WMI query and flags were submitted.'
def assertWMIQuery(self, query=None, flags=None):
if query: last_wmi_query = SWbemServices.get_last_wmi_query() self.assertEquals(last_wmi_query, query) if flags: last_wmi_flags = SWbemServices.get_last_wmi_flags() self.assertEquals(last_wmi_flags, flags)
'Assert the WMI object integrity, i.e. contains the given properties.'
def assertWMIObject(self, wmi_obj, properties):
for prop_and_value in properties: prop = (prop_and_value[0] if isinstance(prop_and_value, tuple) else prop_and_value) value = (prop_and_value[1] if isinstance(prop_and_value, tuple) else None) self.assertIn(prop, wmi_obj) if (value is None): continue self.assertEq...
'Assert WMI objects\' integrity among the WMI sampler.'
def assertWMISampler(self, wmi_sampler, properties, count=None):
self.assertEquals(len(wmi_sampler), count) for wmi_obj in wmi_sampler: self.assertWMIObject(wmi_obj, properties)
'Assert `first` in `second`. Note: needs to be defined for Python 2.6'
def assertIn(self, first, second):
self.assertTrue((first in second), '{0} not in {1}'.format(first, second))
'Assert `first` is not in `second`. Note: needs to be defined for Python 2.6'
def assertNotIn(self, first, second):
self.assertTrue((first not in second), '{0} in {1}'.format(first, second))
'Assert `first` has a key in `second` where it\'s a prefix. Note: needs to be defined for Python 2.6'
def assertInPartial(self, first, second):
self.assertTrue(any((key for key in second if key.startswith(first))), '{0} not in {1}'.format(first, second))
'Get Property from dictionary `dict` starting with `prefix`. Note: needs to be defined for Python 2.6'
def getProp(self, dict, prefix):
for key in dict: if key.startswith(prefix): return dict[key] return None
'Establish a WMI connection to the specified host/namespace, with the right credentials.'
def test_wmi_connection(self):
wmi_sampler = WMISampler('Win32_PerfRawData_PerfOS_System', ['ProcessorQueueLength'], host='myhost', namespace='some/namespace', username='datadog', password='password', provider=32) wmi_sampler.get_connection() self.assertWMIConn(wmi_sampler, param='myhost') self.assertWMIConn(wmi_sampler, param='some/...
'Validate and set a WMI Provider Architecture.'
def test_wmi_provider_architecture(self):
wmi_sampler = WMISampler('Win32_PerfRawData_PerfOS_System', ['ProcessorQueueLength']) self.assertEquals(wmi_sampler.provider, ProviderArchitecture.DEFAULT) wmi_sampler1 = WMISampler('Win32_PerfRawData_PerfOS_System', ['ProcessorQueueLength'], provider='foo') wmi_sampler2 = WMISampler('Win32_PerfRawData_...
'WMI connections are not be shared among WMISampler objects.'
def test_no_wmi_connection_pooling(self):
from win32com.client import Dispatch wmi_sampler_1 = WMISampler('Win32_PerfRawData_PerfOS_System', ['ProcessorQueueLength']) wmi_sampler_2 = WMISampler('Win32_OperatingSystem', ['TotalVisibleMemorySize']) wmi_sampler_3 = WMISampler('Win32_PerfRawData_PerfOS_System', ['ProcessorQueueLength'], host='myhos...
'Format the filters to a comprehensive WQL `WHERE` clause.'
def test_wql_filtering(self):
from checks.libs.wmi import sampler format_filter = sampler.WMISampler._format_filter no_filters = [] filters = [{'Name': 'SomeName', 'Id': 'SomeId'}] self.assertEquals('', format_filter(no_filters)) self.assertEquals(" WHERE ( Name = 'SomeName' AND Id = 'SomeId' )"...
'Format the filters with multiple properties per instance to a comprehensive WQL `WHERE` clause.'
def test_wql_multiquery_filtering(self):
from checks.libs.wmi import sampler format_filter = sampler.WMISampler._format_filter no_filters = [] filters = [{'Name': 'SomeName', 'Property1': 'foo'}, {'Name': 'OtherName', 'Property1': 'bar'}] self.assertEquals('', format_filter(no_filters)) self.assertEquals(" WHERE ( Property1 ...
'Format filters to a comprehensive WQL `WHERE` clause skipping empty lists.'
def test_wql_empty_list(self):
from checks.libs.wmi import sampler format_filter = sampler.WMISampler._format_filter filters = [] query = {} query['User'] = ('=', 'luser') query['SourceName'] = ('=', 'MSSQL') query['EventCode'] = [] query['SomethingEmpty'] = [] query['MoreNothing'] = [] filters.append(query) ...
'Format the filters to a comprehensive WQL `WHERE` clause w/ mixed filter containing regular and operator modified properties.'
def test_wql_filtering_op_adv(self):
from checks.libs.wmi import sampler format_filter = sampler.WMISampler._format_filter filters = [{'Name': 'Foo%'}, {'Name': 'Bar%', 'Id': ('>=', 'SomeId')}, {'Name': 'Zulu'}] self.assertEquals(" WHERE ( Name = 'Zulu' ) OR ( Name LIKE 'Bar%' AND Id >= 'SomeId'...
'Format filters with the eventlog expected form to a comprehensive WQL `WHERE` clause.'
def test_wql_eventlog_filtering(self):
from checks.libs.wmi import sampler from datetime import datetime from checks.wmi_check import from_time format_filter = sampler.WMISampler._format_filter filters = [] query = {} and_props = ['mEssage'] ltypes = ['Error', 'Warning'] source_names = ['MSSQLSERVER', 'IIS'] log_files...
'Format the filters to a comprehensive and inclusive WQL `WHERE` clause.'
def test_wql_filtering_inclusive(self):
from checks.libs.wmi import sampler format_filter = sampler.WMISampler._format_filter filters = [{'Name': 'SomeName'}, {'Id': 'SomeId'}] self.assertEquals(" WHERE ( Id = 'SomeId' ) OR ( Name = 'SomeName' )", format_filter(filters, True))
'Query WMI using WMI Query Language (WQL).'
def test_wmi_query(self):
wmi_sampler = WMISampler('Win32_PerfFormattedData_PerfDisk_LogicalDisk', ['AvgDiskBytesPerWrite', 'FreeMegabytes']) wmi_sampler.sample() self.assertWMIQuery('Select AvgDiskBytesPerWrite,FreeMegabytes from Win32_PerfFormattedData_PerfDisk_LogicalDisk') wmi_sampler = WMISampler('Win32_PerfFormatt...
'Parse WMI objects from WMI query results.'
def test_wmi_parser(self):
wmi_sampler = WMISampler('Win32_PerfFormattedData_PerfDisk_LogicalDisk', ['AvgDiskBytesPerWrite', 'FreeMegabytes']) wmi_sampler.sample() expected_results = [{'freemegabytes': 19742.0, 'name': 'C:', 'avgdiskbytesperwrite': 1536.0}, {'freemegabytes': 19742.0, 'name': 'D:', 'avgdiskbytesperwrite': 1536.0}] ...
'Iterate/Get on the WMISampler object iterates/gets on its current sample.'
def test_wmi_sampler_iterator_getter(self):
wmi_sampler = WMISampler('Win32_PerfFormattedData_PerfDisk_LogicalDisk', ['AvgDiskBytesPerWrite', 'FreeMegabytes']) wmi_sampler.sample() self.assertEquals(len(wmi_sampler), 2) for wmi_obj in wmi_sampler: self.assertWMIObject(wmi_obj, ['AvgDiskBytesPerWrite', 'FreeMegabytes', 'name']) for ind...
'Gracefully handle WMI query timeouts.'
def test_wmi_sampler_timeout(self):
from checks.libs.wmi.sampler import WMISampler logger = Mock() wmi_sampler = WMISampler(logger, 'Win32_PerfFormattedData_PerfDisk_LogicalDisk', ['AvgDiskBytesPerWrite', 'FreeMegabytes'], timeout_duration=0.1) SWbemServices._exec_query_run_time = 0.11 self.assertRaises(TimeoutException, wmi_sampler.s...
'Extend the list of properties to query for RAW Performance classes.'
def test_raw_perf_properties(self):
wmi_sampler = WMISampler('Win32_PerfFormattedData_PerfOS_System', ['ProcessorQueueLength']) self.assertEquals(len(wmi_sampler.property_names), 1) wmi_sampler = WMISampler('Win32_PerfRawData_PerfOS_System', ['CounterRawCount', 'CounterCounter']) self.assertEquals(len(wmi_sampler.property_names), 4)
'Query for initial sample for RAW Performance classes.'
def test_raw_initial_sampling(self):
wmi_sampler = WMISampler('Win32_PerfRawData_PerfOS_System', ['CounterRawCount', 'CounterCounter']) wmi_sampler.sample() self.assertEquals(SWbemServices.ExecQuery.call_count, 2, SWbemServices.ExecQuery.call_count) wmi_sampler.sample() self.assertEquals(SWbemServices.ExecQuery.call_count, 3, SWbemServ...
'Cache the qualifiers on the first query against RAW Performance classes.'
def test_raw_cache_qualifiers(self):
wmi_raw_sampler = WMISampler('Win32_PerfRawData_PerfOS_System', ['CounterRawCount', 'CounterCounter']) wmi_raw_sampler._query() self.assertWMIQuery(flags=131120) wmi_raw_sampler._query() self.assertWMIQuery(flags=48) self.assertTrue(wmi_raw_sampler._property_counter_types) self.assertIn('Cou...
'WMI Object\'s RAW data are returned formatted.'
def test_raw_properties_formatting(self):
wmi_raw_sampler = WMISampler('Win32_PerfRawData_PerfOS_System', ['CounterRawCount', 'CounterCounter']) wmi_raw_sampler.sample() self.assertWMISampler(wmi_raw_sampler, [('CounterRawCount', 500), ('CounterCounter', 50), 'Timestamp_Sys100NS', 'Frequency_Sys100NS', 'name'], count=2)
'Print a warning on RAW Performance classes if the calculator is undefined. Returns the original RAW value.'
def test_raw_properties_fallback(self):
from checks.libs.wmi.sampler import WMISampler logger = Mock() wmi_raw_sampler = WMISampler(logger, 'Win32_PerfRawData_PerfOS_System', ['UnknownCounter', 'MissingProperty']) wmi_raw_sampler.sample() self.assertWMISampler(wmi_raw_sampler, [('UnknownCounter', 999), 'Timestamp_Sys100NS', 'Frequency_Sys...
'Do not raise on missing properties but backfill with empty values.'
def test_missing_property(self):
wmi_raw_sampler = WMISampler('Win32_PerfRawData_PerfOS_System', ['UnknownCounter', 'MissingProperty']) wmi_raw_sampler.sample() self.assertWMISampler(wmi_raw_sampler, ['MissingProperty'], count=1)
'Should not be implemented as it is the mother class'
def test_check(self):
with self.assertRaises(NotImplementedError): self.check.check(None)
'Test the high level method for loading metrics from text format'
def test_parse_metric_family_text(self):
_text_data = None f_name = os.path.join(os.path.dirname(__file__), 'fixtures', 'prometheus', 'metrics.txt') with open(f_name, 'r') as f: _text_data = f.read() self.assertEqual(len(_text_data), 14488) messages = list(self.check.parse_metric_family(_text_data, 'text/plain; version=0.0.4...
'Cheks that the send_histograms_buckets parameter is passed along'
def test_process_send_histograms_buckets(self):
endpoint = 'http://fake.endpoint:10055/metrics' self.check.poll = MagicMock(return_value=[self.protobuf_content_type, self.bin_data]) self.check.process_metric = MagicMock() self.check.process(endpoint, send_histograms_buckets=False, instance=None) self.check.poll.assert_called_with(endpoint) se...
'Checks that an instances with tags passes them as custom tag'
def test_process_instance_with_tags(self):
endpoint = 'http://fake.endpoint:10055/metrics' self.check.poll = MagicMock(return_value=[self.protobuf_content_type, self.bin_data]) self.check.process_metric = MagicMock() instance = {'endpoint': 'IgnoreMe', 'tags': ['tag1:tagValue1', 'tag2:tagValue2']} self.check.process(endpoint, instance=instan...
'Gauge ref submission'
def test_process_metric_gauge(self):
self.check.process_metric(self.ref_gauge) self.check.gauge.assert_called_with('prometheus.process.vm.bytes', 39211008.0, [])
'Metric absent from the metrics_mapper'
def test_process_metric_filtered(self):
filtered_gauge = metrics_pb2.MetricFamily() filtered_gauge.name = 'process_start_time_seconds' filtered_gauge.help = 'Start time of the process since unix epoch in seconds.' filtered_gauge.type = 1 _m = filtered_gauge.metric.add() _m.gauge.value = 39211008.0 self.c...
'Tests poll using the protobuf format'
@patch('requests.get') def test_poll_protobuf(self, mock_get):
mock_get.return_value = MagicMock(status_code=200, content=self.bin_data, headers={'Content-Type': self.protobuf_content_type}) (ct, data) = self.check.poll('http://fake.endpoint:10055/metrics') messages = list(self.check.parse_metric_family(data, ct)) self.assertEqual(len(messages), 61) self.assert...
'submitting metrics that contain labels should result in tags on the gauge call'
def test_submit_metric_gauge_with_labels(self):
_l1 = self.ref_gauge.metric[0].label.add() _l1.name = 'my_1st_label' _l1.value = 'my_1st_label_value' _l2 = self.ref_gauge.metric[0].label.add() _l2.name = 'my_2nd_label' _l2.value = 'my_2nd_label_value' self.check._submit_metric(self.check.metrics_mapper[self.ref_gauge.name], self.ref_gauge...
'Providing custom tags should add them as is on the gauge call'
def test_submit_metric_gauge_with_custom_tags(self):
tags = ['env:dev', 'app:my_pretty_app'] self.check._submit_metric(self.check.metrics_mapper[self.ref_gauge.name], self.ref_gauge, custom_tags=tags) self.check.gauge.assert_called_with('prometheus.process.vm.bytes', 39211008.0, ['env:dev', 'app:my_pretty_app'])
'Submitting metrics that contain labels mappers should result in tags on the gauge call with transformed tag names'
def test_submit_metric_gauge_with_labels_mapper(self):
_l1 = self.ref_gauge.metric[0].label.add() _l1.name = 'my_1st_label' _l1.value = 'my_1st_label_value' _l2 = self.ref_gauge.metric[0].label.add() _l2.name = 'my_2nd_label' _l2.value = 'my_2nd_label_value' self.check.labels_mapper = {'my_1st_label': 'transformed_1st', 'non_existent': 'should_n...
'Submitting metrics when filtering with exclude_labels should end up with a filtered tags list'
def test_submit_metric_gauge_with_exclude_labels(self):
_l1 = self.ref_gauge.metric[0].label.add() _l1.name = 'my_1st_label' _l1.value = 'my_1st_label_value' _l2 = self.ref_gauge.metric[0].label.add() _l2.name = 'my_2nd_label' _l2.value = 'my_2nd_label_value' self.check.labels_mapper = {'my_1st_label': 'transformed_1st', 'non_existent': 'should_n...
'Defines two WMI object samples.'
def setUp(self):
self.previous = {'WMIPropertyName': 300, 'Timestamp_Sys100NS': 50} self.current = {'WMIPropertyName': 500, 'Timestamp_Sys100NS': 52, 'Frequency_Sys100NS': 0.5}
'Handler to assert the value returned by the counter_type\'s calculator on the given sample.'
def assertPropertyValue(self, counter_type, value):
calculator = get_calculator(counter_type) self.assertEquals(value, calculator(self.previous, self.current, 'WMIPropertyName'))
'Asssign a calculator to a counter_type. Raise when the calculator is missing.'
def test_calculator_decorator(self):
@calculator(123456) def do_something(*args, **kwargs): 'A function that does something.' pass self.assertEquals('do_something', do_something.__name__) self.assertEquals('A function that does something.', do_something.__doc__) self.assertTrue(get_calculator(123...
'Check the computed values from calculators.'
def test_calculator_values(self):
self.assertPropertyValue(65536, 500) self.assertPropertyValue(65792, 500) self.assertPropertyValue(542180608, 10000) self.assertPropertyValue(272696576, 50) self.assertPropertyValue(272696320, 50)
'Decorate `make_sum`.'
def __init__(self):
self.make_sum = timeout(0.2)(self.make_sum)
'Sleep, sum and return `a` with `b`'
def make_sum(self, a, b, sleep=0, raise_exception=False):
global count count += 1 time.sleep(sleep)
'Wait for all threads to end to avoid contamination between each tests.'
def tearDown(self):
for (key, worker) in _thread_by_func.iteritems(): while worker.is_alive(): time.sleep(0.2) for key in _thread_by_func.keys(): del _thread_by_func[key]
'Preserve function name and docstring.'
def test_preserve(self):
self.assertEquals(make_sum.__name__, 'make_sum') self.assertEquals(make_sum.__doc__, 'Sleep, sum and return `a` with `b`')
'Return the result when the method runtime does not exceed the limit set.'
def test_no_timeout(self):
self.assertEquals(make_sum(1, 2), 3)
'Propagate exceptions.'
def test_exception_propagation(self):
self.assertRaises(SomeException, make_sum, 1, 2, raise_exception=True)
'Raise `TimeoutException` on timeouts.'
def test_raise_on_timeout(self):
self.assertRaises(TimeoutException, make_sum, 1, 2, sleep=0.5)
'Refetch an existing thread when it exists.'
def test_refetch_thread(self):
self.assertRaises(TimeoutException, make_sum, 1, 2, sleep=0.5) self.assertEquals(count, 1) time.sleep(0.5) self.assertEquals(make_sum(1, 2, sleep=0.5), 3) self.assertEquals(count, 1) self.assertRaises(TimeoutException, make_sum, 1, 2, sleep=0.5) self.assertEquals(count, 2)
'Create one thread per function call.'
def test_multiple_threads(self):
self.assertRaises(TimeoutException, make_sum, 1, 2, sleep=0.5) self.assertRaises(TimeoutException, make_sum, 2, 3, sleep=0.5) self.assertEquals(count, 2)
'Same method within different instances = different threads'
def test_multiple_instances(self):
self.assertRaises(TimeoutException, MyClass().make_sum, 1, 2, sleep=0.5) self.assertRaises(TimeoutException, MyClass().make_sum, 1, 2, sleep=0.5) self.assertEquals(count, 2)
'Starting with Agent 5.0.0, there should always be a local forwarder running and all payloads should go through it. So we should make sure that we pass the no_proxy environment variable that will be used by requests (See: https://github.com/kennethreitz/requests/pull/945 )'
@attr(requires='core_integration') def test_no_proxy(self):
from os import environ as env env['http_proxy'] = 'http://localhost:3128' env['https_proxy'] = env['http_proxy'] env['HTTP_PROXY'] = env['http_proxy'] env['HTTPS_PROXY'] = env['http_proxy'] set_no_proxy_settings() self.assertTrue(('no_proxy' in env)) self.assertEquals(env['no_proxy'], '1...
'Proxy should be skipped when so specified...'
@attr(requires='core_integration') def test_proxy_skip(self):
proxies = {'http': 'http://localhost:3128', 'https': 'http://localhost:3128', 'no': '127.0.0.1,localhost,169.254.169.254,host.foo.bar'} gen_proxies = config_proxy_skip(proxies, 's3://anything', skip_proxy=True) self.assertEquals(gen_proxies.get('http'), None) self.assertEquals(gen_proxies.get('https'), ...
'Make sure that globbed dogstream logfile matching works.'
def test_dogstream_log_path_globbing(self):
first_tmpfile = NamedTemporaryFile() tmp_fprefix = os.path.basename(first_tmpfile.name) all_tmp_filenames = set([first_tmpfile.name]) avoid_gc = [] for i in range(3): new_tmpfile = NamedTemporaryFile(prefix=tmp_fprefix) all_tmp_filenames.add(new_tmpfile.name) avoid_gc.append(...
'Ensure that non-class-based stateful plugins work'
def test_dogstream_function_plugin(self):
log_data = ['test.metric.accumulator 1000000000 1 metric_type=counter', 'test.metric.accumulator 1100000000 1 metric_type=counter'] expected_output = {'dogstream': [('test.metric.accumulator', 1000000000, 1, self.counter), ('test.metric.accumulator', 1100000000, 2, self.counter)]} self._wr...
'Ensure that class-based stateful plugins work'
def test_dogstream_new_plugin(self):
log_data = ['test.metric.accumulator 1000000000 1 metric_type=counter', 'test.metric.accumulator 1100000000 1 metric_type=counter'] expected_output = {'dogstream': [('foo.bar:test.metric.accumulator', 1000000000, 1, self.counter), ('foo.bar:test.metric.accumulator', 1100000000, 2, self.counter...
'Return the last message logged.'
def pop(self):
if (not self.messages): return None return self.messages.pop()
'Catch any exception and log it.'
def test_log_exception(self):
mock_logger = Mock() @log_exceptions(mock_logger) def raise_exception(): '\n Raise an exception.\n ' raise Exception(u'Bad exception.') self.assertRaises(Exception, raise_exception) ...
'`RedactedLogRecord` custom LogRecord obfuscates API key logging.'
def test_api_key_log_obfuscation(self):
logging.LogRecord = RedactedLogRecord logger = logging.getLogger() handler = MockLoggingHandler() logger.setLevel(logging.DEBUG) logger.addHandler(handler) def log_api_key(): '\n Log things, including an API key.\n ...
'Can set, read, update and delete data in the agent_payload'
def test_add_rem_elem(self):
agent_payload = AgentPayload() self.assertEquals(len(agent_payload), 0) agent_payload['something'] = 'value' self.assertEquals(len(agent_payload), 1) self.assertEquals(agent_payload['something'], 'value') agent_payload['something'] = 'other value' self.assertEquals(len(agent_payload), 1) ...
'`agent_payload` property returns a single agent_payload with the content of data and metadata payloads.'
def test_payload_property(self):
agent_payload = AgentPayload() payload = {} DATA_KEYS = ['key1', 'key2'] META_KEYS = list(AgentPayload.METADATA_KEYS)[:2] DUP_KEYS = list(AgentPayload.DUPLICATE_KEYS)[:2] for k in ((DATA_KEYS + META_KEYS) + DUP_KEYS): agent_payload[k] = 'value' payload[k] = 'value' self.asser...
'Split data and metadata payloads. Submit to the right endpoint.'
def test_split_metrics_and_meta(self):
DATA_KEYS = ['key1', 'key2', 'key3', 'key4'] agent_payload = AgentPayload() for key in AgentPayload.METADATA_KEYS: agent_payload[key] = 'value' len_payload1 = len(agent_payload) self.assertEquals(len_payload1, len(AgentPayload.METADATA_KEYS)) self.assertEquals(len_payload1, len(agent_pay...
'Submit each payload to its specific endpoint.'
def test_emit_payload(self):
agent_payload = AgentPayload() fake_emitter = Mock() fake_emitter.__name__ = None agent_payload.emit(None, None, [fake_emitter], True, merge_payloads=False) fake_emitter.assert_any_call(agent_payload.data_payload, None, None, 'metrics') fake_emitter.assert_any_call(agent_payload.meta_payload, No...
'Modules already in the cache should be reused'
def test_cached_module(self):
self.assertTrue(modules.load(('%s:has_been_mutated' % __name__)))
'Python module cache should be populated'
def test_cache_population(self):
self.assertTrue((TARGET_MODULE not in sys.modules)) modules.load(TARGET_MODULE) self.assertTrue((TARGET_MODULE in sys.modules))
'When the specifier contains no module name, any provided default should be used'
def test_modname_load_default(self):
self.assertEquals(modules.load(TARGET_MODULE, 'default_target'), 'DEFAULT')
'When the specifier contains a module name, any provided default should be overridden'
def test_modname_load_specified(self):
self.assertEquals(modules.load('{0}:specified_target'.format(TARGET_MODULE), 'default_target'), 'SPECIFIED')
'"Loading modules by absolute path should correctly set the name of the loaded module to include any package containing it.'
@attr('unix') def test_pathname_load_finds_package(self):
m = modules.load(os.path.join(os.getcwd(), TARGET_MODULE.replace('.', '/'))) self.assertEquals(m.__name__, TARGET_MODULE)
'Helper, a context manager to set the current time value.'
@contextmanager def set_time(self, time):
mock_time = patch('utils.timer.time.time') mock_time.start().return_value = time (yield) mock_time.stop()
'Watchdog restarts the process on suspicious high activity.'
@patch.object(Watchdog, 'self_destruct', side_effect=WatchdogKill) def test_watchdog_frenesy_detection(self, mock_restarted):
Watchdog._RESTART_TIMEFRAME = 1 process_watchdog = Watchdog(10, max_resets=3) ping_watchdog = process_watchdog.reset with self.set_time(1): for x in xrange(0, 3): ping_watchdog() self.assertRaises(WatchdogKill, ping_watchdog) with self.set_time(3): ping_watchdog()...
'Verify that watchdog kills ourselves even when spinning Verify that watchdog kills ourselves when hanging'
def test_watchdog(self):
start = time.time() try: subprocess.check_call(['python', __file__, 'busy'], stderr=subprocess.STDOUT) raise Exception('Should have died with an error') except subprocess.CalledProcessError: duration = int((time.time() - start)) self.assertTrue((duration < (sel...
'Pretend to flush for a long time'
def flush(self):
time.sleep(5) sys.exit(0)
'Collect hostname metadata'
def test_hostname_metadata(self):
c = Collector({'collect_instance_metadata': True}, None, {}, 'foo') metadata = c._get_hostname_metadata() assert ('hostname' in metadata) assert ('socket-fqdn' in metadata) assert ('socket-hostname' in metadata)
'Roll-up instance metadata'
def test_instance_metadata_rollup(self):
config = {'instances': [{'metadata': True, 'more_meta': True}]} instances = config.get('instances') check = TestMetadata.FakeCheck('fake_check', config, {}, instances) check.run() service_metadata = check.get_service_metadata() service_metadata_count = len(service_metadata) self.assertEquals...
'Fill up checks that do not generate any metadata'
def test_metadata_length(self):
config = {'instances': [{'metadata': True}, {}, {'metadata': True}]} instances = config.get('instances') check = TestMetadata.FakeCheck('fake_check', config, {}, instances) check.run() service_metadata = check.get_service_metadata() service_metadata_count = len(service_metadata) self.assertE...
'Test memory limit as well as simple flush'
def testMemoryLimit(self):
trManager = TransactionManager(timedelta(seconds=0), MAX_QUEUE_SIZE, timedelta(seconds=0), max_endpoint_errors=100) step = 10 oneTrSize = ((MAX_QUEUE_SIZE / step) - 1) for i in xrange(step): trManager.append(memTransaction(oneTrSize, trManager)) trManager.flush() self.assertEqual(len(trM...
'Test throttling while flushing'
def testThrottling(self):
trManager = TransactionManager(timedelta(seconds=0), MAX_QUEUE_SIZE, THROTTLING_DELAY, max_endpoint_errors=100) trManager._flush_without_ioloop = True oneTrSize = (MAX_QUEUE_SIZE / 10) for i in xrange(3): tr = memTransaction(oneTrSize, trManager) trManager.append(tr) before = datetim...
'Tests that the logic behind the agent version specific endpoints is ok. Also tests that these endpoints actually exist.'
def testEndpoints(self):
MetricTransaction._endpoints = [] api_key = ('a' * 32) config = {'endpoints': {'https://app.datadoghq.com': [api_key]}, 'dd_url': 'https://app.datadoghq.com', 'api_key': api_key, 'use_dd': True} app = Application() app.skip_ssl_validation = False app.agent_dns_caching = False app._agentConfi...
'Returns an eventlist from specs in the form [(namespace, kind)]'
@classmethod def _build_events(cls, specs):
resVersion = 0 items = [] for (ns, kind) in specs: resVersion += 1 i = {} i['metadata'] = {'resourceVersion': resVersion, 'namespace': ns} i['involvedObject'] = {'kind': kind, 'namespace': ns} items.append(i) return {'items': items}
'Test get_check_config with mocked container inspect and config template'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch('utils.dockerutil.DockerUtil.client', return_value=None) @mock.patch.object(SDDockerBackend, '_get_host_address', return_value='127.0.0.1') @mock.patch.object(SDDockerBackend, '_get_port', ...
c_id = self.docker_container_inspect.get('Id') for image in self.mock_templates.keys(): sd_backend = get_sd_backend(agentConfig=self.auto_conf_agentConfig) state = _SDDockerBackendConfigFetchState(_get_container_inspect) self.assertEquals(sd_backend._get_check_configs(state, c_id, image)...
'Test _get_config_templates with mocked get_check_tpls'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch('utils.dockerutil.DockerUtil.client', return_value=None) @mock.patch.object(ConsulStore, 'get_client', return_value=None) @mock.patch.object(EtcdStore, 'get_client', return_value=None) @moc...
for agentConfig in self.agentConfigs: sd_backend = get_sd_backend(agentConfig=agentConfig) for image in self.mock_templates.keys(): template = sd_backend._get_config_templates(image) expected_template = self.mock_templates.get(image)[0] self.assertEquals(template,...
'Test _render_template'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) def test_render_template(self, mock_get_auto_confd_path):
valid_configs = [(({}, {'host': '%%host%%'}, {'host': 'foo'}), ({}, {'host': 'foo'})), (({}, {'host': '%%host%%', 'port': '%%port%%'}, {'host': 'foo', 'port': '1337'}), ({}, {'host': 'foo', 'port': '1337'})), (({'foo': '%%bar%%'}, {}, {'bar': 'w00t'}), ({'foo': 'w00t'}, {})), (({'foo': '%%bar%%'}, {'host': '%%host%...
'Test _fill_tpl with mocked docker client'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch('utils.dockerutil.DockerUtil.client', return_value=None) @mock.patch.object(EtcdStore, 'get_client', return_value=None) @mock.patch.object(ConsulStore, 'get_client', return_value=None) def ...
valid_configs = [(({}, {'host': 'localhost'}, [], None), ({'host': 'localhost'}, {})), (({'NetworkSettings': {'IPAddress': ''}}, {'host': 'localhost'}, [], None), ({'host': 'localhost'}, {})), (({'NetworkSettings': {'Networks': {}}}, {'host': 'localhost'}, [], None), ({'host': 'localhost'}, {})), (({'NetworkSetting...
'Test _get_auto_config'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) def test_get_auto_config(self, mock_get_auto_confd_path):
expected_tpl = {'disk': [('disk', None, {'host': '%%host%%', 'port': '%%port%%'})], 'consul': [('consul', None, {'url': 'http://%%host%%:%%port%%', 'catalog_checks': True, 'new_leader_checks': True})], 'disk:v1': [('disk', None, {'host': '%%host%%', 'port': '%%port%%'})], 'foobar': []} config_store = get_config...