code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_filter_by_name(self):
"""Test filtering by name in TestResultSet object."""
expected = [
{'value': 0.64,
'time': '2015-01-29T21:51:28.968422294Z',
'host': 'server01',
'region': 'us-west'},
{'value': 0.65,
'time': '2015-01-29T21:51:28.968422294Z',
'host': 'server02',
'region': 'us-west'},
]
self.assertEqual(expected, list(self.rs['cpu_load_short']))
self.assertEqual(expected,
list(self.rs.get_points(
measurement='cpu_load_short'))) | Test filtering by name in TestResultSet object. | test_filter_by_name | python | influxdata/influxdb-python | influxdb/tests/resultset_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/resultset_test.py | MIT |
def test_filter_by_tags(self):
"""Test filter by tags in TestResultSet object."""
expected = [
{'value': 0.64,
'time': '2015-01-29T21:51:28.968422294Z',
'host': 'server01',
'region': 'us-west'},
{'value': 0.66,
'time': '2015-01-29T21:51:28.968422294Z',
'host': 'server01',
'region': 'us-west'},
]
self.assertEqual(
expected,
list(self.rs[{"host": "server01"}])
)
self.assertEqual(
expected,
list(self.rs.get_points(tags={'host': 'server01'}))
) | Test filter by tags in TestResultSet object. | test_filter_by_tags | python | influxdata/influxdb-python | influxdb/tests/resultset_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/resultset_test.py | MIT |
def test_filter_by_name_and_tags(self):
"""Test filter by name and tags in TestResultSet object."""
self.assertEqual(
list(self.rs[('cpu_load_short', {"host": "server01"})]),
[{'value': 0.64,
'time': '2015-01-29T21:51:28.968422294Z',
'host': 'server01',
'region': 'us-west'}]
)
self.assertEqual(
list(self.rs[('cpu_load_short', {"region": "us-west"})]),
[
{'value': 0.64,
'time': '2015-01-29T21:51:28.968422294Z',
'host': 'server01',
'region': 'us-west'},
{'value': 0.65,
'time': '2015-01-29T21:51:28.968422294Z',
'host': 'server02',
'region': 'us-west'},
]
) | Test filter by name and tags in TestResultSet object. | test_filter_by_name_and_tags | python | influxdata/influxdb-python | influxdb/tests/resultset_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/resultset_test.py | MIT |
def test_point_from_cols_vals(self):
"""Test points from columns in TestResultSet object."""
cols = ['col1', 'col2']
vals = [1, '2']
point = ResultSet.point_from_cols_vals(cols, vals)
self.assertDictEqual(
point,
{'col1': 1, 'col2': '2'}
) | Test points from columns in TestResultSet object. | test_point_from_cols_vals | python | influxdata/influxdb-python | influxdb/tests/resultset_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/resultset_test.py | MIT |
def test_system_query(self):
"""Test system query capabilities in TestResultSet object."""
rs = ResultSet(
{'series': [
{'values': [['another', '48h0m0s', 3, False],
['default', '0', 1, False],
['somename', '24h0m0s', 4, True]],
'columns': ['name', 'duration',
'replicaN', 'default']}]}
)
self.assertEqual(
rs.keys(),
[('results', None)]
)
self.assertEqual(
list(rs['results']),
[
{'duration': '48h0m0s', 'default': False, 'replicaN': 3,
'name': 'another'},
{'duration': '0', 'default': False, 'replicaN': 1,
'name': 'default'},
{'duration': '24h0m0s', 'default': True, 'replicaN': 4,
'name': 'somename'}
]
) | Test system query capabilities in TestResultSet object. | test_system_query | python | influxdata/influxdb-python | influxdb/tests/resultset_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/resultset_test.py | MIT |
def test_resultset_error(self):
"""Test returning error in TestResultSet object."""
with self.assertRaises(InfluxDBClientError):
ResultSet({
"series": [],
"error": "Big error, many problems."
}) | Test returning error in TestResultSet object. | test_resultset_error | python | influxdata/influxdb-python | influxdb/tests/resultset_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/resultset_test.py | MIT |
def test_make_lines(self):
"""Test make new lines in TestLineProtocol object."""
data = {
"tags": {
"empty_tag": "",
"none_tag": None,
"backslash_tag": "C:\\",
"integer_tag": 2,
"string_tag": "hello"
},
"points": [
{
"measurement": "test",
"fields": {
"string_val": "hello!",
"int_val": 1,
"float_val": 1.1,
"none_field": None,
"bool_val": True,
}
}
]
}
self.assertEqual(
line_protocol.make_lines(data),
'test,backslash_tag=C:\\\\,integer_tag=2,string_tag=hello '
'bool_val=True,float_val=1.1,int_val=1i,string_val="hello!"\n'
) | Test make new lines in TestLineProtocol object. | test_make_lines | python | influxdata/influxdb-python | influxdb/tests/test_line_protocol.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/test_line_protocol.py | MIT |
def test_string_val_newline(self):
"""Test string value with newline in TestLineProtocol object."""
data = {
"points": [
{
"measurement": "m1",
"fields": {
"multi_line": "line1\nline1\nline3"
}
}
]
}
self.assertEqual(
line_protocol.make_lines(data),
'm1 multi_line="line1\\nline1\\nline3"\n'
) | Test string value with newline in TestLineProtocol object. | test_string_val_newline | python | influxdata/influxdb-python | influxdb/tests/test_line_protocol.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/test_line_protocol.py | MIT |
def test_make_lines_empty_field_string(self):
"""Test make lines with an empty string field."""
data = {
"points": [
{
"measurement": "test",
"fields": {
"string": "",
}
}
]
}
self.assertEqual(
line_protocol.make_lines(data),
'test string=""\n'
) | Test make lines with an empty string field. | test_make_lines_empty_field_string | python | influxdata/influxdb-python | influxdb/tests/test_line_protocol.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/test_line_protocol.py | MIT |
def test_tag_value_newline(self):
"""Test make lines with tag value contains newline."""
data = {
"tags": {
"t1": "line1\nline2"
},
"points": [
{
"measurement": "test",
"fields": {
"val": "hello"
}
}
]
}
self.assertEqual(
line_protocol.make_lines(data),
'test,t1=line1\\nline2 val="hello"\n'
) | Test make lines with tag value contains newline. | test_tag_value_newline | python | influxdata/influxdb-python | influxdb/tests/test_line_protocol.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/test_line_protocol.py | MIT |
def test_float_with_long_decimal_fraction(self):
"""Ensure precision is preserved when casting floats into strings."""
data = {
"points": [
{
"measurement": "test",
"fields": {
"float_val": 1.0000000000000009,
}
}
]
}
self.assertEqual(
line_protocol.make_lines(data),
'test float_val=1.0000000000000009\n'
) | Ensure precision is preserved when casting floats into strings. | test_float_with_long_decimal_fraction | python | influxdata/influxdb-python | influxdb/tests/test_line_protocol.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/test_line_protocol.py | MIT |
def test_float_with_long_decimal_fraction_as_type_decimal(self):
"""Ensure precision is preserved when casting Decimal into strings."""
data = {
"points": [
{
"measurement": "test",
"fields": {
"float_val": Decimal(0.8289445733333332),
}
}
]
}
self.assertEqual(
line_protocol.make_lines(data),
'test float_val=0.8289445733333332\n'
) | Ensure precision is preserved when casting Decimal into strings. | test_float_with_long_decimal_fraction_as_type_decimal | python | influxdata/influxdb-python | influxdb/tests/test_line_protocol.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/test_line_protocol.py | MIT |
def test_scheme(self):
"""Test database scheme for TestInfluxDBClient object."""
cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
self.assertEqual(cli._baseurl, 'http://host:8086')
cli = InfluxDBClient(
'host', 8086, 'username', 'password', 'database', ssl=True
)
self.assertEqual(cli._baseurl, 'https://host:8086') | Test database scheme for TestInfluxDBClient object. | test_scheme | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_dsn(self):
"""Test datasource name for TestInfluxDBClient object."""
cli = InfluxDBClient.from_dsn(self.dsn_string)
self.assertEqual('http://host:1886', cli._baseurl)
self.assertEqual('uSr', cli._username)
self.assertEqual('pWd', cli._password)
self.assertEqual('db', cli._database)
self.assertFalse(cli._use_udp)
cli = InfluxDBClient.from_dsn('udp+' + self.dsn_string)
self.assertTrue(cli._use_udp)
cli = InfluxDBClient.from_dsn('https+' + self.dsn_string)
self.assertEqual('https://host:1886', cli._baseurl)
cli = InfluxDBClient.from_dsn('https+' + self.dsn_string,
**{'ssl': False})
self.assertEqual('http://host:1886', cli._baseurl) | Test datasource name for TestInfluxDBClient object. | test_dsn | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_switch_database(self):
"""Test switch database for TestInfluxDBClient object."""
cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
cli.switch_database('another_database')
self.assertEqual(cli._database, 'another_database') | Test switch database for TestInfluxDBClient object. | test_switch_database | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_switch_db_deprecated(self):
"""Test deprecated switch database for TestInfluxDBClient object."""
cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
cli.switch_db('another_database')
self.assertEqual(cli._database, 'another_database') | Test deprecated switch database for TestInfluxDBClient object. | test_switch_db_deprecated | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_switch_user(self):
"""Test switch user for TestInfluxDBClient object."""
cli = InfluxDBClient('host', 8086, 'username', 'password', 'database')
cli.switch_user('another_username', 'another_password')
self.assertEqual(cli._username, 'another_username')
self.assertEqual(cli._password, 'another_password') | Test switch user for TestInfluxDBClient object. | test_switch_user | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write(self):
"""Test write to database for TestInfluxDBClient object."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/write"
)
cli = InfluxDBClient(database='db')
cli.write(
{"database": "mydb",
"retentionPolicy": "mypolicy",
"points": [{"name": "cpu_load_short",
"tags": {"host": "server01",
"region": "us-west"},
"timestamp": "2009-11-10T23:00:00Z",
"values": {"value": 0.64}}]}
)
self.assertEqual(
json.loads(m.last_request.body),
{"database": "mydb",
"retentionPolicy": "mypolicy",
"points": [{"name": "cpu_load_short",
"tags": {"host": "server01",
"region": "us-west"},
"timestamp": "2009-11-10T23:00:00Z",
"values": {"value": 0.64}}]}
) | Test write to database for TestInfluxDBClient object. | test_write | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points(self):
"""Test write points for TestInfluxDBClient object."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/db/db/series"
)
cli = InfluxDBClient(database='db')
cli.write_points(
self.dummy_points
)
self.assertListEqual(
json.loads(m.last_request.body),
self.dummy_points
) | Test write points for TestInfluxDBClient object. | test_write_points | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_string(self):
"""Test write string points for TestInfluxDBClient object."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/db/db/series"
)
cli = InfluxDBClient(database='db')
cli.write_points(
str(json.dumps(self.dummy_points))
)
self.assertListEqual(
json.loads(m.last_request.body),
self.dummy_points
) | Test write string points for TestInfluxDBClient object. | test_write_points_string | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_batch(self):
"""Test write batch points for TestInfluxDBClient object."""
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = InfluxDBClient('localhost', 8086,
'username', 'password', 'db')
cli.write_points(data=self.dummy_points, batch_size=2)
self.assertEqual(1, m.call_count) | Test write batch points for TestInfluxDBClient object. | test_write_points_batch | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_batch_invalid_size(self):
"""Test write batch points invalid size for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = InfluxDBClient('localhost', 8086,
'username', 'password', 'db')
cli.write_points(data=self.dummy_points, batch_size=-2)
self.assertEqual(1, m.call_count) | Test write batch points invalid size for TestInfluxDBClient. | test_write_points_batch_invalid_size | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_batch_multiple_series(self):
"""Test write points batch multiple series."""
dummy_points = [
{"points": [["1", 1, 1.0], ["2", 2, 2.0], ["3", 3, 3.0],
["4", 4, 4.0], ["5", 5, 5.0]],
"name": "foo",
"columns": ["val1", "val2", "val3"]},
{"points": [["1", 1, 1.0], ["2", 2, 2.0], ["3", 3, 3.0],
["4", 4, 4.0], ["5", 5, 5.0], ["6", 6, 6.0],
["7", 7, 7.0], ["8", 8, 8.0]],
"name": "bar",
"columns": ["val1", "val2", "val3"]},
]
expected_last_body = [{'points': [['7', 7, 7.0], ['8', 8, 8.0]],
'name': 'bar',
'columns': ['val1', 'val2', 'val3']}]
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = InfluxDBClient('localhost', 8086,
'username', 'password', 'db')
cli.write_points(data=dummy_points, batch_size=3)
self.assertEqual(m.call_count, 5)
self.assertEqual(expected_last_body, m.request_history[4].json()) | Test write points batch multiple series. | test_write_points_batch_multiple_series | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_udp(self):
"""Test write points UDP for TestInfluxDBClient object."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = random.randint(4000, 8000)
s.bind(('0.0.0.0', port))
cli = InfluxDBClient(
'localhost', 8086, 'root', 'root',
'test', use_udp=True, udp_port=port
)
cli.write_points(self.dummy_points)
received_data, addr = s.recvfrom(1024)
self.assertEqual(self.dummy_points,
json.loads(received_data.decode(), strict=True)) | Test write points UDP for TestInfluxDBClient object. | test_write_points_udp | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_fails(self):
"""Test failed write points for TestInfluxDBClient object."""
with _mocked_session('post', 500):
cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
cli.write_points([]) | Test failed write points for TestInfluxDBClient object. | test_write_points_fails | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_bad_precision(self):
"""Test write points with bad precision."""
cli = InfluxDBClient()
with self.assertRaisesRegexp(
Exception,
"Invalid time precision is given. \(use 's', 'm', 'ms' or 'u'\)"
):
cli.write_points(
self.dummy_points,
time_precision='g'
) | Test write points with bad precision. | test_write_points_bad_precision | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_with_precision_fails(self):
"""Test write points where precision fails."""
with _mocked_session('post', 500):
cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
cli.write_points_with_precision([]) | Test write points where precision fails. | test_write_points_with_precision_fails | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_delete_points(self):
"""Test delete points for TestInfluxDBClient object."""
with _mocked_session('delete', 204) as mocked:
cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
self.assertTrue(cli.delete_points("foo"))
self.assertEqual(len(mocked.call_args_list), 1)
args, kwds = mocked.call_args_list[0]
self.assertEqual(kwds['params'],
{'u': 'username', 'p': 'password'})
self.assertEqual(kwds['url'], 'http://host:8086/db/db/series/foo') | Test delete points for TestInfluxDBClient object. | test_delete_points | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_delete_points_with_wrong_name(self):
"""Test delete points with wrong name."""
with _mocked_session('delete', 400):
cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
cli.delete_points("nonexist") | Test delete points with wrong name. | test_delete_points_with_wrong_name | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_query_chunked(self):
"""Test chunked query for TestInfluxDBClient object."""
cli = InfluxDBClient(database='db')
example_object = {
'points': [
[1415206250119, 40001, 667],
[1415206244555, 30001, 7],
[1415206228241, 20001, 788],
[1415206212980, 10001, 555],
[1415197271586, 10001, 23]
],
'name': 'foo',
'columns': [
'time',
'sequence_number',
'val'
]
}
example_response = \
json.dumps(example_object) + json.dumps(example_object)
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.GET,
"http://localhost:8086/db/db/series",
text=example_response
)
self.assertListEqual(
cli.query('select * from foo', chunked=True),
[example_object, example_object]
) | Test chunked query for TestInfluxDBClient object. | test_query_chunked | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_query_chunked_unicode(self):
"""Test unicode chunked query for TestInfluxDBClient object."""
cli = InfluxDBClient(database='db')
example_object = {
'points': [
[1415206212980, 10001, u('unicode-\xcf\x89')],
[1415197271586, 10001, u('more-unicode-\xcf\x90')]
],
'name': 'foo',
'columns': [
'time',
'sequence_number',
'val'
]
}
example_response = \
json.dumps(example_object) + json.dumps(example_object)
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.GET,
"http://localhost:8086/db/db/series",
text=example_response
)
self.assertListEqual(
cli.query('select * from foo', chunked=True),
[example_object, example_object]
) | Test unicode chunked query for TestInfluxDBClient object. | test_query_chunked_unicode | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_query_bad_precision(self):
"""Test query with bad precision for TestInfluxDBClient."""
cli = InfluxDBClient()
with self.assertRaisesRegexp(
Exception,
"Invalid time precision is given. \(use 's', 'm', 'ms' or 'u'\)"
):
cli.query('select column_one from foo', time_precision='g') | Test query with bad precision for TestInfluxDBClient. | test_query_bad_precision | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_create_database_fails(self):
"""Test failed create database for TestInfluxDBClient."""
with _mocked_session('post', 401):
cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
cli.create_database('new_db') | Test failed create database for TestInfluxDBClient. | test_create_database_fails | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_delete_database_fails(self):
"""Test failed delete database for TestInfluxDBClient."""
with _mocked_session('delete', 401):
cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
cli.delete_database('old_db') | Test failed delete database for TestInfluxDBClient. | test_delete_database_fails | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_get_list_database(self):
"""Test get list of databases for TestInfluxDBClient."""
data = [
{"name": "a_db"}
]
with _mocked_session('get', 200, data):
cli = InfluxDBClient('host', 8086, 'username', 'password')
self.assertEqual(len(cli.get_list_database()), 1)
self.assertEqual(cli.get_list_database()[0]['name'], 'a_db') | Test get list of databases for TestInfluxDBClient. | test_get_list_database | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_get_list_database_fails(self):
"""Test failed get list of databases for TestInfluxDBClient."""
with _mocked_session('get', 401):
cli = InfluxDBClient('host', 8086, 'username', 'password')
cli.get_list_database() | Test failed get list of databases for TestInfluxDBClient. | test_get_list_database_fails | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_get_database_list_deprecated(self):
"""Test deprecated get database list for TestInfluxDBClient."""
data = [
{"name": "a_db"}
]
with _mocked_session('get', 200, data):
cli = InfluxDBClient('host', 8086, 'username', 'password')
self.assertEqual(len(cli.get_database_list()), 1)
self.assertEqual(cli.get_database_list()[0]['name'], 'a_db') | Test deprecated get database list for TestInfluxDBClient. | test_get_database_list_deprecated | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_delete_series_fails(self):
"""Test failed delete series for TestInfluxDBClient."""
with _mocked_session('delete', 401):
cli = InfluxDBClient('host', 8086, 'username', 'password', 'db')
cli.delete_series('old_series') | Test failed delete series for TestInfluxDBClient. | test_delete_series_fails | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_get_series_list(self):
"""Test get list of series for TestInfluxDBClient."""
cli = InfluxDBClient(database='db')
with requests_mock.Mocker() as m:
example_response = \
'[{"name":"list_series_result","columns":' \
'["time","name"],"points":[[0,"foo"],[0,"bar"]]}]'
m.register_uri(
requests_mock.GET,
"http://localhost:8086/db/db/series",
text=example_response
)
self.assertListEqual(
cli.get_list_series(),
['foo', 'bar']
) | Test get list of series for TestInfluxDBClient. | test_get_series_list | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_get_continuous_queries(self):
"""Test get continuous queries for TestInfluxDBClient."""
cli = InfluxDBClient(database='db')
with requests_mock.Mocker() as m:
# Tip: put this in a json linter!
example_response = '[ { "name": "continuous queries", "columns"' \
': [ "time", "id", "query" ], "points": [ [ ' \
'0, 1, "select foo(bar,95) from \\"foo_bar' \
's\\" group by time(5m) into response_times.' \
'percentiles.5m.95" ], [ 0, 2, "select perce' \
'ntile(value,95) from \\"response_times\\" g' \
'roup by time(5m) into response_times.percen' \
'tiles.5m.95" ] ] } ]'
m.register_uri(
requests_mock.GET,
"http://localhost:8086/db/db/series",
text=example_response
)
self.assertListEqual(
cli.get_list_continuous_queries(),
[
'select foo(bar,95) from "foo_bars" group '
'by time(5m) into response_times.percentiles.5m.95',
'select percentile(value,95) from "response_times" group '
'by time(5m) into response_times.percentiles.5m.95'
]
) | Test get continuous queries for TestInfluxDBClient. | test_get_continuous_queries | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_add_cluster_admin(self):
"""Test add cluster admin for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/cluster_admins"
)
cli = InfluxDBClient(database='db')
cli.add_cluster_admin(
new_username='paul',
new_password='laup'
)
self.assertDictEqual(
json.loads(m.last_request.body),
{
'name': 'paul',
'password': 'laup'
}
) | Test add cluster admin for TestInfluxDBClient. | test_add_cluster_admin | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_update_cluster_admin_password(self):
"""Test update cluster admin pass for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/cluster_admins/paul"
)
cli = InfluxDBClient(database='db')
cli.update_cluster_admin_password(
username='paul',
new_password='laup'
)
self.assertDictEqual(
json.loads(m.last_request.body),
{'password': 'laup'}
) | Test update cluster admin pass for TestInfluxDBClient. | test_update_cluster_admin_password | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_delete_cluster_admin(self):
"""Test delete cluster admin for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.DELETE,
"http://localhost:8086/cluster_admins/paul",
status_code=200,
)
cli = InfluxDBClient(database='db')
cli.delete_cluster_admin(username='paul')
self.assertIsNone(m.last_request.body) | Test delete cluster admin for TestInfluxDBClient. | test_delete_cluster_admin | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_alter_database_admin(self):
"""Test alter database admin for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/db/db/users/paul"
)
cli = InfluxDBClient(database='db')
cli.alter_database_admin(
username='paul',
is_admin=False
)
self.assertDictEqual(
json.loads(m.last_request.body),
{
'admin': False
}
) | Test alter database admin for TestInfluxDBClient. | test_alter_database_admin | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_get_database_users(self):
"""Test get database users for TestInfluxDBClient."""
cli = InfluxDBClient('localhost', 8086, 'username', 'password', 'db')
example_response = \
'[{"name":"paul","isAdmin":false,"writeTo":".*","readFrom":".*"},'\
'{"name":"bobby","isAdmin":false,"writeTo":".*","readFrom":".*"}]'
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.GET,
"http://localhost:8086/db/db/users",
text=example_response
)
users = cli.get_database_users()
self.assertEqual(json.loads(example_response), users) | Test get database users for TestInfluxDBClient. | test_get_database_users | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_add_database_user(self):
"""Test add database user for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/db/db/users"
)
cli = InfluxDBClient(database='db')
cli.add_database_user(
new_username='paul',
new_password='laup',
permissions=('.*', '.*')
)
self.assertDictEqual(
json.loads(m.last_request.body),
{
'writeTo': '.*',
'password': 'laup',
'readFrom': '.*',
'name': 'paul'
}
) | Test add database user for TestInfluxDBClient. | test_add_database_user | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_add_database_user_bad_permissions(self):
"""Test add database user with bad perms for TestInfluxDBClient."""
cli = InfluxDBClient()
with self.assertRaisesRegexp(
Exception,
"'permissions' must be \(readFrom, writeTo\) tuple"
):
cli.add_database_user(
new_password='paul',
new_username='paul',
permissions=('hello', 'hello', 'hello')
) | Test add database user with bad perms for TestInfluxDBClient. | test_add_database_user_bad_permissions | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_alter_database_user_password(self):
"""Test alter database user pass for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/db/db/users/paul"
)
cli = InfluxDBClient(database='db')
cli.alter_database_user(
username='paul',
password='n3wp4ss!'
)
self.assertDictEqual(
json.loads(m.last_request.body),
{
'password': 'n3wp4ss!'
}
) | Test alter database user pass for TestInfluxDBClient. | test_alter_database_user_password | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_alter_database_user_permissions(self):
"""Test alter database user perms for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/db/db/users/paul"
)
cli = InfluxDBClient(database='db')
cli.alter_database_user(
username='paul',
permissions=('^$', '.*')
)
self.assertDictEqual(
json.loads(m.last_request.body),
{
'readFrom': '^$',
'writeTo': '.*'
}
) | Test alter database user perms for TestInfluxDBClient. | test_alter_database_user_permissions | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_alter_database_user_password_and_permissions(self):
"""Test alter database user pass and perms for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/db/db/users/paul"
)
cli = InfluxDBClient(database='db')
cli.alter_database_user(
username='paul',
password='n3wp4ss!',
permissions=('^$', '.*')
)
self.assertDictEqual(
json.loads(m.last_request.body),
{
'password': 'n3wp4ss!',
'readFrom': '^$',
'writeTo': '.*'
}
) | Test alter database user pass and perms for TestInfluxDBClient. | test_alter_database_user_password_and_permissions | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_update_database_user_password_current_user(self):
"""Test update database user pass for TestInfluxDBClient."""
cli = InfluxDBClient(
username='root',
password='hello',
database='database'
)
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.POST,
"http://localhost:8086/db/database/users/root"
)
cli.update_database_user_password(
username='root',
new_password='bye'
)
self.assertEqual(cli._password, 'bye') | Test update database user pass for TestInfluxDBClient. | test_update_database_user_password_current_user | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_delete_database_user(self):
"""Test delete database user for TestInfluxDBClient."""
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.DELETE,
"http://localhost:8086/db/db/users/paul"
)
cli = InfluxDBClient(database='db')
cli.delete_database_user(username='paul')
self.assertIsNone(m.last_request.body) | Test delete database user for TestInfluxDBClient. | test_delete_database_user | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_request_retry(self, mock_request):
"""Test that two connection errors will be handled."""
class CustomMock(object):
"""Define CustomMock object."""
def __init__(self):
self.i = 0
def connection_error(self, *args, **kwargs):
"""Test connection error in CustomMock."""
self.i += 1
if self.i < 3:
raise requests.exceptions.ConnectionError
else:
r = requests.Response()
r.status_code = 200
return r
mock_request.side_effect = CustomMock().connection_error
cli = InfluxDBClient(database='db')
cli.write_points(
self.dummy_points
) | Test that two connection errors will be handled. | test_request_retry | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_request_retry_raises(self, mock_request):
"""Test that three connection errors will not be handled."""
class CustomMock(object):
"""Define CustomMock object."""
def __init__(self):
"""Initialize the object."""
self.i = 0
def connection_error(self, *args, **kwargs):
"""Test the connection error for CustomMock."""
self.i += 1
if self.i < 4:
raise requests.exceptions.ConnectionError
else:
r = requests.Response()
r.status_code = 200
return r
mock_request.side_effect = CustomMock().connection_error
cli = InfluxDBClient(database='db')
with self.assertRaises(requests.exceptions.ConnectionError):
cli.write_points(self.dummy_points) | Test that three connection errors will not be handled. | test_request_retry_raises | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def connection_error(self, *args, **kwargs):
"""Test the connection error for CustomMock."""
self.i += 1
if self.i < 4:
raise requests.exceptions.ConnectionError
else:
r = requests.Response()
r.status_code = 200
return r | Test the connection error for CustomMock. | connection_error | python | influxdata/influxdb-python | influxdb/tests/influxdb08/client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/client_test.py | MIT |
def test_write_points_from_dataframe_with_float_nan(self):
"""Test write points from dataframe with NaN float."""
now = pd.Timestamp('1970-01-01 00:00+00:00')
dataframe = pd.DataFrame(data=[[1, float("NaN"), 1.0], [2, 2, 2.0]],
index=[now, now + timedelta(hours=1)],
columns=["column_one", "column_two",
"column_three"])
points = [
{
"points": [
[1, None, 1.0, 0],
[2, 2, 2.0, 3600]
],
"name": "foo",
"columns": ["column_one", "column_two", "column_three", "time"]
}
]
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = DataFrameClient(database='db')
cli.write_points({"foo": dataframe})
self.assertListEqual(json.loads(m.last_request.body), points) | Test write points from dataframe with NaN float. | test_write_points_from_dataframe_with_float_nan | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def test_write_points_from_dataframe_in_batches(self):
"""Test write points from dataframe in batches."""
now = pd.Timestamp('1970-01-01 00:00+00:00')
dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
index=[now, now + timedelta(hours=1)],
columns=["column_one", "column_two",
"column_three"])
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = DataFrameClient(database='db')
self.assertTrue(cli.write_points({"foo": dataframe}, batch_size=1)) | Test write points from dataframe in batches. | test_write_points_from_dataframe_in_batches | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def test_write_points_from_dataframe_with_numeric_column_names(self):
"""Test write points from dataframe with numeric columns."""
now = pd.Timestamp('1970-01-01 00:00+00:00')
# df with numeric column names
dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
index=[now, now + timedelta(hours=1)])
points = [
{
"points": [
["1", 1, 1.0, 0],
["2", 2, 2.0, 3600]
],
"name": "foo",
"columns": ['0', '1', '2', "time"]
}
]
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = DataFrameClient(database='db')
cli.write_points({"foo": dataframe})
self.assertListEqual(json.loads(m.last_request.body), points) | Test write points from dataframe with numeric columns. | test_write_points_from_dataframe_with_numeric_column_names | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def test_write_points_from_dataframe_with_period_index(self):
"""Test write points from dataframe with period index."""
dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
index=[pd.Period('1970-01-01'),
pd.Period('1970-01-02')],
columns=["column_one", "column_two",
"column_three"])
points = [
{
"points": [
["1", 1, 1.0, 0],
["2", 2, 2.0, 86400]
],
"name": "foo",
"columns": ["column_one", "column_two", "column_three", "time"]
}
]
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = DataFrameClient(database='db')
cli.write_points({"foo": dataframe})
self.assertListEqual(json.loads(m.last_request.body), points) | Test write points from dataframe with period index. | test_write_points_from_dataframe_with_period_index | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def test_write_points_from_dataframe_with_time_precision(self):
"""Test write points from dataframe with time precision."""
now = pd.Timestamp('1970-01-01 00:00+00:00')
dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
index=[now, now + timedelta(hours=1)],
columns=["column_one", "column_two",
"column_three"])
points = [
{
"points": [
["1", 1, 1.0, 0],
["2", 2, 2.0, 3600]
],
"name": "foo",
"columns": ["column_one", "column_two", "column_three", "time"]
}
]
points_ms = copy.deepcopy(points)
points_ms[0]["points"][1][-1] = 3600 * 1000
points_us = copy.deepcopy(points)
points_us[0]["points"][1][-1] = 3600 * 1000000
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = DataFrameClient(database='db')
cli.write_points({"foo": dataframe}, time_precision='s')
self.assertListEqual(json.loads(m.last_request.body), points)
cli.write_points({"foo": dataframe}, time_precision='m')
self.assertListEqual(json.loads(m.last_request.body), points_ms)
cli.write_points({"foo": dataframe}, time_precision='u')
self.assertListEqual(json.loads(m.last_request.body), points_us) | Test write points from dataframe with time precision. | test_write_points_from_dataframe_with_time_precision | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def test_write_points_from_dataframe_fails_without_time_index(self):
"""Test write points from dataframe that fails without time index."""
dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]],
columns=["column_one", "column_two",
"column_three"])
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = DataFrameClient(database='db')
cli.write_points({"foo": dataframe}) | Test write points from dataframe that fails without time index. | test_write_points_from_dataframe_fails_without_time_index | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def test_write_points_from_dataframe_fails_with_series(self):
"""Test failed write points from dataframe with series."""
now = pd.Timestamp('1970-01-01 00:00+00:00')
dataframe = pd.Series(data=[1.0, 2.0],
index=[now, now + timedelta(hours=1)])
with requests_mock.Mocker() as m:
m.register_uri(requests_mock.POST,
"http://localhost:8086/db/db/series")
cli = DataFrameClient(database='db')
cli.write_points({"foo": dataframe}) | Test failed write points from dataframe with series. | test_write_points_from_dataframe_fails_with_series | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def test_query_multiple_time_series(self):
"""Test query for multiple time series."""
data = [
{
"name": "series1",
"columns": ["time", "mean", "min", "max", "stddev"],
"points": [[0, 323048, 323048, 323048, 0]]
},
{
"name": "series2",
"columns": ["time", "mean", "min", "max", "stddev"],
"points": [[0, -2.8233, -2.8503, -2.7832, 0.0173]]
},
{
"name": "series3",
"columns": ["time", "mean", "min", "max", "stddev"],
"points": [[0, -0.01220, -0.01220, -0.01220, 0]]
}
]
dataframes = {
'series1': pd.DataFrame(data=[[323048, 323048, 323048, 0]],
index=pd.to_datetime([0], unit='s',
utc=True),
columns=['mean', 'min', 'max', 'stddev']),
'series2': pd.DataFrame(data=[[-2.8233, -2.8503, -2.7832, 0.0173]],
index=pd.to_datetime([0], unit='s',
utc=True),
columns=['mean', 'min', 'max', 'stddev']),
'series3': pd.DataFrame(data=[[-0.01220, -0.01220, -0.01220, 0]],
index=pd.to_datetime([0], unit='s',
utc=True),
columns=['mean', 'min', 'max', 'stddev'])
}
with _mocked_session('get', 200, data):
cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
result = cli.query("""select mean(value), min(value), max(value),
stddev(value) from series1, series2, series3""")
self.assertEqual(dataframes.keys(), result.keys())
for key in dataframes.keys():
assert_frame_equal(dataframes[key], result[key]) | Test query for multiple time series. | test_query_multiple_time_series | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def test_list_series(self):
"""Test list of series for dataframe object."""
response = [
{
'columns': ['time', 'name'],
'name': 'list_series_result',
'points': [[0, 'seriesA'], [0, 'seriesB']]
}
]
with _mocked_session('get', 200, response):
cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
series_list = cli.get_list_series()
self.assertEqual(series_list, ['seriesA', 'seriesB']) | Test list of series for dataframe object. | test_list_series | python | influxdata/influxdb-python | influxdb/tests/influxdb08/dataframe_client_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/dataframe_client_test.py | MIT |
def setUpClass(cls):
"""Set up an instance of the TestSerisHelper object."""
super(TestSeriesHelper, cls).setUpClass()
TestSeriesHelper.client = InfluxDBClient(
'host',
8086,
'username',
'password',
'database'
)
class MySeriesHelper(SeriesHelper):
"""Define a subset SeriesHelper instance."""
class Meta:
"""Define metadata for the TestSeriesHelper object."""
client = TestSeriesHelper.client
series_name = 'events.stats.{server_name}'
fields = ['time', 'server_name']
bulk_size = 5
autocommit = True
TestSeriesHelper.MySeriesHelper = MySeriesHelper | Set up an instance of the TestSerisHelper object. | setUpClass | python | influxdata/influxdb-python | influxdb/tests/influxdb08/helper_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/helper_test.py | MIT |
def test_auto_commit(self):
"""Test that write_points called after the right number of events."""
class AutoCommitTest(SeriesHelper):
"""Define an instance of SeriesHelper for AutoCommit test."""
class Meta:
"""Define metadata AutoCommitTest object."""
series_name = 'events.stats.{server_name}'
fields = ['time', 'server_name']
bulk_size = 5
client = InfluxDBClient()
autocommit = True
fake_write_points = mock.MagicMock()
AutoCommitTest(server_name='us.east-1', time=159)
AutoCommitTest._client.write_points = fake_write_points
AutoCommitTest(server_name='us.east-1', time=158)
AutoCommitTest(server_name='us.east-1', time=157)
AutoCommitTest(server_name='us.east-1', time=156)
self.assertFalse(fake_write_points.called)
AutoCommitTest(server_name='us.east-1', time=3443)
self.assertTrue(fake_write_points.called) | Test that write_points called after the right number of events. | test_auto_commit | python | influxdata/influxdb-python | influxdb/tests/influxdb08/helper_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/helper_test.py | MIT |
def testSingleSeriesName(self):
"""Test JSON conversion when there is only one series name."""
TestSeriesHelper.MySeriesHelper(server_name='us.east-1', time=159)
TestSeriesHelper.MySeriesHelper(server_name='us.east-1', time=158)
TestSeriesHelper.MySeriesHelper(server_name='us.east-1', time=157)
TestSeriesHelper.MySeriesHelper(server_name='us.east-1', time=156)
expectation = [{'points': [[159, 'us.east-1'],
[158, 'us.east-1'],
[157, 'us.east-1'],
[156, 'us.east-1']],
'name': 'events.stats.us.east-1',
'columns': ['time', 'server_name']}]
rcvd = TestSeriesHelper.MySeriesHelper._json_body_()
self.assertTrue(all([el in expectation for el in rcvd]) and
all([el in rcvd for el in expectation]),
'Invalid JSON body of time series returned from '
'_json_body_ for one series name: {0}.'.format(rcvd))
TestSeriesHelper.MySeriesHelper._reset_()
self.assertEqual(
TestSeriesHelper.MySeriesHelper._json_body_(),
[],
'Resetting helper did not empty datapoints.') | Test JSON conversion when there is only one series name. | testSingleSeriesName | python | influxdata/influxdb-python | influxdb/tests/influxdb08/helper_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/helper_test.py | MIT |
def testSeveralSeriesNames(self):
"""Test JSON conversion when there is only one series name."""
TestSeriesHelper.MySeriesHelper(server_name='us.east-1', time=159)
TestSeriesHelper.MySeriesHelper(server_name='fr.paris-10', time=158)
TestSeriesHelper.MySeriesHelper(server_name='lu.lux', time=157)
TestSeriesHelper.MySeriesHelper(server_name='uk.london', time=156)
expectation = [{'points': [[157, 'lu.lux']],
'name': 'events.stats.lu.lux',
'columns': ['time', 'server_name']},
{'points': [[156, 'uk.london']],
'name': 'events.stats.uk.london',
'columns': ['time', 'server_name']},
{'points': [[158, 'fr.paris-10']],
'name': 'events.stats.fr.paris-10',
'columns': ['time', 'server_name']},
{'points': [[159, 'us.east-1']],
'name': 'events.stats.us.east-1',
'columns': ['time', 'server_name']}]
rcvd = TestSeriesHelper.MySeriesHelper._json_body_()
self.assertTrue(all([el in expectation for el in rcvd]) and
all([el in rcvd for el in expectation]),
'Invalid JSON body of time series returned from '
'_json_body_ for several series names: {0}.'
.format(rcvd))
TestSeriesHelper.MySeriesHelper._reset_()
self.assertEqual(
TestSeriesHelper.MySeriesHelper._json_body_(),
[],
'Resetting helper did not empty datapoints.') | Test JSON conversion when there is only one series name. | testSeveralSeriesNames | python | influxdata/influxdb-python | influxdb/tests/influxdb08/helper_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/helper_test.py | MIT |
def testWarnBulkSizeZero(self):
"""Test warning for an invalid bulk size."""
class WarnBulkSizeZero(SeriesHelper):
"""Define SeriesHelper for WarnBulkSizeZero test."""
class Meta:
"""Define metadata for WarnBulkSizeZero object."""
client = TestSeriesHelper.client
series_name = 'events.stats.{server_name}'
fields = ['time', 'server_name']
bulk_size = 0
autocommit = True
with warnings.catch_warnings(record=True) as rec_warnings:
warnings.simplefilter("always")
# Server defined in the client is invalid, we're testing
# the warning only.
with self.assertRaises(ConnectionError):
WarnBulkSizeZero(time=159, server_name='us.east-1')
self.assertGreaterEqual(
len(rec_warnings), 1,
'{0} call should have generated one warning.'
'Actual generated warnings: {1}'.format(
WarnBulkSizeZero, '\n'.join(map(str, rec_warnings))))
expected_msg = (
'Definition of bulk_size in WarnBulkSizeZero forced to 1, '
'was less than 1.')
self.assertIn(expected_msg, list(w.message.args[0]
for w in rec_warnings),
'Warning message did not contain "forced to 1".') | Test warning for an invalid bulk size. | testWarnBulkSizeZero | python | influxdata/influxdb-python | influxdb/tests/influxdb08/helper_test.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/influxdb08/helper_test.py | MIT |
def test_query_fail_ignore_errors(self):
"""Test query failed but ignore errors."""
result = self.cli.query('select column_one from foo',
raise_errors=False)
self.assertEqual(result.error, 'database not found: db') | Test query failed but ignore errors. | test_query_fail_ignore_errors | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_create_user_blank_password(self):
"""Test create user with a blank pass."""
self.cli.create_user('test_user', '')
rsp = list(self.cli.query("SHOW USERS")['results'])
self.assertIn({'user': 'test_user', 'admin': False},
rsp) | Test create user with a blank pass. | test_create_user_blank_password | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_revoke_admin_privileges(self):
"""Test revoking admin privs, deprecated as of v0.9.0."""
self.cli.create_user('test', 'test', admin=True)
self.assertEqual([{'user': 'test', 'admin': True}],
self.cli.get_list_users())
self.cli.revoke_admin_privileges('test')
self.assertEqual([{'user': 'test', 'admin': False}],
self.cli.get_list_users()) | Test revoking admin privs, deprecated as of v0.9.0. | test_revoke_admin_privileges | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_grant_privilege_invalid(self):
"""Test grant invalid privs to user."""
self.cli.create_user('test', 'test')
self.cli.create_database('testdb')
with self.assertRaises(InfluxDBClientError) as ctx:
self.cli.grant_privilege('', 'testdb', 'test')
self.assertEqual(400, ctx.exception.code)
self.assertIn('{"error":"error parsing query: ',
ctx.exception.content) | Test grant invalid privs to user. | test_grant_privilege_invalid | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_revoke_privilege_invalid(self):
"""Test revoke invalid privs from user."""
self.cli.create_user('test', 'test')
self.cli.create_database('testdb')
with self.assertRaises(InfluxDBClientError) as ctx:
self.cli.revoke_privilege('', 'testdb', 'test')
self.assertEqual(400, ctx.exception.code)
self.assertIn('{"error":"error parsing query: ',
ctx.exception.content) | Test revoke invalid privs from user. | test_revoke_privilege_invalid | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_write_check_read(self):
"""Test write and check read of data to server."""
self.test_write()
time.sleep(1)
rsp = self.cli.query('SELECT * FROM cpu_load_short', database='db')
self.assertListEqual([{'value': 0.64, 'time': '2009-11-10T23:00:00Z',
"host": "server01", "region": "us-west"}],
list(rsp.get_points())) | Test write and check read of data to server. | test_write_check_read | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_write_points_check_read(self):
"""Test writing points and check read back."""
self.test_write_points()
time.sleep(1) # same as test_write_check_read()
rsp = self.cli.query('SELECT * FROM cpu_load_short')
self.assertEqual(
list(rsp),
[[
{'value': 0.64,
'time': '2009-11-10T23:00:00Z',
"host": "server01",
"region": "us-west"}
]]
)
rsp2 = list(rsp.get_points())
self.assertEqual(len(rsp2), 1)
pt = rsp2[0]
self.assertEqual(
pt,
{'time': '2009-11-10T23:00:00Z',
'value': 0.64,
"host": "server01",
"region": "us-west"}
) | Test writing points and check read back. | test_write_points_check_read | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_write_points_check_read_DF(self):
"""Test write points and check back with dataframe."""
self.test_write_points_DF()
time.sleep(1) # same as test_write_check_read()
rsp = self.cliDF.query('SELECT * FROM cpu_load_short')
assert_frame_equal(
rsp['cpu_load_short'],
dummy_point_df['dataframe']
)
# Query with Tags
rsp = self.cliDF.query(
"SELECT * FROM cpu_load_short GROUP BY *")
assert_frame_equal(
rsp[('cpu_load_short',
(('host', 'server01'), ('region', 'us-west')))],
dummy_point_df['dataframe']
) | Test write points and check back with dataframe. | test_write_points_check_read_DF | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_write_multiple_points_different_series(self):
"""Test write multiple points to different series."""
self.assertIs(True, self.cli.write_points(dummy_points))
time.sleep(1)
rsp = self.cli.query('SELECT * FROM cpu_load_short')
lrsp = list(rsp)
self.assertEqual(
[[
{'value': 0.64,
'time': '2009-11-10T23:00:00Z',
"host": "server01",
"region": "us-west"}
]],
lrsp
)
rsp = list(self.cli.query('SELECT * FROM memory'))
self.assertEqual(
rsp,
[[
{'value': 33,
'time': '2009-11-10T23:01:35Z',
"host": "server01",
"region": "us-west"}
]]
) | Test write multiple points to different series. | test_write_multiple_points_different_series | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_write_multiple_points_different_series_DF(self):
"""Test write multiple points using dataframe to different series."""
for i in range(2):
self.assertIs(
True, self.cliDF.write_points(
dummy_points_df[i]['dataframe'],
dummy_points_df[i]['measurement'],
dummy_points_df[i]['tags']))
time.sleep(1)
rsp = self.cliDF.query('SELECT * FROM cpu_load_short')
assert_frame_equal(
rsp['cpu_load_short'],
dummy_points_df[0]['dataframe']
)
rsp = self.cliDF.query('SELECT * FROM memory')
assert_frame_equal(
rsp['memory'],
dummy_points_df[1]['dataframe']
) | Test write multiple points using dataframe to different series. | test_write_multiple_points_different_series_DF | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_write_points_batch_generator(self):
"""Test writing points in a batch from a generator."""
dummy_points = [
{"measurement": "cpu_usage", "tags": {"unit": "percent"},
"time": "2009-11-10T23:00:00Z", "fields": {"value": 12.34}},
{"measurement": "network", "tags": {"direction": "in"},
"time": "2009-11-10T23:00:00Z", "fields": {"value": 123.00}},
{"measurement": "network", "tags": {"direction": "out"},
"time": "2009-11-10T23:00:00Z", "fields": {"value": 12.00}}
]
dummy_points_generator = (point for point in dummy_points)
self.cli.write_points(points=dummy_points_generator,
tags={"host": "server01",
"region": "us-west"},
batch_size=2)
time.sleep(5)
net_in = self.cli.query("SELECT value FROM network "
"WHERE direction=$dir",
bind_params={'dir': 'in'}
).raw
net_out = self.cli.query("SELECT value FROM network "
"WHERE direction='out'").raw
cpu = self.cli.query("SELECT value FROM cpu_usage").raw
self.assertIn(123, net_in['series'][0]['values'][0])
self.assertIn(12, net_out['series'][0]['values'][0])
self.assertIn(12.34, cpu['series'][0]['values'][0]) | Test writing points in a batch from a generator. | test_write_points_batch_generator | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_query_chunked(self):
"""Test query for chunked response from server."""
cli = InfluxDBClient(database='db')
example_object = {
'points': [
[1415206250119, 40001, 667],
[1415206244555, 30001, 7],
[1415206228241, 20001, 788],
[1415206212980, 10001, 555],
[1415197271586, 10001, 23]
],
'name': 'foo',
'columns': [
'time',
'sequence_number',
'val'
]
}
del cli
del example_object
# TODO ? | Test query for chunked response from server. | test_query_chunked | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_create_retention_policy_default(self):
"""Test create a new default retention policy."""
self.cli.create_retention_policy('somename', '1d', 1, default=True)
self.cli.create_retention_policy('another', '2d', 1, default=False)
rsp = self.cli.get_list_retention_policies()
self.assertEqual(
[
{'duration': '0s',
'default': False,
'replicaN': 1,
'shardGroupDuration': u'168h0m0s',
'name': 'autogen'},
{'duration': '24h0m0s',
'default': True,
'replicaN': 1,
'shardGroupDuration': u'1h0m0s',
'name': 'somename'},
{'duration': '48h0m0s',
'default': False,
'replicaN': 1,
'shardGroupDuration': u'24h0m0s',
'name': 'another'}
],
rsp
) | Test create a new default retention policy. | test_create_retention_policy_default | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_create_retention_policy(self):
"""Test creating a new retention policy, not default."""
self.cli.create_retention_policy('somename', '1d', 1)
# NB: creating a retention policy without specifying
# shard group duration
# leads to a shard group duration of 1 hour
rsp = self.cli.get_list_retention_policies()
self.assertEqual(
[
{'duration': '0s',
'default': True,
'replicaN': 1,
'shardGroupDuration': u'168h0m0s',
'name': 'autogen'},
{'duration': '24h0m0s',
'default': False,
'replicaN': 1,
'shardGroupDuration': u'1h0m0s',
'name': 'somename'}
],
rsp
)
self.cli.drop_retention_policy('somename', 'db')
# recreate the RP
self.cli.create_retention_policy('somename', '1w', 1,
shard_duration='1h')
rsp = self.cli.get_list_retention_policies()
self.assertEqual(
[
{'duration': '0s',
'default': True,
'replicaN': 1,
'shardGroupDuration': u'168h0m0s',
'name': 'autogen'},
{'duration': '168h0m0s',
'default': False,
'replicaN': 1,
'shardGroupDuration': u'1h0m0s',
'name': 'somename'}
],
rsp
)
self.cli.drop_retention_policy('somename', 'db')
# recreate the RP
self.cli.create_retention_policy('somename', '1w', 1)
rsp = self.cli.get_list_retention_policies()
self.assertEqual(
[
{'duration': '0s',
'default': True,
'replicaN': 1,
'shardGroupDuration': u'168h0m0s',
'name': 'autogen'},
{'duration': '168h0m0s',
'default': False,
'replicaN': 1,
'shardGroupDuration': u'24h0m0s',
'name': 'somename'}
],
rsp
) | Test creating a new retention policy, not default. | test_create_retention_policy | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_alter_retention_policy(self):
"""Test alter a retention policy, not default."""
self.cli.create_retention_policy('somename', '1d', 1)
# Test alter duration
self.cli.alter_retention_policy('somename', 'db',
duration='4d',
shard_duration='2h')
# NB: altering retention policy doesn't change shard group duration
rsp = self.cli.get_list_retention_policies()
self.assertEqual(
[
{'duration': '0s',
'default': True,
'replicaN': 1,
'shardGroupDuration': u'168h0m0s',
'name': 'autogen'},
{'duration': '96h0m0s',
'default': False,
'replicaN': 1,
'shardGroupDuration': u'2h0m0s',
'name': 'somename'}
],
rsp
)
# Test alter replication
self.cli.alter_retention_policy('somename', 'db',
replication=4)
# NB: altering retention policy doesn't change shard group duration
rsp = self.cli.get_list_retention_policies()
self.assertEqual(
[
{'duration': '0s',
'default': True,
'replicaN': 1,
'shardGroupDuration': u'168h0m0s',
'name': 'autogen'},
{'duration': '96h0m0s',
'default': False,
'replicaN': 4,
'shardGroupDuration': u'2h0m0s',
'name': 'somename'}
],
rsp
)
# Test alter default
self.cli.alter_retention_policy('somename', 'db',
default=True)
# NB: altering retention policy doesn't change shard group duration
rsp = self.cli.get_list_retention_policies()
self.assertEqual(
[
{'duration': '0s',
'default': False,
'replicaN': 1,
'shardGroupDuration': u'168h0m0s',
'name': 'autogen'},
{'duration': '96h0m0s',
'default': True,
'replicaN': 4,
'shardGroupDuration': u'2h0m0s',
'name': 'somename'}
],
rsp
)
# Test alter shard_duration
self.cli.alter_retention_policy('somename', 'db',
shard_duration='4h')
rsp = self.cli.get_list_retention_policies()
self.assertEqual(
[
{'duration': '0s',
'default': False,
'replicaN': 1,
'shardGroupDuration': u'168h0m0s',
'name': 'autogen'},
{'duration': '96h0m0s',
'default': True,
'replicaN': 4,
'shardGroupDuration': u'4h0m0s',
'name': 'somename'}
],
rsp
) | Test alter a retention policy, not default. | test_alter_retention_policy | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def test_get_list_series(self):
"""Test get a list of series from the database."""
dummy_points = [
{
"measurement": "cpu_load_short",
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2009-11-10T23:00:00.123456Z",
"fields": {
"value": 0.64
}
}
]
dummy_points_2 = [
{
"measurement": "memory_usage",
"tags": {
"host": "server02",
"region": "us-east"
},
"time": "2009-11-10T23:00:00.123456Z",
"fields": {
"value": 80
}
}
]
self.cli.write_points(dummy_points)
self.cli.write_points(dummy_points_2)
self.assertEquals(
self.cli.get_list_series(),
['cpu_load_short,host=server01,region=us-west',
'memory_usage,host=server02,region=us-east']
)
self.assertEquals(
self.cli.get_list_series(measurement='memory_usage'),
['memory_usage,host=server02,region=us-east']
)
self.assertEquals(
self.cli.get_list_series(measurement='memory_usage'),
['memory_usage,host=server02,region=us-east']
)
self.assertEquals(
self.cli.get_list_series(tags={'host': 'server02'}),
['memory_usage,host=server02,region=us-east'])
self.assertEquals(
self.cli.get_list_series(
measurement='cpu_load_short', tags={'host': 'server02'}),
[]) | Test get a list of series from the database. | test_get_list_series | python | influxdata/influxdb-python | influxdb/tests/server_tests/client_test_with_server.py | https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/server_tests/client_test_with_server.py | MIT |
def extract_path_data_using_pen(self, font: hb.Font, char: str) -> GlyphPaths | None:
"""Extract glyph path data using the pen API."""
gid = font.get_nominal_glyph(ord(char))
if gid is None:
return None
container = []
font.draw_glyph(gid, self.draw_funcs, container)
return container | Extract glyph path data using the pen API. | extract_path_data_using_pen | python | SerCeMan/fontogen | fonts.py | https://github.com/SerCeMan/fontogen/blob/master/fonts.py | MIT |
def scale_and_translate_path_data(self, pen_data: GlyphPaths, max_dim: int, min_y_min: int) -> GlyphPaths:
"""
Scale the path data to fit within the target range, round to integers,
and then translate it to make all coordinates non-negative.
"""
target_range = self.glyph_res
all_coords = [coord for command, data in pen_data for coord in data]
x_coords, y_coords = zip(*all_coords)
# apply the vertical offset from the glyph
x_min, x_max = min(x_coords), max(x_coords)
y_min, y_max = min(y_coords), max(y_coords)
y_min = min(y_min, min_y_min)
scale_factor = target_range / max_dim
translated_and_scaled_pen_data = []
for command, data in pen_data:
scaled_data = tuple([(min(round((x - x_min) * scale_factor), target_range - 1),
min(round((y - y_min) * scale_factor), target_range - 1)) for x, y in data])
translated_and_scaled_pen_data.append((command, scaled_data))
return translated_and_scaled_pen_data |
Scale the path data to fit within the target range, round to integers,
and then translate it to make all coordinates non-negative.
| scale_and_translate_path_data | python | SerCeMan/fontogen | fonts.py | https://github.com/SerCeMan/fontogen/blob/master/fonts.py | MIT |
def top_k_top_p_filtering(logits: torch.Tensor, top_k=0, top_p=0.0, filter_value=-float('Inf')):
""" Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (vocabulary size)
top_k >0: keep only top k tokens with the highest probability (top-k filtering).
top_p >0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
"""
assert logits.dim() == 1 # batch size 1 for now - could be updated for more but the code would be less clear
top_k = min(top_k, logits.size(-1)) # Safety check
if top_k > 0:
# Remove all tokens with a probability less than the last token of the top-k
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = filter_value
if top_p > 0.0:
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above the threshold
sorted_indices_to_remove = cumulative_probs > top_p
# Shift the indices to the right to keep also the first token above the threshold
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
indices_to_remove = sorted_indices[sorted_indices_to_remove]
logits[indices_to_remove] = filter_value
return logits | Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (vocabulary size)
top_k >0: keep only top k tokens with the highest probability (top-k filtering).
top_p >0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
| top_k_top_p_filtering | python | SerCeMan/fontogen | sampler.py | https://github.com/SerCeMan/fontogen/blob/master/sampler.py | MIT |
def normalize(image):
"""Normalize input image channel-wise to zero mean and unit variance."""
image = image.transpose(2, 0, 1) # Switch to channel-first
mean, std = np.array(MEAN), np.array(STD)
image = (image - mean[:, None, None]) / std[:, None, None]
return image.transpose(1, 2, 0) | Normalize input image channel-wise to zero mean and unit variance. | normalize | python | google-research/augmix | augment_and_mix.py | https://github.com/google-research/augmix/blob/master/augment_and_mix.py | Apache-2.0 |
def augment_and_mix(image, severity=3, width=3, depth=-1, alpha=1.):
"""Perform AugMix augmentations and compute mixture.
Args:
image: Raw input image as float32 np.ndarray of shape (h, w, c)
severity: Severity of underlying augmentation operators (between 1 to 10).
width: Width of augmentation chain
depth: Depth of augmentation chain. -1 enables stochastic depth uniformly
from [1, 3]
alpha: Probability coefficient for Beta and Dirichlet distributions.
Returns:
mixed: Augmented and mixed image.
"""
ws = np.float32(
np.random.dirichlet([alpha] * width))
m = np.float32(np.random.beta(alpha, alpha))
mix = np.zeros_like(image)
for i in range(width):
image_aug = image.copy()
d = depth if depth > 0 else np.random.randint(1, 4)
for _ in range(d):
op = np.random.choice(augmentations.augmentations)
image_aug = apply_op(image_aug, op, severity)
# Preprocessing commutes since all coefficients are convex
mix += ws[i] * normalize(image_aug)
mixed = (1 - m) * normalize(image) + m * mix
return mixed | Perform AugMix augmentations and compute mixture.
Args:
image: Raw input image as float32 np.ndarray of shape (h, w, c)
severity: Severity of underlying augmentation operators (between 1 to 10).
width: Width of augmentation chain
depth: Depth of augmentation chain. -1 enables stochastic depth uniformly
from [1, 3]
alpha: Probability coefficient for Beta and Dirichlet distributions.
Returns:
mixed: Augmented and mixed image.
| augment_and_mix | python | google-research/augmix | augment_and_mix.py | https://github.com/google-research/augmix/blob/master/augment_and_mix.py | Apache-2.0 |
def get_lr(step, total_steps, lr_max, lr_min):
"""Compute learning rate according to cosine annealing schedule."""
return lr_min + (lr_max - lr_min) * 0.5 * (1 +
np.cos(step / total_steps * np.pi)) | Compute learning rate according to cosine annealing schedule. | get_lr | python | google-research/augmix | cifar.py | https://github.com/google-research/augmix/blob/master/cifar.py | Apache-2.0 |
def aug(image, preprocess):
"""Perform AugMix augmentations and compute mixture.
Args:
image: PIL.Image input image
preprocess: Preprocessing function which should return a torch tensor.
Returns:
mixed: Augmented and mixed image.
"""
aug_list = augmentations.augmentations
if args.all_ops:
aug_list = augmentations.augmentations_all
ws = np.float32(np.random.dirichlet([1] * args.mixture_width))
m = np.float32(np.random.beta(1, 1))
mix = torch.zeros_like(preprocess(image))
for i in range(args.mixture_width):
image_aug = image.copy()
depth = args.mixture_depth if args.mixture_depth > 0 else np.random.randint(
1, 4)
for _ in range(depth):
op = np.random.choice(aug_list)
image_aug = op(image_aug, args.aug_severity)
# Preprocessing commutes since all coefficients are convex
mix += ws[i] * preprocess(image_aug)
mixed = (1 - m) * preprocess(image) + m * mix
return mixed | Perform AugMix augmentations and compute mixture.
Args:
image: PIL.Image input image
preprocess: Preprocessing function which should return a torch tensor.
Returns:
mixed: Augmented and mixed image.
| aug | python | google-research/augmix | cifar.py | https://github.com/google-research/augmix/blob/master/cifar.py | Apache-2.0 |
def test_c(net, test_data, base_path):
"""Evaluate network on given corrupted dataset."""
corruption_accs = []
for corruption in CORRUPTIONS:
# Reference to original data is mutated
test_data.data = np.load(base_path + corruption + '.npy')
test_data.targets = torch.LongTensor(np.load(base_path + 'labels.npy'))
test_loader = torch.utils.data.DataLoader(
test_data,
batch_size=args.eval_batch_size,
shuffle=False,
num_workers=args.num_workers,
pin_memory=True)
test_loss, test_acc = test(net, test_loader)
corruption_accs.append(test_acc)
print('{}\n\tTest Loss {:.3f} | Test Error {:.3f}'.format(
corruption, test_loss, 100 - 100. * test_acc))
return np.mean(corruption_accs) | Evaluate network on given corrupted dataset. | test_c | python | google-research/augmix | cifar.py | https://github.com/google-research/augmix/blob/master/cifar.py | Apache-2.0 |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR (linearly scaled to batch size) decayed by 10 every n / 3 epochs."""
b = args.batch_size / 256.
k = args.epochs // 3
if epoch < k:
m = 1
elif epoch < 2 * k:
m = 0.1
else:
m = 0.01
lr = args.learning_rate * m * b
for param_group in optimizer.param_groups:
param_group['lr'] = lr | Sets the learning rate to the initial LR (linearly scaled to batch size) decayed by 10 every n / 3 epochs. | adjust_learning_rate | python | google-research/augmix | imagenet.py | https://github.com/google-research/augmix/blob/master/imagenet.py | Apache-2.0 |
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k."""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res | Computes the accuracy over the k top predictions for the specified values of k. | accuracy | python | google-research/augmix | imagenet.py | https://github.com/google-research/augmix/blob/master/imagenet.py | Apache-2.0 |
def compute_mce(corruption_accs):
"""Compute mCE (mean Corruption Error) normalized by AlexNet performance."""
mce = 0.
for i in range(len(CORRUPTIONS)):
avg_err = 1 - np.mean(corruption_accs[CORRUPTIONS[i]])
ce = 100 * avg_err / ALEXNET_ERR[i]
mce += ce / 15
return mce | Compute mCE (mean Corruption Error) normalized by AlexNet performance. | compute_mce | python | google-research/augmix | imagenet.py | https://github.com/google-research/augmix/blob/master/imagenet.py | Apache-2.0 |
def aug(image, preprocess):
"""Perform AugMix augmentations and compute mixture.
Args:
image: PIL.Image input image
preprocess: Preprocessing function which should return a torch tensor.
Returns:
mixed: Augmented and mixed image.
"""
aug_list = augmentations.augmentations
if args.all_ops:
aug_list = augmentations.augmentations_all
ws = np.float32(
np.random.dirichlet([args.aug_prob_coeff] * args.mixture_width))
m = np.float32(np.random.beta(args.aug_prob_coeff, args.aug_prob_coeff))
mix = torch.zeros_like(preprocess(image))
for i in range(args.mixture_width):
image_aug = image.copy()
depth = args.mixture_depth if args.mixture_depth > 0 else np.random.randint(
1, 4)
for _ in range(depth):
op = np.random.choice(aug_list)
image_aug = op(image_aug, args.aug_severity)
# Preprocessing commutes since all coefficients are convex
mix += ws[i] * preprocess(image_aug)
mixed = (1 - m) * preprocess(image) + m * mix
return mixed | Perform AugMix augmentations and compute mixture.
Args:
image: PIL.Image input image
preprocess: Preprocessing function which should return a torch tensor.
Returns:
mixed: Augmented and mixed image.
| aug | python | google-research/augmix | imagenet.py | https://github.com/google-research/augmix/blob/master/imagenet.py | Apache-2.0 |
def test_c(net, test_transform):
"""Evaluate network on given corrupted dataset."""
corruption_accs = {}
for c in CORRUPTIONS:
print(c)
for s in range(1, 6):
valdir = os.path.join(args.corrupted_data, c, str(s))
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, test_transform),
batch_size=args.eval_batch_size,
shuffle=False,
num_workers=args.num_workers,
pin_memory=True)
loss, acc1 = test(net, val_loader)
if c in corruption_accs:
corruption_accs[c].append(acc1)
else:
corruption_accs[c] = [acc1]
print('\ts={}: Test Loss {:.3f} | Test Acc1 {:.3f}'.format(
s, loss, 100. * acc1))
return corruption_accs | Evaluate network on given corrupted dataset. | test_c | python | google-research/augmix | imagenet.py | https://github.com/google-research/augmix/blob/master/imagenet.py | Apache-2.0 |
def __init__(self, path='config.yml'):
"""Constructor that will return an ATCconfig object holding the project configuration
Keyword Arguments:
path {str} -- 'Path of the local configuration file' (default: {'config.yml'})
"""
self.config_local = path
self.config_project = DEFAULT_PROJECT_CONFIG_PATH | Constructor that will return an ATCconfig object holding the project configuration
Keyword Arguments:
path {str} -- 'Path of the local configuration file' (default: {'config.yml'})
| __init__ | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
def config(self):
"""Get the whole configuration including local settings and additions.
This the configuation that is used by the application.
Returns:
config {dict} -- Dictionary object containing default settings, overriden by local settings if set.
"""
config_final = dict(self.config_project)
config_final.update(self.config_local)
return config_final | Get the whole configuration including local settings and additions.
This the configuation that is used by the application.
Returns:
config {dict} -- Dictionary object containing default settings, overriden by local settings if set.
| config | python | atc-project/atomic-threat-coverage | scripts/atcutils.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atcutils.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.