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_get_list_measurements(self): """Test get list of measurements for TestInfluxDBClient object.""" data = { "results": [{ "series": [ {"name": "measurements", "columns": ["name"], "values": [["cpu"], ["disk"] ]}]} ] } with _mocked_session(self.cli, 'get', 200, json.dumps(data)): self.assertListEqual( self.cli.get_list_measurements(), [{'name': 'cpu'}, {'name': 'disk'}] )
Test get list of measurements for TestInfluxDBClient object.
test_get_list_measurements
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_series(self): """Test get a list of series from the database.""" data = {'results': [ {'series': [ { 'values': [ ['cpu_load_short,host=server01,region=us-west'], ['memory_usage,host=server02,region=us-east']], 'columns': ['key'] } ]} ]} with _mocked_session(self.cli, 'get', 200, json.dumps(data)): self.assertListEqual( self.cli.get_list_series(), ['cpu_load_short,host=server01,region=us-west', 'memory_usage,host=server02,region=us-east'])
Test get a list of series from the database.
test_get_list_series
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_series_with_measurement(self): """Test get a list of series from the database by filter.""" data = {'results': [ {'series': [ { 'values': [ ['cpu_load_short,host=server01,region=us-west']], 'columns': ['key'] } ]} ]} with _mocked_session(self.cli, 'get', 200, json.dumps(data)): self.assertListEqual( self.cli.get_list_series(measurement='cpu_load_short'), ['cpu_load_short,host=server01,region=us-west'])
Test get a list of series from the database by filter.
test_get_list_series_with_measurement
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_series_with_tags(self): """Test get a list of series from the database by tags.""" data = {'results': [ {'series': [ { 'values': [ ['cpu_load_short,host=server01,region=us-west']], 'columns': ['key'] } ]} ]} with _mocked_session(self.cli, 'get', 200, json.dumps(data)): self.assertListEqual( self.cli.get_list_series(tags={'region': 'us-west'}), ['cpu_load_short,host=server01,region=us-west'])
Test get a list of series from the database by tags.
test_get_list_series_with_tags
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_series_fails(self): """Test get a list of series from the database but fail.""" cli = InfluxDBClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 401): cli.get_list_series()
Test get a list of series from the database but fail.
test_get_list_series_fails
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_create_retention_policy_default(self): """Test create default ret policy for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.create_retention_policy( 'somename', '1d', 4, default=True, database='db' ) self.assertEqual( m.last_request.qs['q'][0], 'create retention policy "somename" on ' '"db" duration 1d replication 4 shard duration 0s default' )
Test create default ret policy for TestInfluxDBClient object.
test_create_retention_policy_default
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_create_retention_policy(self): """Test create retention policy for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.create_retention_policy( 'somename', '1d', 4, database='db' ) self.assertEqual( m.last_request.qs['q'][0], 'create retention policy "somename" on ' '"db" duration 1d replication 4 shard duration 0s' )
Test create retention policy for TestInfluxDBClient object.
test_create_retention_policy
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_create_retention_policy_shard_duration(self): """Test create retention policy with a custom shard duration.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.create_retention_policy( 'somename2', '1d', 4, database='db', shard_duration='1h' ) self.assertEqual( m.last_request.qs['q'][0], 'create retention policy "somename2" on ' '"db" duration 1d replication 4 shard duration 1h' )
Test create retention policy with a custom shard duration.
test_create_retention_policy_shard_duration
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_create_retention_policy_shard_duration_default(self): """Test create retention policy with a default shard duration.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.create_retention_policy( 'somename3', '1d', 4, database='db', shard_duration='1h', default=True ) self.assertEqual( m.last_request.qs['q'][0], 'create retention policy "somename3" on ' '"db" duration 1d replication 4 shard duration 1h ' 'default' )
Test create retention policy with a default shard duration.
test_create_retention_policy_shard_duration_default
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_alter_retention_policy(self): """Test alter retention policy for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) # Test alter duration self.cli.alter_retention_policy('somename', 'db', duration='4d') self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" duration 4d' ) # Test alter replication self.cli.alter_retention_policy('somename', 'db', replication=4) self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" replication 4' ) # Test alter shard duration self.cli.alter_retention_policy('somename', 'db', shard_duration='1h') self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" shard duration 1h' ) # Test alter default self.cli.alter_retention_policy('somename', 'db', default=True) self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" default' )
Test alter retention policy for TestInfluxDBClient object.
test_alter_retention_policy
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_alter_retention_policy_invalid(self): """Test invalid alter ret policy for TestInfluxDBClient object.""" cli = InfluxDBClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 400): self.cli.alter_retention_policy('somename', 'db')
Test invalid alter ret policy for TestInfluxDBClient object.
test_alter_retention_policy_invalid
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_drop_retention_policy(self): """Test drop retention policy for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.drop_retention_policy('somename', 'db') self.assertEqual( m.last_request.qs['q'][0], 'drop retention policy "somename" on "db"' )
Test drop retention policy for TestInfluxDBClient object.
test_drop_retention_policy
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_drop_retention_policy_fails(self): """Test failed drop ret policy for TestInfluxDBClient object.""" cli = InfluxDBClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'delete', 401): cli.drop_retention_policy('default', 'db')
Test failed drop ret policy for TestInfluxDBClient object.
test_drop_retention_policy_fails
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_retention_policies(self): """Test get retention policies for TestInfluxDBClient object.""" example_response = \ '{"results": [{"series": [{"values": [["fsfdsdf", "24h0m0s", 2]],'\ ' "columns": ["name", "duration", "replicaN"]}]}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.GET, "http://localhost:8086/query", text=example_response ) self.assertListEqual( self.cli.get_list_retention_policies("db"), [{'duration': '24h0m0s', 'name': 'fsfdsdf', 'replicaN': 2}] )
Test get retention policies for TestInfluxDBClient object.
test_get_list_retention_policies
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_request_retry(self, mock_request): """Test that two connection errors will be handled.""" class CustomMock(object): """Create custom mock object for test.""" def __init__(self): self.i = 0 def connection_error(self, *args, **kwargs): """Handle a connection error for the CustomMock object.""" self.i += 1 if self.i < 3: raise requests.exceptions.ConnectionError r = requests.Response() r.status_code = 204 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/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def connection_error(self, *args, **kwargs): """Handle a connection error for the CustomMock object.""" self.i += 1 if self.i < 3: raise requests.exceptions.ConnectionError r = requests.Response() r.status_code = 204 return r
Handle a connection error for the CustomMock object.
connection_error
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_request_retry_raises(self, mock_request): """Test that three requests errors will not be handled.""" class CustomMock(object): """Create custom mock object for test.""" def __init__(self): self.i = 0 def connection_error(self, *args, **kwargs): """Handle a connection error for the CustomMock object.""" self.i += 1 if self.i < 4: raise requests.exceptions.HTTPError 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.HTTPError): cli.write_points(self.dummy_points)
Test that three requests errors will not be handled.
test_request_retry_raises
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def connection_error(self, *args, **kwargs): """Handle a connection error for the CustomMock object.""" self.i += 1 if self.i < 4: raise requests.exceptions.HTTPError else: r = requests.Response() r.status_code = 200 return r
Handle a connection error for the CustomMock object.
connection_error
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_random_request_retry(self, mock_request): """Test that a random number of connection errors will be handled.""" class CustomMock(object): """Create custom mock object for test.""" def __init__(self, retries): self.i = 0 self.retries = retries def connection_error(self, *args, **kwargs): """Handle a connection error for the CustomMock object.""" self.i += 1 if self.i < self.retries: raise requests.exceptions.ConnectionError else: r = requests.Response() r.status_code = 204 return r retries = random.randint(1, 5) mock_request.side_effect = CustomMock(retries).connection_error cli = InfluxDBClient(database='db', retries=retries) cli.write_points(self.dummy_points)
Test that a random number of connection errors will be handled.
test_random_request_retry
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def connection_error(self, *args, **kwargs): """Handle a connection error for the CustomMock object.""" self.i += 1 if self.i < self.retries: raise requests.exceptions.ConnectionError else: r = requests.Response() r.status_code = 204 return r
Handle a connection error for the CustomMock object.
connection_error
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_random_request_retry_raises(self, mock_request): """Test a random number of conn errors plus one will not be handled.""" class CustomMock(object): """Create custom mock object for test.""" def __init__(self, retries): self.i = 0 self.retries = retries def connection_error(self, *args, **kwargs): """Handle a connection error for the CustomMock object.""" self.i += 1 if self.i < self.retries + 1: raise requests.exceptions.ConnectionError else: r = requests.Response() r.status_code = 200 return r retries = random.randint(1, 5) mock_request.side_effect = CustomMock(retries).connection_error cli = InfluxDBClient(database='db', retries=retries) with self.assertRaises(requests.exceptions.ConnectionError): cli.write_points(self.dummy_points)
Test a random number of conn errors plus one will not be handled.
test_random_request_retry_raises
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def connection_error(self, *args, **kwargs): """Handle a connection error for the CustomMock object.""" self.i += 1 if self.i < self.retries + 1: raise requests.exceptions.ConnectionError else: r = requests.Response() r.status_code = 200 return r
Handle a connection error for the CustomMock object.
connection_error
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_users(self): """Test get users for TestInfluxDBClient object.""" example_response = ( '{"results":[{"series":[{"columns":["user","admin"],' '"values":[["test",false]]}]}]}' ) with requests_mock.Mocker() as m: m.register_uri( requests_mock.GET, "http://localhost:8086/query", text=example_response ) self.assertListEqual( self.cli.get_list_users(), [{'user': 'test', 'admin': False}] )
Test get users for TestInfluxDBClient object.
test_get_list_users
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_users_empty(self): """Test get empty userlist for TestInfluxDBClient object.""" example_response = ( '{"results":[{"series":[{"columns":["user","admin"]}]}]}' ) with requests_mock.Mocker() as m: m.register_uri( requests_mock.GET, "http://localhost:8086/query", text=example_response ) self.assertListEqual(self.cli.get_list_users(), [])
Test get empty userlist for TestInfluxDBClient object.
test_get_list_users_empty
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_grant_admin_privileges(self): """Test grant admin privs for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.grant_admin_privileges('test') self.assertEqual( m.last_request.qs['q'][0], 'grant all privileges to "test"' )
Test grant admin privs for TestInfluxDBClient object.
test_grant_admin_privileges
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_grant_admin_privileges_invalid(self): """Test grant invalid admin privs for TestInfluxDBClient object.""" cli = InfluxDBClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 400): self.cli.grant_admin_privileges('')
Test grant invalid admin privs for TestInfluxDBClient object.
test_grant_admin_privileges_invalid
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_revoke_admin_privileges(self): """Test revoke admin privs for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.revoke_admin_privileges('test') self.assertEqual( m.last_request.qs['q'][0], 'revoke all privileges from "test"' )
Test revoke admin privs for TestInfluxDBClient object.
test_revoke_admin_privileges
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_revoke_admin_privileges_invalid(self): """Test revoke invalid admin privs for TestInfluxDBClient object.""" cli = InfluxDBClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 400): self.cli.revoke_admin_privileges('')
Test revoke invalid admin privs for TestInfluxDBClient object.
test_revoke_admin_privileges_invalid
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_grant_privilege(self): """Test grant privs for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.grant_privilege('read', 'testdb', 'test') self.assertEqual( m.last_request.qs['q'][0], 'grant read on "testdb" to "test"' )
Test grant privs for TestInfluxDBClient object.
test_grant_privilege
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_grant_privilege_invalid(self): """Test grant invalid privs for TestInfluxDBClient object.""" cli = InfluxDBClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 400): self.cli.grant_privilege('', 'testdb', 'test')
Test grant invalid privs for TestInfluxDBClient object.
test_grant_privilege_invalid
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_revoke_privilege(self): """Test revoke privs for TestInfluxDBClient object.""" example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) self.cli.revoke_privilege('read', 'testdb', 'test') self.assertEqual( m.last_request.qs['q'][0], 'revoke read on "testdb" from "test"' )
Test revoke privs for TestInfluxDBClient object.
test_revoke_privilege
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_revoke_privilege_invalid(self): """Test revoke invalid privs for TestInfluxDBClient object.""" cli = InfluxDBClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 400): self.cli.revoke_privilege('', 'testdb', 'test')
Test revoke invalid privs for TestInfluxDBClient object.
test_revoke_privilege_invalid
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_privileges(self): """Test get list of privs for TestInfluxDBClient object.""" data = {'results': [ {'series': [ {'columns': ['database', 'privilege'], 'values': [ ['db1', 'READ'], ['db2', 'ALL PRIVILEGES'], ['db3', 'NO PRIVILEGES']]} ]} ]} with _mocked_session(self.cli, 'get', 200, json.dumps(data)): self.assertListEqual( self.cli.get_list_privileges('test'), [{'database': 'db1', 'privilege': 'READ'}, {'database': 'db2', 'privilege': 'ALL PRIVILEGES'}, {'database': 'db3', 'privilege': 'NO PRIVILEGES'}] )
Test get list of privs for TestInfluxDBClient object.
test_get_list_privileges
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_privileges_fails(self): """Test failed get list of privs for TestInfluxDBClient object.""" cli = InfluxDBClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 401): cli.get_list_privileges('test')
Test failed get list of privs for TestInfluxDBClient object.
test_get_list_privileges_fails
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_get_list_continuous_queries(self): """Test getting a list of continuous queries.""" data = { "results": [ { "statement_id": 0, "series": [ { "name": "testdb01", "columns": ["name", "query"], "values": [["testname01", "testquery01"], ["testname02", "testquery02"]] }, { "name": "testdb02", "columns": ["name", "query"], "values": [["testname03", "testquery03"]] }, { "name": "testdb03", "columns": ["name", "query"] } ] } ] } with _mocked_session(self.cli, 'get', 200, json.dumps(data)): self.assertListEqual( self.cli.get_list_continuous_queries(), [ { 'testdb01': [ {'name': 'testname01', 'query': 'testquery01'}, {'name': 'testname02', 'query': 'testquery02'} ] }, { 'testdb02': [ {'name': 'testname03', 'query': 'testquery03'} ] }, { 'testdb03': [] } ] )
Test getting a list of continuous queries.
test_get_list_continuous_queries
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_create_continuous_query_fails(self): """Test failing to create a continuous query.""" with _mocked_session(self.cli, 'get', 400): self.cli.create_continuous_query('cq_name', 'select', 'db_name')
Test failing to create a continuous query.
test_create_continuous_query_fails
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_invalid_port_fails(self): """Test invalid port fail for TestInfluxDBClient object.""" with self.assertRaises(ValueError): InfluxDBClient('host', '80/redir', 'username', 'password')
Test invalid port fail for TestInfluxDBClient object.
test_invalid_port_fails
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_chunked_response(self): """Test chunked response for TestInfluxDBClient object.""" example_response = \ u'{"results":[{"statement_id":0,"series":[{"columns":["key"],' \ '"values":[["cpu"],["memory"],["iops"],["network"]],"partial":' \ 'true}],"partial":true}]}\n{"results":[{"statement_id":0,' \ '"series":[{"columns":["key"],"values":[["qps"],["uptime"],' \ '["df"],["mount"]]}]}]}\n' with requests_mock.Mocker() as m: m.register_uri( requests_mock.GET, "http://localhost:8086/query", text=example_response ) response = self.cli.query('show series', chunked=True, chunk_size=4) res = list(response) self.assertTrue(len(res) == 2) self.assertEqual(res[0].__repr__(), ResultSet( {'series': [{ 'columns': ['key'], 'values': [['cpu'], ['memory'], ['iops'], ['network']] }]}).__repr__()) self.assertEqual(res[1].__repr__(), ResultSet( {'series': [{ 'columns': ['key'], 'values': [['qps'], ['uptime'], ['df'], ['mount']] }]}).__repr__())
Test chunked response for TestInfluxDBClient object.
test_chunked_response
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_auth_username_password(self): """Test auth with custom username and password.""" with requests_mock.Mocker() as m: m.register_uri( requests_mock.GET, "http://localhost:8086/ping", status_code=204, headers={'X-Influxdb-Version': '1.2.3'} ) cli = InfluxDBClient(username='my-username', password='my-password') cli.ping() self.assertEqual(m.last_request.headers["Authorization"], "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=")
Test auth with custom username and password.
test_auth_username_password
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_auth_username_password_none(self): """Test auth with not defined username or password.""" with requests_mock.Mocker() as m: m.register_uri( requests_mock.GET, "http://localhost:8086/ping", status_code=204, headers={'X-Influxdb-Version': '1.2.3'} ) cli = InfluxDBClient(username=None, password=None) cli.ping() self.assertFalse('Authorization' in m.last_request.headers) cli = InfluxDBClient(username=None) cli.ping() self.assertFalse('Authorization' in m.last_request.headers) cli = InfluxDBClient(password=None) cli.ping() self.assertFalse('Authorization' in m.last_request.headers)
Test auth with not defined username or password.
test_auth_username_password_none
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_auth_token(self): """Test auth with custom authorization header.""" with requests_mock.Mocker() as m: m.register_uri( requests_mock.GET, "http://localhost:8086/ping", status_code=204, headers={'X-Influxdb-Version': '1.2.3'} ) cli = InfluxDBClient(username=None, password=None, headers={"Authorization": "my-token"}) cli.ping() self.assertEqual(m.last_request.headers["Authorization"], "my-token")
Test auth with custom authorization header.
test_auth_token
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def query(self, query, params=None, expected_response_code=200, database=None): """Query data from the FakeClient object.""" if query == 'Fail': raise Exception("Fail") elif query == 'Fail once' and self._host == 'host1': raise Exception("Fail Once") elif query == 'Fail twice' and self._host in 'host1 host2': raise Exception("Fail Twice") else: return "Success"
Query data from the FakeClient object.
query
python
influxdata/influxdb-python
influxdb/tests/client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/client_test.py
MIT
def test_write_points_from_dataframe(self): """Test write points from df in TestDataFrameClient object.""" 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"]) expected = ( b"foo column_one=\"1\",column_two=1i,column_three=1.0 0\n" b"foo column_one=\"2\",column_two=2i,column_three=2.0 " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo') self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None) self.assertEqual(m.last_request.body, expected)
Test write points from df in TestDataFrameClient object.
test_write_points_from_dataframe
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_dataframe_write_points_with_whitespace_measurement(self): """write_points should escape white space in measurements.""" 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"]) expected = ( b"meas\\ with\\ space " b"column_one=\"1\",column_two=1i,column_three=1.0 0\n" b"meas\\ with\\ space " b"column_one=\"2\",column_two=2i,column_three=2.0 " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'meas with space') self.assertEqual(m.last_request.body, expected)
write_points should escape white space in measurements.
test_dataframe_write_points_with_whitespace_measurement
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_dataframe_write_points_with_whitespace_in_column_names(self): """write_points should escape white space in column names.""" 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"]) expected = ( b"foo column\\ one=\"1\",column\\ two=1i,column\\ three=1.0 0\n" b"foo column\\ one=\"2\",column\\ two=2i,column\\ three=2.0 " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo') self.assertEqual(m.last_request.body, expected)
write_points should escape white space in column names.
test_dataframe_write_points_with_whitespace_in_column_names
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_none(self): """Test write points from df in TestDataFrameClient object.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[["1", None, 1.0], ["2", 2.0, 2.0]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) expected = ( b"foo column_one=\"1\",column_three=1.0 0\n" b"foo column_one=\"2\",column_two=2.0,column_three=2.0 " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo') self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None) self.assertEqual(m.last_request.body, expected)
Test write points from df in TestDataFrameClient object.
test_write_points_from_dataframe_with_none
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_line_of_none(self): """Test write points from df in TestDataFrameClient object.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[[None, None, None], ["2", 2.0, 2.0]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) expected = ( b"foo column_one=\"2\",column_two=2.0,column_three=2.0 " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo') self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None) self.assertEqual(m.last_request.body, expected)
Test write points from df in TestDataFrameClient object.
test_write_points_from_dataframe_with_line_of_none
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_all_none(self): """Test write points from df in TestDataFrameClient object.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[[None, None, None], [None, None, None]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) expected = ( b"\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo') self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None) self.assertEqual(m.last_request.body, expected)
Test write points from df in TestDataFrameClient object.
test_write_points_from_dataframe_with_all_none
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_in_batches(self): """Test write points in batch from df in TestDataFrameClient object.""" 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/write", status_code=204) cli = DataFrameClient(database='db') self.assertTrue(cli.write_points(dataframe, "foo", batch_size=1))
Test write points in batch from df in TestDataFrameClient object.
test_write_points_from_dataframe_in_batches
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_tag_columns(self): """Test write points from df w/tag in TestDataFrameClient object.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, 1.0], ['red', 0, "2", 2, 2.0]], index=[now, now + timedelta(hours=1)], columns=["tag_one", "tag_two", "column_one", "column_two", "column_three"]) expected = ( b"foo,tag_one=blue,tag_two=1 " b"column_one=\"1\",column_two=1i,column_three=1.0 " b"0\n" b"foo,tag_one=red,tag_two=0 " b"column_one=\"2\",column_two=2i,column_three=2.0 " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo', tag_columns=['tag_one', 'tag_two']) self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tag_columns=['tag_one', 'tag_two'], tags=None) self.assertEqual(m.last_request.body, expected)
Test write points from df w/tag in TestDataFrameClient object.
test_write_points_from_dataframe_with_tag_columns
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_tag_cols_and_global_tags(self): """Test write points from df w/tag + cols in TestDataFrameClient.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, 1.0], ['red', 0, "2", 2, 2.0]], index=[now, now + timedelta(hours=1)], columns=["tag_one", "tag_two", "column_one", "column_two", "column_three"]) expected = ( b"foo,global_tag=value,tag_one=blue,tag_two=1 " b"column_one=\"1\",column_two=1i,column_three=1.0 " b"0\n" b"foo,global_tag=value,tag_one=red,tag_two=0 " b"column_one=\"2\",column_two=2i,column_three=2.0 " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo', tag_columns=['tag_one', 'tag_two'], tags={'global_tag': 'value'}) self.assertEqual(m.last_request.body, expected)
Test write points from df w/tag + cols in TestDataFrameClient.
test_write_points_from_dataframe_with_tag_cols_and_global_tags
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_tag_cols_and_defaults(self): """Test default write points from df w/tag in TestDataFrameClient.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, 1.0, 'hot'], ['red', 0, "2", 2, 2.0, 'cold']], index=[now, now + timedelta(hours=1)], columns=["tag_one", "tag_two", "column_one", "column_two", "column_three", "tag_three"]) expected_tags_and_fields = ( b"foo,tag_one=blue " b"column_one=\"1\",column_two=1i " b"0\n" b"foo,tag_one=red " b"column_one=\"2\",column_two=2i " b"3600000000000\n" ) expected_tags_no_fields = ( b"foo,tag_one=blue,tag_two=1 " b"column_one=\"1\",column_two=1i,column_three=1.0," b"tag_three=\"hot\" 0\n" b"foo,tag_one=red,tag_two=0 " b"column_one=\"2\",column_two=2i,column_three=2.0," b"tag_three=\"cold\" 3600000000000\n" ) expected_fields_no_tags = ( b"foo,tag_one=blue,tag_three=hot,tag_two=1 " b"column_one=\"1\",column_two=1i,column_three=1.0 " b"0\n" b"foo,tag_one=red,tag_three=cold,tag_two=0 " b"column_one=\"2\",column_two=2i,column_three=2.0 " b"3600000000000\n" ) expected_no_tags_no_fields = ( b"foo " b"tag_one=\"blue\",tag_two=1i,column_one=\"1\"," b"column_two=1i,column_three=1.0,tag_three=\"hot\" " b"0\n" b"foo " b"tag_one=\"red\",tag_two=0i,column_one=\"2\"," b"column_two=2i,column_three=2.0,tag_three=\"cold\" " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo', field_columns=['column_one', 'column_two'], tag_columns=['tag_one']) self.assertEqual(m.last_request.body, expected_tags_and_fields) cli.write_points(dataframe, 'foo', tag_columns=['tag_one', 'tag_two']) self.assertEqual(m.last_request.body, expected_tags_no_fields) cli.write_points(dataframe, 'foo', field_columns=['column_one', 'column_two', 'column_three']) self.assertEqual(m.last_request.body, expected_fields_no_tags) cli.write_points(dataframe, 'foo') self.assertEqual(m.last_request.body, expected_no_tags_no_fields)
Test default write points from df w/tag in TestDataFrameClient.
test_write_points_from_dataframe_with_tag_cols_and_defaults
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_tag_escaped(self): """Test write points from df w/escaped tag in TestDataFrameClient.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame( data=[ ['blue orange', "1", 1, 'hot=cold'], # space, equal ['red,green', "2", 2, r'cold\fire'], # comma, backslash ['some', "2", 2, ''], # skip empty ['some', "2", 2, None], # skip None ['', "2", 2, None], # all tags empty ], index=pd.period_range(now, freq='H', periods=5), columns=["tag_one", "column_one", "column_two", "tag_three"] ) expected_escaped_tags = ( b"foo,tag_one=blue\\ orange,tag_three=hot\\=cold " b"column_one=\"1\",column_two=1i " b"0\n" b"foo,tag_one=red\\,green,tag_three=cold\\\\fire " b"column_one=\"2\",column_two=2i " b"3600000000000\n" b"foo,tag_one=some " b"column_one=\"2\",column_two=2i " b"7200000000000\n" b"foo,tag_one=some " b"column_one=\"2\",column_two=2i " b"10800000000000\n" b"foo " b"column_one=\"2\",column_two=2i " b"14400000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo', field_columns=['column_one', 'column_two'], tag_columns=['tag_one', 'tag_three']) self.assertEqual(m.last_request.body, expected_escaped_tags)
Test write points from df w/escaped tag in TestDataFrameClient.
test_write_points_from_dataframe_with_tag_escaped
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_numeric_column_names(self): """Test write points from df with numeric cols.""" 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)]) expected = ( b'foo,hello=there 0=\"1\",1=1i,2=1.0 0\n' b'foo,hello=there 0=\"2\",1=2i,2=2.0 3600000000000\n' ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, "foo", {"hello": "there"}) self.assertEqual(m.last_request.body, expected)
Test write points from df with numeric cols.
test_write_points_from_dataframe_with_numeric_column_names
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_leading_none_column(self): """write_points detect erroneous leading comma for null first field.""" dataframe = pd.DataFrame( dict( first=[1, None, None, 8, 9], second=[2, None, None, None, 10], third=[3, 4.1, None, None, 11], first_tag=["one", None, None, "eight", None], second_tag=["two", None, None, None, None], third_tag=["three", "four", None, None, None], comment=[ "All columns filled", "First two of three empty", "All empty", "Last two of three empty", "Empty tags with values", ] ), index=pd.date_range( start=pd.to_datetime('2018-01-01'), freq='1D', periods=5, ) ) expected = ( b'foo,first_tag=one,second_tag=two,third_tag=three' b' comment="All columns filled",first=1.0,second=2.0,third=3.0' b' 1514764800000000000\n' b'foo,third_tag=four' b' comment="First two of three empty",third=4.1' b' 1514851200000000000\n' b'foo comment="All empty" 1514937600000000000\n' b'foo,first_tag=eight' b' comment="Last two of three empty",first=8.0' b' 1515024000000000000\n' b'foo' b' comment="Empty tags with values",first=9.0,second=10.0' b',third=11.0' b' 1515110400000000000\n' ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') colnames = [ "first_tag", "second_tag", "third_tag", "comment", "first", "second", "third" ] cli.write_points(dataframe.loc[:, colnames], 'foo', tag_columns=[ "first_tag", "second_tag", "third_tag"]) self.assertEqual(m.last_request.body, expected)
write_points detect erroneous leading comma for null first field.
test_write_points_from_dataframe_with_leading_none_column
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_numeric_precision(self): """Test write points from df with numeric precision.""" now = pd.Timestamp('1970-01-01 00:00+00:00') # df with numeric column names dataframe = pd.DataFrame(data=[["1", 1, 1.1111111111111], ["2", 2, 2.2222222222222]], index=[now, now + timedelta(hours=1)]) if np.lib.NumpyVersion(np.__version__) <= '1.13.3': expected_default_precision = ( b'foo,hello=there 0=\"1\",1=1i,2=1.11111111111 0\n' b'foo,hello=there 0=\"2\",1=2i,2=2.22222222222 3600000000000\n' ) else: expected_default_precision = ( b'foo,hello=there 0=\"1\",1=1i,2=1.1111111111111 0\n' b'foo,hello=there 0=\"2\",1=2i,2=2.2222222222222 3600000000000\n' # noqa E501 line too long ) expected_specified_precision = ( b'foo,hello=there 0=\"1\",1=1i,2=1.1111 0\n' b'foo,hello=there 0=\"2\",1=2i,2=2.2222 3600000000000\n' ) expected_full_precision = ( b'foo,hello=there 0=\"1\",1=1i,2=1.1111111111111 0\n' b'foo,hello=there 0=\"2\",1=2i,2=2.2222222222222 3600000000000\n' ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, "foo", {"hello": "there"}) print(expected_default_precision) print(m.last_request.body) self.assertEqual(m.last_request.body, expected_default_precision) cli = DataFrameClient(database='db') cli.write_points(dataframe, "foo", {"hello": "there"}, numeric_precision=4) self.assertEqual(m.last_request.body, expected_specified_precision) cli = DataFrameClient(database='db') cli.write_points(dataframe, "foo", {"hello": "there"}, numeric_precision='full') self.assertEqual(m.last_request.body, expected_full_precision)
Test write points from df with numeric precision.
test_write_points_from_dataframe_with_numeric_precision
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_period_index(self): """Test write points from df 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"]) expected = ( b"foo column_one=\"1\",column_two=1i,column_three=1.0 0\n" b"foo column_one=\"2\",column_two=2i,column_three=2.0 " b"86400000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, "foo") self.assertEqual(m.last_request.body, expected)
Test write points from df with period index.
test_write_points_from_dataframe_with_period_index
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_time_precision(self): """Test write points from df 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"]) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') measurement = "foo" cli.write_points(dataframe, measurement, time_precision='h') self.assertEqual(m.last_request.qs['precision'], ['h']) self.assertEqual( b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo ' b'column_one="2",column_two=2i,column_three=2.0 1\n', m.last_request.body, ) cli.write_points(dataframe, measurement, time_precision='m') self.assertEqual(m.last_request.qs['precision'], ['m']) self.assertEqual( b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo ' b'column_one="2",column_two=2i,column_three=2.0 60\n', m.last_request.body, ) cli.write_points(dataframe, measurement, time_precision='s') self.assertEqual(m.last_request.qs['precision'], ['s']) self.assertEqual( b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo ' b'column_one="2",column_two=2i,column_three=2.0 3600\n', m.last_request.body, ) cli.write_points(dataframe, measurement, time_precision='ms') self.assertEqual(m.last_request.qs['precision'], ['ms']) self.assertEqual( b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo ' b'column_one="2",column_two=2i,column_three=2.0 3600000\n', m.last_request.body, ) cli.write_points(dataframe, measurement, time_precision='u') self.assertEqual(m.last_request.qs['precision'], ['u']) self.assertEqual( b'foo column_one="1",column_two=1i,column_three=1.0 0\nfoo ' b'column_one="2",column_two=2i,column_three=2.0 3600000000\n', m.last_request.body, ) cli.write_points(dataframe, measurement, time_precision='n') self.assertEqual(m.last_request.qs['precision'], ['n']) self.assertEqual( b'foo column_one="1",column_two=1i,column_three=1.0 0\n' b'foo column_one="2",column_two=2i,column_three=2.0 ' b'3600000000000\n', m.last_request.body, )
Test write points from df with time precision.
test_write_points_from_dataframe_with_time_precision
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_fails_without_time_index(self): """Test failed write points from df 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", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, "foo")
Test failed write points from df without time index.
test_write_points_from_dataframe_fails_without_time_index
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_fails_with_series(self): """Test failed write points from df 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", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, "foo")
Test failed write points from df with series.
test_write_points_from_dataframe_fails_with_series
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_create_database(self): """Test create database for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text='{"results":[{}]}' ) cli.create_database('new_db') self.assertEqual( m.last_request.qs['q'][0], 'create database "new_db"' )
Test create database for TestInfluxDBClient object.
test_create_database
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_create_numeric_named_database(self): """Test create db w/numeric name for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text='{"results":[{}]}' ) cli.create_database('123') self.assertEqual( m.last_request.qs['q'][0], 'create database "123"' )
Test create db w/numeric name for TestInfluxDBClient object.
test_create_numeric_named_database
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_create_database_fails(self): """Test create database fail for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') with _mocked_session(cli, 'post', 401): cli.create_database('new_db')
Test create database fail for TestInfluxDBClient object.
test_create_database_fails
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_drop_database(self): """Test drop database for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text='{"results":[{}]}' ) cli.drop_database('new_db') self.assertEqual( m.last_request.qs['q'][0], 'drop database "new_db"' )
Test drop database for TestInfluxDBClient object.
test_drop_database
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_drop_measurement(self): """Test drop measurement for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text='{"results":[{}]}' ) cli.drop_measurement('new_measurement') self.assertEqual( m.last_request.qs['q'][0], 'drop measurement "new_measurement"' )
Test drop measurement for TestInfluxDBClient object.
test_drop_measurement
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_drop_numeric_named_database(self): """Test drop numeric db for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text='{"results":[{}]}' ) cli.drop_database('123') self.assertEqual( m.last_request.qs['q'][0], 'drop database "123"' )
Test drop numeric db for TestInfluxDBClient object.
test_drop_numeric_named_database
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_get_list_database_fails(self): """Test get list of dbs fail for TestInfluxDBClient object.""" cli = DataFrameClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 401): cli.get_list_database()
Test get list of dbs fail for TestInfluxDBClient object.
test_get_list_database_fails
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_get_list_measurements(self): """Test get list of measurements for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') data = { "results": [{ "series": [ {"name": "measurements", "columns": ["name"], "values": [["cpu"], ["disk"] ]}]} ] } with _mocked_session(cli, 'get', 200, json.dumps(data)): self.assertListEqual( cli.get_list_measurements(), [{'name': 'cpu'}, {'name': 'disk'}] )
Test get list of measurements for TestInfluxDBClient object.
test_get_list_measurements
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_create_retention_policy_default(self): """Test create default ret policy for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) cli.create_retention_policy( 'somename', '1d', 4, default=True, database='db' ) self.assertEqual( m.last_request.qs['q'][0], 'create retention policy "somename" on ' '"db" duration 1d replication 4 shard duration 0s default' )
Test create default ret policy for TestInfluxDBClient object.
test_create_retention_policy_default
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_create_retention_policy(self): """Test create retention policy for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) cli.create_retention_policy( 'somename', '1d', 4, database='db' ) self.assertEqual( m.last_request.qs['q'][0], 'create retention policy "somename" on ' '"db" duration 1d replication 4 shard duration 0s' )
Test create retention policy for TestInfluxDBClient object.
test_create_retention_policy
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_alter_retention_policy(self): """Test alter retention policy for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) # Test alter duration cli.alter_retention_policy('somename', 'db', duration='4d') self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" duration 4d' ) # Test alter replication cli.alter_retention_policy('somename', 'db', replication=4) self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" replication 4' ) # Test alter shard duration cli.alter_retention_policy('somename', 'db', shard_duration='1h') self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" shard duration 1h' ) # Test alter default cli.alter_retention_policy('somename', 'db', default=True) self.assertEqual( m.last_request.qs['q'][0], 'alter retention policy "somename" on "db" default' )
Test alter retention policy for TestInfluxDBClient object.
test_alter_retention_policy
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_alter_retention_policy_invalid(self): """Test invalid alter ret policy for TestInfluxDBClient object.""" cli = DataFrameClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'get', 400): cli.alter_retention_policy('somename', 'db')
Test invalid alter ret policy for TestInfluxDBClient object.
test_alter_retention_policy_invalid
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_drop_retention_policy(self): """Test drop retention policy for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') example_response = '{"results":[{}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/query", text=example_response ) cli.drop_retention_policy('somename', 'db') self.assertEqual( m.last_request.qs['q'][0], 'drop retention policy "somename" on "db"' )
Test drop retention policy for TestInfluxDBClient object.
test_drop_retention_policy
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_drop_retention_policy_fails(self): """Test failed drop ret policy for TestInfluxDBClient object.""" cli = DataFrameClient('host', 8086, 'username', 'password') with _mocked_session(cli, 'delete', 401): cli.drop_retention_policy('default', 'db')
Test failed drop ret policy for TestInfluxDBClient object.
test_drop_retention_policy_fails
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_get_list_retention_policies(self): """Test get retention policies for TestInfluxDBClient object.""" cli = DataFrameClient(database='db') example_response = \ '{"results": [{"series": [{"values": [["fsfdsdf", "24h0m0s", 2]],'\ ' "columns": ["name", "duration", "replicaN"]}]}]}' with requests_mock.Mocker() as m: m.register_uri( requests_mock.GET, "http://localhost:8086/query", text=example_response ) self.assertListEqual( cli.get_list_retention_policies("db"), [{'duration': '24h0m0s', 'name': 'fsfdsdf', 'replicaN': 2}] )
Test get retention policies for TestInfluxDBClient object.
test_get_list_retention_policies
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_query_into_dataframe(self): """Test query into df for TestDataFrameClient object.""" data = { "results": [{ "series": [ {"measurement": "network", "tags": {"direction": ""}, "columns": ["time", "value"], "values": [["2009-11-10T23:00:00Z", 23422]] }, {"measurement": "network", "tags": {"direction": "in"}, "columns": ["time", "value"], "values": [["2009-11-10T23:00:00Z", 23422], ["2009-11-10T23:00:00Z", 23422], ["2009-11-10T23:00:00Z", 23422]] } ] }] } pd1 = pd.DataFrame( [[23422]], columns=['value'], index=pd.to_datetime(["2009-11-10T23:00:00Z"])) if pd1.index.tzinfo is None: pd1.index = pd1.index.tz_localize('UTC') pd2 = pd.DataFrame( [[23422], [23422], [23422]], columns=['value'], index=pd.to_datetime(["2009-11-10T23:00:00Z", "2009-11-10T23:00:00Z", "2009-11-10T23:00:00Z"])) if pd2.index.tzinfo is None: pd2.index = pd2.index.tz_localize('UTC') expected = { ('network', (('direction', ''),)): pd1, ('network', (('direction', 'in'),)): pd2 } cli = DataFrameClient('host', 8086, 'username', 'password', 'db') with _mocked_session(cli, 'GET', 200, data): result = cli.query('select value from network group by direction;') for k in expected: assert_frame_equal(expected[k], result[k])
Test query into df for TestDataFrameClient object.
test_query_into_dataframe
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_multiquery_into_dataframe(self): """Test multiquery into df for TestDataFrameClient object.""" data = { "results": [ { "series": [ { "name": "cpu_load_short", "columns": ["time", "value"], "values": [ ["2015-01-29T21:55:43.702900257Z", 0.55], ["2015-01-29T21:55:43.702900257Z", 23422], ["2015-06-11T20:46:02Z", 0.64] ] } ] }, { "series": [ { "name": "cpu_load_short", "columns": ["time", "count"], "values": [ ["1970-01-01T00:00:00Z", 3] ] } ] } ] } pd1 = pd.DataFrame( [[0.55], [23422.0], [0.64]], columns=['value'], index=pd.to_datetime([ "2015-01-29 21:55:43.702900257+0000", "2015-01-29 21:55:43.702900257+0000", "2015-06-11 20:46:02+0000"])) if pd1.index.tzinfo is None: pd1.index = pd1.index.tz_localize('UTC') pd2 = pd.DataFrame( [[3]], columns=['count'], index=pd.to_datetime(["1970-01-01 00:00:00+00:00"])) if pd2.index.tzinfo is None: pd2.index = pd2.index.tz_localize('UTC') expected = [{'cpu_load_short': pd1}, {'cpu_load_short': pd2}] cli = DataFrameClient('host', 8086, 'username', 'password', 'db') iql = "SELECT value FROM cpu_load_short WHERE region=$region;"\ "SELECT count(value) FROM cpu_load_short WHERE region=$region" bind_params = {'region': 'us-west'} with _mocked_session(cli, 'GET', 200, data): result = cli.query(iql, bind_params=bind_params) for r, e in zip(result, expected): for k in e: assert_frame_equal(e[k], r[k])
Test multiquery into df for TestDataFrameClient object.
test_multiquery_into_dataframe
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_multiquery_into_dataframe_dropna(self): """Test multiquery into df for TestDataFrameClient object.""" data = { "results": [ { "series": [ { "name": "cpu_load_short", "columns": ["time", "value", "value2", "value3"], "values": [ ["2015-01-29T21:55:43.702900257Z", 0.55, 0.254, np.NaN], ["2015-01-29T21:55:43.702900257Z", 23422, 122878, np.NaN], ["2015-06-11T20:46:02Z", 0.64, 0.5434, np.NaN] ] } ] }, { "series": [ { "name": "cpu_load_short", "columns": ["time", "count"], "values": [ ["1970-01-01T00:00:00Z", 3] ] } ] } ] } pd1 = pd.DataFrame( [[0.55, 0.254, np.NaN], [23422.0, 122878, np.NaN], [0.64, 0.5434, np.NaN]], columns=['value', 'value2', 'value3'], index=pd.to_datetime([ "2015-01-29 21:55:43.702900257+0000", "2015-01-29 21:55:43.702900257+0000", "2015-06-11 20:46:02+0000"])) if pd1.index.tzinfo is None: pd1.index = pd1.index.tz_localize('UTC') pd1_dropna = pd.DataFrame( [[0.55, 0.254], [23422.0, 122878], [0.64, 0.5434]], columns=['value', 'value2'], index=pd.to_datetime([ "2015-01-29 21:55:43.702900257+0000", "2015-01-29 21:55:43.702900257+0000", "2015-06-11 20:46:02+0000"])) if pd1_dropna.index.tzinfo is None: pd1_dropna.index = pd1_dropna.index.tz_localize('UTC') pd2 = pd.DataFrame( [[3]], columns=['count'], index=pd.to_datetime(["1970-01-01 00:00:00+00:00"])) if pd2.index.tzinfo is None: pd2.index = pd2.index.tz_localize('UTC') expected_dropna_true = [ {'cpu_load_short': pd1_dropna}, {'cpu_load_short': pd2}] expected_dropna_false = [ {'cpu_load_short': pd1}, {'cpu_load_short': pd2}] cli = DataFrameClient('host', 8086, 'username', 'password', 'db') iql = "SELECT value FROM cpu_load_short WHERE region=$region;" \ "SELECT count(value) FROM cpu_load_short WHERE region=$region" bind_params = {'region': 'us-west'} for dropna in [True, False]: with _mocked_session(cli, 'GET', 200, data): result = cli.query(iql, bind_params=bind_params, dropna=dropna) expected = \ expected_dropna_true if dropna else expected_dropna_false for r, e in zip(result, expected): for k in e: assert_frame_equal(e[k], r[k]) # test default value (dropna = True) with _mocked_session(cli, 'GET', 200, data): result = cli.query(iql, bind_params=bind_params) for r, e in zip(result, expected_dropna_true): for k in e: assert_frame_equal(e[k], r[k])
Test multiquery into df for TestDataFrameClient object.
test_multiquery_into_dataframe_dropna
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_query_with_empty_result(self): """Test query with empty results in TestDataFrameClient object.""" cli = DataFrameClient('host', 8086, 'username', 'password', 'db') with _mocked_session(cli, 'GET', 200, {"results": [{}]}): result = cli.query('select column_one from foo;') self.assertEqual(result, {})
Test query with empty results in TestDataFrameClient object.
test_query_with_empty_result
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_get_list_database(self): """Test get list of databases in TestDataFrameClient object.""" data = {'results': [ {'series': [ {'measurement': 'databases', 'values': [ ['new_db_1'], ['new_db_2']], 'columns': ['name']}]} ]} cli = DataFrameClient('host', 8086, 'username', 'password', 'db') with _mocked_session(cli, 'get', 200, json.dumps(data)): self.assertListEqual( cli.get_list_database(), [{'name': 'new_db_1'}, {'name': 'new_db_2'}] )
Test get list of databases in TestDataFrameClient object.
test_get_list_database
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_datetime_to_epoch(self): """Test convert datetime to epoch in TestDataFrameClient object.""" timestamp = pd.Timestamp('2013-01-01 00:00:00.000+00:00') cli = DataFrameClient('host', 8086, 'username', 'password', 'db') self.assertEqual( cli._datetime_to_epoch(timestamp), 1356998400.0 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='h'), 1356998400.0 / 3600 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='m'), 1356998400.0 / 60 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='s'), 1356998400.0 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='ms'), 1356998400000.0 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='u'), 1356998400000000.0 ) self.assertEqual( cli._datetime_to_epoch(timestamp, time_precision='n'), 1356998400000000000.0 )
Test convert datetime to epoch in TestDataFrameClient object.
test_datetime_to_epoch
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_dsn_constructor(self): """Test data source name deconstructor in TestDataFrameClient.""" client = DataFrameClient.from_dsn('influxdb://localhost:8086') self.assertIsInstance(client, DataFrameClient) self.assertEqual('http://localhost:8086', client._baseurl)
Test data source name deconstructor in TestDataFrameClient.
test_dsn_constructor
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_nan_line(self): """Test write points from dataframe with Nan lines.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[["1", 1, np.inf], ["2", 2, np.nan]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) expected = ( b"foo column_one=\"1\",column_two=1i 0\n" b"foo column_one=\"2\",column_two=2i " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo', protocol='line') self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None, protocol='line') self.assertEqual(m.last_request.body, expected)
Test write points from dataframe with Nan lines.
test_write_points_from_dataframe_with_nan_line
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_nan_json(self): """Test write points from json with NaN lines.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[["1", 1, np.inf], ["2", 2, np.nan]], index=[now, now + timedelta(hours=1)], columns=["column_one", "column_two", "column_three"]) expected = ( b"foo column_one=\"1\",column_two=1i 0\n" b"foo column_one=\"2\",column_two=2i " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo', protocol='json') self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None, protocol='json') self.assertEqual(m.last_request.body, expected)
Test write points from json with NaN lines.
test_write_points_from_dataframe_with_nan_json
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_tags_and_nan_line(self): """Test write points from dataframe with NaN lines and tags.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, np.inf], ['red', 0, "2", 2, np.nan]], index=[now, now + timedelta(hours=1)], columns=["tag_one", "tag_two", "column_one", "column_two", "column_three"]) expected = ( b"foo,tag_one=blue,tag_two=1 " b"column_one=\"1\",column_two=1i " b"0\n" b"foo,tag_one=red,tag_two=0 " b"column_one=\"2\",column_two=2i " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo', protocol='line', tag_columns=['tag_one', 'tag_two']) self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None, protocol='line', tag_columns=['tag_one', 'tag_two']) self.assertEqual(m.last_request.body, expected)
Test write points from dataframe with NaN lines and tags.
test_write_points_from_dataframe_with_tags_and_nan_line
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_write_points_from_dataframe_with_tags_and_nan_json(self): """Test write points from json with NaN lines and tags.""" now = pd.Timestamp('1970-01-01 00:00+00:00') dataframe = pd.DataFrame(data=[['blue', 1, "1", 1, np.inf], ['red', 0, "2", 2, np.nan]], index=[now, now + timedelta(hours=1)], columns=["tag_one", "tag_two", "column_one", "column_two", "column_three"]) expected = ( b"foo,tag_one=blue,tag_two=1 " b"column_one=\"1\",column_two=1i " b"0\n" b"foo,tag_one=red,tag_two=0 " b"column_one=\"2\",column_two=2i " b"3600000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, 'foo', protocol='json', tag_columns=['tag_one', 'tag_two']) self.assertEqual(m.last_request.body, expected) cli.write_points(dataframe, 'foo', tags=None, protocol='json', tag_columns=['tag_one', 'tag_two']) self.assertEqual(m.last_request.body, expected)
Test write points from json with NaN lines and tags.
test_write_points_from_dataframe_with_tags_and_nan_json
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def test_dataframe_nanosecond_precision_one_microsecond(self): """Test nanosecond precision within one microsecond.""" # 1 microsecond = 1000 nanoseconds start = np.datetime64('2019-10-04T06:27:19.850557000') end = np.datetime64('2019-10-04T06:27:19.850558000') # generate timestamps with nanosecond precision timestamps = np.arange( start, end + np.timedelta64(1, 'ns'), np.timedelta64(1, 'ns') ) # generate values values = np.arange(0.0, len(timestamps)) df = pd.DataFrame({'value': values}, index=timestamps) with requests_mock.Mocker() as m: m.register_uri( requests_mock.POST, "http://localhost:8086/write", status_code=204 ) cli = DataFrameClient(database='db') cli.write_points(df, 'foo', time_precision='n') lines = m.last_request.body.decode('utf-8').split('\n') self.assertEqual(len(lines), 1002) for index, line in enumerate(lines): if index == 1001: self.assertEqual(line, '') continue self.assertEqual( line, f"foo value={index}.0 157017043985055{7000 + index:04}" )
Test nanosecond precision within one microsecond.
test_dataframe_nanosecond_precision_one_microsecond
python
influxdata/influxdb-python
influxdb/tests/dataframe_client_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/dataframe_client_test.py
MIT
def setUp(self): """Check that MySeriesHelper has empty datapoints.""" super(TestSeriesHelper, self).setUp() self.assertEqual( TestSeriesHelper.MySeriesHelper._json_body_(), [], 'Resetting helper in teardown did not empty datapoints.')
Check that MySeriesHelper has empty datapoints.
setUp
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def test_auto_commit(self): """Test write_points called after valid number of events.""" class AutoCommitTest(SeriesHelper): """Define a SeriesHelper instance to test autocommit.""" class Meta: """Define metadata for AutoCommitTest.""" series_name = 'events.stats.{server_name}' fields = ['some_stat'] tags = ['server_name', 'other_tag'] bulk_size = 5 client = InfluxDBClient() autocommit = True fake_write_points = mock.MagicMock() AutoCommitTest(server_name='us.east-1', some_stat=159, other_tag='gg') AutoCommitTest._client.write_points = fake_write_points AutoCommitTest(server_name='us.east-1', some_stat=158, other_tag='gg') AutoCommitTest(server_name='us.east-1', some_stat=157, other_tag='gg') AutoCommitTest(server_name='us.east-1', some_stat=156, other_tag='gg') self.assertFalse(fake_write_points.called) AutoCommitTest(server_name='us.east-1', some_stat=3443, other_tag='gg') self.assertTrue(fake_write_points.called)
Test write_points called after valid number of events.
test_auto_commit
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def testSingleSeriesName(self, current_timestamp): """Test JSON conversion when there is only one series name.""" current_timestamp.return_value = current_date = datetime.today() TestSeriesHelper.MySeriesHelper( server_name='us.east-1', other_tag='ello', some_stat=159) TestSeriesHelper.MySeriesHelper( server_name='us.east-1', other_tag='ello', some_stat=158) TestSeriesHelper.MySeriesHelper( server_name='us.east-1', other_tag='ello', some_stat=157) TestSeriesHelper.MySeriesHelper( server_name='us.east-1', other_tag='ello', some_stat=156) expectation = [ { "measurement": "events.stats.us.east-1", "tags": { "other_tag": "ello", "server_name": "us.east-1" }, "fields": { "some_stat": 159 }, "time": current_date, }, { "measurement": "events.stats.us.east-1", "tags": { "other_tag": "ello", "server_name": "us.east-1" }, "fields": { "some_stat": 158 }, "time": current_date, }, { "measurement": "events.stats.us.east-1", "tags": { "other_tag": "ello", "server_name": "us.east-1" }, "fields": { "some_stat": 157 }, "time": current_date, }, { "measurement": "events.stats.us.east-1", "tags": { "other_tag": "ello", "server_name": "us.east-1" }, "fields": { "some_stat": 156 }, "time": current_date, } ] 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))
Test JSON conversion when there is only one series name.
testSingleSeriesName
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def testSeveralSeriesNames(self, current_timestamp): """Test JSON conversion when there are multiple series names.""" current_timestamp.return_value = current_date = datetime.today() TestSeriesHelper.MySeriesHelper( server_name='us.east-1', some_stat=159, other_tag='ello') TestSeriesHelper.MySeriesHelper( server_name='fr.paris-10', some_stat=158, other_tag='ello') TestSeriesHelper.MySeriesHelper( server_name='lu.lux', some_stat=157, other_tag='ello') TestSeriesHelper.MySeriesHelper( server_name='uk.london', some_stat=156, other_tag='ello') expectation = [ { 'fields': { 'some_stat': 157 }, 'measurement': 'events.stats.lu.lux', 'tags': { 'other_tag': 'ello', 'server_name': 'lu.lux' }, "time": current_date, }, { 'fields': { 'some_stat': 156 }, 'measurement': 'events.stats.uk.london', 'tags': { 'other_tag': 'ello', 'server_name': 'uk.london' }, "time": current_date, }, { 'fields': { 'some_stat': 158 }, 'measurement': 'events.stats.fr.paris-10', 'tags': { 'other_tag': 'ello', 'server_name': 'fr.paris-10' }, "time": current_date, }, { 'fields': { 'some_stat': 159 }, 'measurement': 'events.stats.us.east-1', 'tags': { 'other_tag': 'ello', 'server_name': 'us.east-1' }, "time": current_date, } ] 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))
Test JSON conversion when there are multiple series names.
testSeveralSeriesNames
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def testSeriesWithoutTimeField(self, current_timestamp): """Test that time is optional on a series without a time field.""" current_date = datetime.today() yesterday = current_date - timedelta(days=1) current_timestamp.return_value = yesterday TestSeriesHelper.MySeriesHelper( server_name='us.east-1', other_tag='ello', some_stat=159, time=current_date ) TestSeriesHelper.MySeriesHelper( server_name='us.east-1', other_tag='ello', some_stat=158, ) point1, point2 = TestSeriesHelper.MySeriesHelper._json_body_() self.assertTrue('time' in point1 and 'time' in point2) self.assertEqual(point1['time'], current_date) self.assertEqual(point2['time'], yesterday)
Test that time is optional on a series without a time field.
testSeriesWithoutTimeField
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def testSeriesWithoutAllTags(self): """Test that creating a data point without a tag throws an error.""" class MyTimeFieldSeriesHelper(SeriesHelper): class Meta: client = TestSeriesHelper.client series_name = 'events.stats.{server_name}' fields = ['some_stat', 'time'] tags = ['server_name', 'other_tag'] bulk_size = 5 autocommit = True self.assertRaises(NameError, MyTimeFieldSeriesHelper, **{"server_name": 'us.east-1', "some_stat": 158})
Test that creating a data point without a tag throws an error.
testSeriesWithoutAllTags
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def testSeriesWithTimeField(self, current_timestamp): """Test that time is optional on a series with a time field.""" current_date = datetime.today() yesterday = current_date - timedelta(days=1) current_timestamp.return_value = yesterday class MyTimeFieldSeriesHelper(SeriesHelper): class Meta: client = TestSeriesHelper.client series_name = 'events.stats.{server_name}' fields = ['some_stat', 'time'] tags = ['server_name', 'other_tag'] bulk_size = 5 autocommit = True MyTimeFieldSeriesHelper( server_name='us.east-1', other_tag='ello', some_stat=159, time=current_date ) MyTimeFieldSeriesHelper( server_name='us.east-1', other_tag='ello', some_stat=158, ) point1, point2 = MyTimeFieldSeriesHelper._json_body_() self.assertTrue('time' in point1 and 'time' in point2) self.assertEqual(point1['time'], current_date) self.assertEqual(point2['time'], yesterday)
Test that time is optional on a series with a time field.
testSeriesWithTimeField
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def testWarnBulkSizeZero(self): """Test warning for an invalid bulk size.""" class WarnBulkSizeZero(SeriesHelper): class Meta: client = TestSeriesHelper.client series_name = 'events.stats.{server_name}' fields = ['time', 'server_name'] tags = [] bulk_size = 0 autocommit = True with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") try: WarnBulkSizeZero(time=159, server_name='us.east-1') except ConnectionError: # Server defined in the client is invalid, we're testing # the warning only. pass self.assertEqual(len(w), 1, '{0} call should have generated one warning.' .format(WarnBulkSizeZero)) self.assertIn('forced to 1', str(w[-1].message), 'Warning message did not contain "forced to 1".')
Test warning for an invalid bulk size.
testWarnBulkSizeZero
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def testSeriesWithRetentionPolicy(self): """Test that the data is saved with the specified retention policy.""" my_policy = 'my_policy' class RetentionPolicySeriesHelper(SeriesHelper): class Meta: client = InfluxDBClient() series_name = 'events.stats.{server_name}' fields = ['some_stat', 'time'] tags = ['server_name', 'other_tag'] bulk_size = 2 autocommit = True retention_policy = my_policy fake_write_points = mock.MagicMock() RetentionPolicySeriesHelper( server_name='us.east-1', some_stat=159, other_tag='gg') RetentionPolicySeriesHelper._client.write_points = fake_write_points RetentionPolicySeriesHelper( server_name='us.east-1', some_stat=158, other_tag='aa') kall = fake_write_points.call_args args, kwargs = kall self.assertTrue('retention_policy' in kwargs) self.assertEqual(kwargs['retention_policy'], my_policy)
Test that the data is saved with the specified retention policy.
testSeriesWithRetentionPolicy
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def testSeriesWithoutRetentionPolicy(self): """Test that the data is saved without any retention policy.""" class NoRetentionPolicySeriesHelper(SeriesHelper): class Meta: client = InfluxDBClient() series_name = 'events.stats.{server_name}' fields = ['some_stat', 'time'] tags = ['server_name', 'other_tag'] bulk_size = 2 autocommit = True fake_write_points = mock.MagicMock() NoRetentionPolicySeriesHelper( server_name='us.east-1', some_stat=159, other_tag='gg') NoRetentionPolicySeriesHelper._client.write_points = fake_write_points NoRetentionPolicySeriesHelper( server_name='us.east-1', some_stat=158, other_tag='aa') kall = fake_write_points.call_args args, kwargs = kall self.assertTrue('retention_policy' in kwargs) self.assertEqual(kwargs['retention_policy'], None)
Test that the data is saved without any retention policy.
testSeriesWithoutRetentionPolicy
python
influxdata/influxdb-python
influxdb/tests/helper_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/helper_test.py
MIT
def get_free_ports(num_ports, ip='127.0.0.1'): """Determine free ports on provided interface. Get `num_ports` free/available ports on the interface linked to the `ip` :param int num_ports: The number of free ports to get :param str ip: The ip on which the ports have to be taken :return: a set of ports number """ sock_ports = [] ports = set() try: for _ in range(num_ports): sock = socket.socket() cur = [sock, -1] # append the socket directly, # so that it'll be also closed (no leaked resource) # in the finally here after. sock_ports.append(cur) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((ip, 0)) cur[1] = sock.getsockname()[1] finally: for sock, port in sock_ports: sock.close() ports.add(port) assert num_ports == len(ports) return ports
Determine free ports on provided interface. Get `num_ports` free/available ports on the interface linked to the `ip` :param int num_ports: The number of free ports to get :param str ip: The ip on which the ports have to be taken :return: a set of ports number
get_free_ports
python
influxdata/influxdb-python
influxdb/tests/misc.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/misc.py
MIT
def is_port_open(port, ip='127.0.0.1'): """Check if given TCP port is open for connection.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: result = sock.connect_ex((ip, port)) if not result: sock.shutdown(socket.SHUT_RDWR) return result == 0 finally: sock.close()
Check if given TCP port is open for connection.
is_port_open
python
influxdata/influxdb-python
influxdb/tests/misc.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/misc.py
MIT
def setUp(self): """Set up an instance of TestResultSet.""" self.query_response = { "results": [ {"series": [{"name": "cpu_load_short", "columns": ["time", "value", "host", "region"], "values": [ ["2015-01-29T21:51:28.968422294Z", 0.64, "server01", "us-west"], ["2015-01-29T21:51:28.968422294Z", 0.65, "server02", "us-west"], ]}, {"name": "other_series", "columns": ["time", "value", "host", "region"], "values": [ ["2015-01-29T21:51:28.968422294Z", 0.66, "server01", "us-west"], ]}]} ] } self.rs = ResultSet(self.query_response['results'][0])
Set up an instance of TestResultSet.
setUp
python
influxdata/influxdb-python
influxdb/tests/resultset_test.py
https://github.com/influxdata/influxdb-python/blob/master/influxdb/tests/resultset_test.py
MIT