Skip to content

Commit b65afdf

Browse files
authored
Enable setup of logging query results during library import and using a dedicated keyword 'Set Logging Query Results' (#218)
1 parent 261c32a commit b65afdf

File tree

4 files changed

+94
-5
lines changed

4 files changed

+94
-5
lines changed

src/DatabaseLibrary/__init__.py

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,15 +94,15 @@ class DatabaseLibrary(ConnectionManager, Query, Assertion):
9494
|
9595
9696
= Inline assertions =
97-
Keywords that accept arguments ``assertion_operator`` <`AssertionOperator`> and ``expected_value``
97+
Keywords, that accept arguments ``assertion_operator`` <`AssertionOperator`> and ``expected_value``,
9898
perform a check according to the specified condition - using the [https://github.com/MarketSquare/AssertionEngine|Assertion Engine].
9999
100100
Examples:
101101
| Check Row Count | SELECT id FROM person | *==* | 2 |
102102
| Check Query Result | SELECT first_name FROM person | *contains* | Allan |
103103
104104
= Retry mechanism =
105-
Assertion keywords that accept arguments ``retry_timeout`` and ``retry_pause`` support waiting for assertion to pass.
105+
Assertion keywords, that accept arguments ``retry_timeout`` and ``retry_pause``, support waiting for assertion to pass.
106106
107107
Setting the ``retry_timeout`` argument enables the mechanism -
108108
in this case the SQL request and the assertion are executed in a loop,
@@ -118,6 +118,27 @@ class DatabaseLibrary(ConnectionManager, Query, Assertion):
118118
| Check Row Count | SELECT id FROM person | *==* | 2 | retry_timeout=10 seconds |
119119
| Check Query Result | SELECT first_name FROM person | *contains* | Allan | retry_timeout=5s | retry_timeout=1s |
120120
121+
= Logging query results =
122+
Keywords, that fetch results of a SQL query, print the result rows as a table in RF log.
123+
- A log head limit of *50 rows* is applied, other table rows are truncated in the log message.
124+
- The limit and the logging in general can be adjusted any time in your tests using the Keyword `Set Logging Query Results`.
125+
126+
You can also setup the limit or disable the logging during the library import.
127+
Examples:
128+
129+
| # Default behavior - logging of query results is enabled, log head is 50 rows.
130+
| *** Settings ***
131+
| Library DatabaseLibrary
132+
|
133+
| # Logging of query results is disabled, log head is 50 rows (default).
134+
| Library DatabaseLibrary log_query_results=False
135+
|
136+
| # Logging of query results is enabled (default), log head is 10 rows.
137+
| Library DatabaseLibrary log_query_results_head=10
138+
|
139+
| # Logging of query results is enabled (default), log head limit is disabled (log all rows).
140+
| Library DatabaseLibrary log_query_results_head=0
141+
121142
= Database modules compatibility =
122143
The library is basically compatible with any [https://peps.python.org/pep-0249|Python Database API Specification 2.0] module.
123144
@@ -128,3 +149,15 @@ class DatabaseLibrary(ConnectionManager, Query, Assertion):
128149
"""
129150

130151
ROBOT_LIBRARY_SCOPE = "GLOBAL"
152+
153+
def __init__(self, log_query_results=True, log_query_results_head=50):
154+
"""
155+
The library can be imported without any arguments:
156+
| *** Settings ***
157+
| Library DatabaseLibrary
158+
Use optional library import parameters to disable `Logging query results` or setup the log head.
159+
"""
160+
ConnectionManager.__init__(self)
161+
if log_query_results_head < 0:
162+
raise ValueError(f"Wrong log head value provided: {log_query_results_head}. The value can't be negative!")
163+
Query.__init__(self, log_query_results=log_query_results, log_query_results_head=log_query_results_head)

src/DatabaseLibrary/query.py

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ class Query:
2525
Query handles all the querying done by the Database Library.
2626
"""
2727

28+
def __init__(self, log_query_results, log_query_results_head):
29+
self.LOG_QUERY_RESULTS = log_query_results
30+
self.LOG_QUERY_RESULTS_HEAD = log_query_results_head
31+
2832
def query(
2933
self,
3034
selectStatement: str,
@@ -86,7 +90,7 @@ def query(
8690
self._execute_sql(cur, selectStatement, parameters=parameters)
8791
all_rows = cur.fetchall()
8892
col_names = [c[0] for c in cur.description]
89-
self._log_query_result(col_names, all_rows)
93+
self._log_query_results(col_names, all_rows)
9094
if returnAsDict:
9195
return [dict(zip(col_names, row)) for row in all_rows]
9296
return all_rows
@@ -132,7 +136,7 @@ def row_count(
132136
else:
133137
current_row_count = cur.rowcount
134138
logger.info(f"Retrieved {current_row_count} rows")
135-
self._log_query_result(col_names, data)
139+
self._log_query_results(col_names, data)
136140
return current_row_count
137141
finally:
138142
if cur and not sansTran:
@@ -552,6 +556,24 @@ def call_stored_procedure(
552556
if cur and not sansTran:
553557
db_connection.client.rollback()
554558

559+
def set_logging_query_results(self, enabled: Optional[bool] = None, log_head: Optional[int] = None):
560+
"""
561+
Allows to enable/disable logging of query results and to adjust the log head value.
562+
- Overrides the values, which were set during the library import.
563+
- See `Logging query results` for details.
564+
565+
Examples:
566+
| Set Logging Query Results | enabled=False |
567+
| Set Logging Query Results | enabled=True | log_head=0 |
568+
| Set Logging Query Results | log_head=10 |
569+
"""
570+
if enabled is not None:
571+
self.LOG_QUERY_RESULTS = enabled
572+
if log_head is not None:
573+
if log_head < 0:
574+
raise ValueError(f"Wrong log head value provided: {log_head}. The value can't be negative!")
575+
self.LOG_QUERY_RESULTS_HEAD = log_head
576+
555577
def _execute_sql(
556578
self,
557579
cur,
@@ -577,12 +599,17 @@ def _execute_sql(
577599
logger.debug(f"Executing sql '{sql_statement}' with parameters: {parameters}")
578600
return cur.execute(sql_statement, parameters)
579601

580-
def _log_query_result(self, col_names, result_rows, log_head=50):
602+
def _log_query_results(self, col_names, result_rows, log_head: Optional[int] = None):
581603
"""
582604
Logs the `result_rows` of a query in RF log as a HTML table.
583605
The `col_names` are needed for the table header.
584606
Max. `log_head` rows are logged (`0` disables the limit).
585607
"""
608+
if not self.LOG_QUERY_RESULTS:
609+
return
610+
611+
if log_head is None:
612+
log_head = self.LOG_QUERY_RESULTS_HEAD
586613
cell_border_and_align = "border: 1px solid rgb(160 160 160);padding: 8px 10px;text-align: center;"
587614
table_border = "2px solid rgb(140 140 140)"
588615
row_index_color = "#d6ecd4"
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
*** Settings ***
2+
Documentation Tests for parameters used when importing the library
3+
4+
*** Test Cases ***
5+
Import Without Parameters Is Valid
6+
Import Library DatabaseLibrary
7+
8+
Log Query Results Params Cause No Crash
9+
Import Library DatabaseLibrary log_query_results=False log_query_results_head=0
10+
11+
Log Query Results Head - Negative Value Not Allowed
12+
Run Keyword And Expect Error
13+
... STARTS: Initializing library 'DatabaseLibrary' with arguments [ log_query_results_head=-1 ] failed: ValueError: Wrong log head value provided: -1. The value can't be negative!
14+
... Import Library DatabaseLibrary log_query_results_head=-1
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
*** Settings ***
2+
Documentation Tests for keywords controlling the logging query results
3+
4+
Resource ../../resources/common.resource
5+
6+
Suite Setup Connect To DB
7+
Suite Teardown Disconnect From Database
8+
Test Setup Create Person Table And Insert Data
9+
Test Teardown Drop Tables Person And Foobar
10+
11+
*** Test Cases ***
12+
Calling The Keyword Causes No Crash
13+
Set Logging Query Results enabled=False
14+
Set Logging Query Results enabled=True log_head=0
15+
Set Logging Query Results log_head=30

0 commit comments

Comments
 (0)