def test_query(self): """Test _query().""" test_query = 'SELECT count(*) from now()' expected = [{'count': 1}] dbs = DatabaseStatus() result = dbs.query(test_query) self.assertEqual(result, expected)
def test_query_cache(self): """Test that query() returns a cached response when available.""" dbs = DatabaseStatus() dbs._last_result = 1 dbs._last_query = datetime.now() result = dbs.query('SELECT count(*) from now()') self.assertEqual(result, 1)
def test_query_exception(self): """Test _query() when an exception is thrown.""" logging.disable(0) with mock.patch('django.db.backends.utils.CursorWrapper') as mock_cursor: mock_cursor = mock_cursor.return_value.__enter__.return_value mock_cursor.execute.side_effect = OperationalError('test exception') test_query = 'SELECT count(*) from now()' dbs = DatabaseStatus() with self.assertLogs(level=logging.WARNING): dbs.query(test_query)
def test_query_exception(self, patched_sleep): # pylint: disable=W0613 """Test _query() when an exception is thrown.""" logging.disable(logging.NOTSET) with mock.patch("django.db.backends.utils.CursorWrapper") as mock_cursor: mock_cursor = mock_cursor.return_value.__enter__.return_value mock_cursor.execute.side_effect = OperationalError("test exception") test_query = "SELECT count(*) from now()" dbs = DatabaseStatus() with self.assertLogs(logger="koku.metrics", level=logging.WARNING): result = dbs.query(test_query, "test_query") self.assertFalse(result)
def test_query_return_empty(self, mock_connection): """Test that empty query returns [] and logs info.""" # Mocked up objects: # connection.cursor().fetchall() # connection.cursor().description mock_ctx = Mock(return_value=Mock(description=[("schema",), ("size",)], fetchall=[("chicken", 2)])) mock_connection.cursor = Mock(return_value=Mock(__enter__=mock_ctx, __exit__=mock_ctx)) logging.disable(logging.NOTSET) dbs = DatabaseStatus() with self.assertLogs(logger="koku.metrics", level=logging.INFO): result = dbs.schema_size() self.assertFalse(result)
def test_schema_size_valid(self, mock_connection): """Test that schema_size() parses rows correctly.""" fake_rows = [(FAKE.word(), FAKE.pyint()) for _ in range(0, random.randint(2, 20))] # Mocked up objects: # connection.cursor().fetchall() # connection.cursor().description mock_ctx = Mock(return_value=Mock(description=[("schema",), ("size",)], fetchall=Mock(return_value=fake_rows))) mock_connection.cursor = Mock(return_value=Mock(__enter__=mock_ctx, __exit__=mock_ctx)) expected = [dict(zip(["schema", "size"], row)) for row in fake_rows if len(row) == 2] dbs = DatabaseStatus() result = dbs.schema_size() self.assertEqual(result, expected)
def test_query_exception(self, mock_connect): """Test _query() when an exception is thrown.""" logging.disable(0) # Because of psycopg2's chained method design, we need to chain mocks... # result of psycopg2.connect() mock_con = mock_connect.return_value # result of con.cursor() mock_cur = mock_con.cursor.return_value # result of cur.execute() mock_cur.execute.side_effect = psycopg2.OperationalError( 'test exception') test_query = 'SELECT count(*) from now()' with self.assertLogs(level=logging.WARNING): dbs = DatabaseStatus() dbs.query(test_query)
def test_db_is_not_connected(self, mock_connection): """Test that db is not connected, log at ERROR level and counter increments.""" mock_connection.cursor.side_effect = OperationalError("test exception") logging.disable(logging.NOTSET) before = REGISTRY.get_sample_value("db_connection_errors_total") with self.assertLogs(logger="koku.metrics", level=logging.ERROR): DatabaseStatus().connection_check() after = REGISTRY.get_sample_value("db_connection_errors_total") self.assertEqual(1, after - before)
def test_collect(self, _, mock_gauge): """Test collect().""" dbs = DatabaseStatus() dbs.collect() self.assertTrue(mock_gauge.called)
def test_schema_size(self, mock_status): """Test schema_size().""" dbs = DatabaseStatus() result = dbs.schema_size() assert mock_status.called self.assertTrue(result)
def test_db_is_connected(self): """Test that db is connected and logs at DEBUG level.""" logging.disable(logging.NOTSET) with self.assertLogs(logger="koku.metrics", level=logging.DEBUG): DatabaseStatus().connection_check()
def test_collect_bad_schema_size(self, _, mock_gauge): """Test collect with None data types.""" dbs = DatabaseStatus() dbs.collect() self.assertFalse(mock_gauge.called)
def test_constructor(self): """Test DatabaseStatus constructor.""" dbs = DatabaseStatus() self.assertIsNotNone(dbs.uri) self.assertRegex(dbs.uri, r'\w+://\w+:[a-zA-Z0-9\']*@\w+:\d+/\w+')