From 18bbf344a22e63bcf7c4c185bce9da9bd959c1b3 Mon Sep 17 00:00:00 2001 From: Luke Dziewanowski Date: Mon, 18 Oct 2021 22:25:54 +0200 Subject: [PATCH 1/3] Fix some tests --- test/DB2SQL_DB_Conf.txt | 6 ------ test/DB2SQL_DB_Tests.robot | 14 +++++++++++++- test/DB2_Variables.yaml | 5 +++++ test/DB_Variables.yaml | 13 +++++++++++++ test/MySQL_DB_Tests.robot | 22 ++++++++++++++-------- test/MySQL_Variables.yaml | 5 +++++ test/PostgreSQL_DB_Tests.robot | 22 ++++++++++++++-------- test/PostgreSQL_Variables.yaml | 5 +++++ test/SQLite3_DB_Tests.robot | 6 ++++-- test/run_tests.sh | 3 +++ 10 files changed, 76 insertions(+), 25 deletions(-) delete mode 100644 test/DB2SQL_DB_Conf.txt create mode 100644 test/DB2_Variables.yaml create mode 100644 test/DB_Variables.yaml create mode 100644 test/MySQL_Variables.yaml create mode 100644 test/PostgreSQL_Variables.yaml create mode 100755 test/run_tests.sh diff --git a/test/DB2SQL_DB_Conf.txt b/test/DB2SQL_DB_Conf.txt deleted file mode 100644 index 3a22bea..0000000 --- a/test/DB2SQL_DB_Conf.txt +++ /dev/null @@ -1,6 +0,0 @@ -*** Variables *** -${DBName} dbname -${DBUser} user -${DBPass} password -${DBHost} host -${DBPort} port diff --git a/test/DB2SQL_DB_Tests.robot b/test/DB2SQL_DB_Tests.robot index 46e50f5..06dc1b5 100644 --- a/test/DB2SQL_DB_Tests.robot +++ b/test/DB2SQL_DB_Tests.robot @@ -1,9 +1,21 @@ *** Settings *** -Suite Setup Connect To Database ibm_db_dbi ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} +Suite Setup Connect To Database ibm_db_dbi ${DB2_DBName} ${DB2_DBUser} ${DB2_DBPass} ${DB2_DBHost} ${DB2_DBPort} Suite Teardown Disconnect From Database Resource DB2SQL_DB_Conf.txt Library DatabaseLibrary +*** Variables *** +${DBName} dbname +${DBUser} user +${DBPass} password +${DBHost} host +${DBPort} port +${DB2_DBName} ${DBName} +${DB2_DBUser} ${DBUser} +${DB2_DBPass} ${DBPass} +${DB2_DBHost} ${DBHost} +${DB2_DBPort} ${DBPort} + *** Test Cases *** Create person table ${output} = Execute SQL String CREATE TABLE person (id decimal(10,0),first_name varchar(30),last_name varchar(30)); diff --git a/test/DB2_Variables.yaml b/test/DB2_Variables.yaml new file mode 100644 index 0000000..f3f82c1 --- /dev/null +++ b/test/DB2_Variables.yaml @@ -0,0 +1,5 @@ +DB2_DBHost: localhost +DB2_DBName: mydb +DB2_DBPass: mypass +DB2_DBPort: 64481 +DB2_DBUser: myuser diff --git a/test/DB_Variables.yaml b/test/DB_Variables.yaml new file mode 100644 index 0000000..b19a352 --- /dev/null +++ b/test/DB_Variables.yaml @@ -0,0 +1,13 @@ +MYSQL_DBHost: localhost +MYSQL_DBName: mydb +MYSQL_DBPass: mypass +MYSQL_DBPort: 64479 +MYSQL_DBUser: myuser + +POSTGRESQL_DBHost: localhost +POSTGRESQL_DBName: mydb +POSTGRESQL_DBPass: mypass +POSTGRESQL_DBPort: 64480 +POSTGRESQL_DBUser: myuser + +SQLITE3_DBName: mydb diff --git a/test/MySQL_DB_Tests.robot b/test/MySQL_DB_Tests.robot index d242df9..bca888f 100644 --- a/test/MySQL_DB_Tests.robot +++ b/test/MySQL_DB_Tests.robot @@ -1,8 +1,9 @@ *** Settings *** -Suite Setup Connect To Database pymysql ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} +Suite Setup Connect To Database pymysql ${MYSQL_DBName} ${MYSQL_DBUser} ${MYSQL_DBPass} ${MYSQL_DBHost} ${MYSQL_DBPort} Suite Teardown Disconnect From Database Library DatabaseLibrary Library OperatingSystem +Force Tags standard *** Variables *** ${DBHost} 127.0.0.1 @@ -10,6 +11,11 @@ ${DBName} my_db_test ${DBPass} "" ${DBPort} 3306 ${DBUser} root +${MYSQL_DBName} ${DBName} +${MYSQL_DBUser} ${DBUser} +${MYSQL_DBPass} ${DBPass} +${MYSQL_DBHost} ${DBHost} +${MYSQL_DBPort} ${DBPort} *** Test Cases *** Create person table @@ -77,11 +83,11 @@ Verify person Description @{queryResults} = Description SELECT * FROM person LIMIT 1; Log Many @{queryResults} ${output} = Set Variable ${queryResults[0]} - Should Be Equal As Strings ${output} (u'id', 3, None, 11, 11, 0, True) + Should Be Equal As Strings ${output} ('id', 3, None, 11, 11, 0, True) ${output} = Set Variable ${queryResults[1]} - Should Be Equal As Strings ${output} (u'first_name', 253, None, 20, 20, 0, True) + Should Be Equal As Strings ${output} ('first_name', 253, None, 80, 80, 0, True) ${output} = Set Variable ${queryResults[2]} - Should Be Equal As Strings ${output} (u'last_name', 253, None, 20, 20, 0, True) + Should Be Equal As Strings ${output} ('last_name', 253, None, 80, 80, 0, True) ${NumColumns} = Get Length ${queryResults} Should Be Equal As Integers ${NumColumns} 3 @@ -91,9 +97,9 @@ Verify foobar Description @{queryResults} = Description SELECT * FROM foobar LIMIT 1; Log Many @{queryResults} ${output} = Set Variable ${queryResults[0]} - Should Be Equal As Strings ${output} (u'id', 3, None, 11, 11, 0, False) + Should Be Equal As Strings ${output} ('id', 3, None, 11, 11, 0, False) ${output} = Set Variable ${queryResults[1]} - Should Be Equal As Strings ${output} (u'firstname', 253, None, 20, 20, 0, True) + Should Be Equal As Strings ${output} ('firstname', 253, None, 80, 80, 0, True) ${NumColumns} = Get Length ${queryResults} Should Be Equal As Integers ${NumColumns} 2 @@ -113,8 +119,8 @@ Verify Query - Get results as a list of dictionaries [Tags] db smoke ${output} = Query SELECT * FROM person; \ True Log ${output} - Should Be Equal As Strings &{output[0]}[first_name] Franz Allan - Should Be Equal As Strings &{output[1]}[first_name] Jerry + Should Be Equal As Strings ${output[0]['first_name']} Franz Allan + Should Be Equal As Strings ${output[1]['first_name']} Jerry Verify Execute SQL String - Row Count person table [Tags] db smoke diff --git a/test/MySQL_Variables.yaml b/test/MySQL_Variables.yaml new file mode 100644 index 0000000..76135ca --- /dev/null +++ b/test/MySQL_Variables.yaml @@ -0,0 +1,5 @@ +MYSQL_DBHost: localhost +MYSQL_DBName: mydb +MYSQL_DBPass: mypass +MYSQL_DBPort: 64479 +MYSQL_DBUser: myuser diff --git a/test/PostgreSQL_DB_Tests.robot b/test/PostgreSQL_DB_Tests.robot index fb458db..89c293e 100644 --- a/test/PostgreSQL_DB_Tests.robot +++ b/test/PostgreSQL_DB_Tests.robot @@ -1,9 +1,10 @@ *** Settings *** -Suite Setup Connect To Database psycopg2 ${DBName} ${DBUser} ${DBPass} ${DBHost} ${DBPort} +Suite Setup Connect To Database psycopg2 ${POSTGRESQL_DBName} ${POSTGRESQL_DBUser} ${POSTGRESQL_DBPass} ${POSTGRESQL_DBHost} ${POSTGRESQL_DBPort} Suite Teardown Disconnect From Database Library DatabaseLibrary Library OperatingSystem Library Collections +Force Tags standard *** Variables *** ${DBHost} localhost @@ -11,6 +12,11 @@ ${DBName} travis_ci_test ${DBPass} "" ${DBPort} 5432 ${DBUser} postgres +${POSTGRESQL_DBName} ${DBName} +${POSTGRESQL_DBUser} ${DBUser} +${POSTGRESQL_DBPass} ${DBPass} +${POSTGRESQL_DBHost} ${DBHost} +${POSTGRESQL_DBPort} ${DBPort} *** Test Cases *** Create person table @@ -66,11 +72,11 @@ Verify person Description @{queryResults} = Description SELECT * FROM person LIMIT 1; Log Many @{queryResults} ${output} = Set Variable ${queryResults[0]} - Should Be Equal As Strings ${output} Column(name='id', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None) + Should Be Equal As Strings ${output} Column(name='id', type_code=23) ${output} = Set Variable ${queryResults[1]} - Should Be Equal As Strings ${output} Column(name='first_name', type_code=1043, display_size=None, internal_size=-1, precision=None, scale=None, null_ok=None) + Should Be Equal As Strings ${output} Column(name='first_name', type_code=1043) ${output} = Set Variable ${queryResults[2]} - Should Be Equal As Strings ${output} Column(name='last_name', type_code=1043, display_size=None, internal_size=-1, precision=None, scale=None, null_ok=None) + Should Be Equal As Strings ${output} Column(name='last_name', type_code=1043) ${NumColumns} = Get Length ${queryResults} Should Be Equal As Integers ${NumColumns} 3 @@ -80,9 +86,9 @@ Verify foobar Description @{queryResults} = Description SELECT * FROM foobar LIMIT 1; Log Many @{queryResults} ${output} = Set Variable ${queryResults[0]} - Should Be Equal As Strings ${output} Column(name='id', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None) + Should Be Equal As Strings ${output} Column(name='id', type_code=23) ${output} = Set Variable ${queryResults[1]} - Should Be Equal As Strings ${output} Column(name='firstname', type_code=1043, display_size=None, internal_size=-1, precision=None, scale=None, null_ok=None) + Should Be Equal As Strings ${output} Column(name='firstname', type_code=1043) ${NumColumns} = Get Length ${queryResults} Should Be Equal As Integers ${NumColumns} 2 @@ -106,8 +112,8 @@ Verify Query - Get results as a list of dictionaries [Tags] db smoke ${output} = Query SELECT * FROM person; \ True Log ${output} - Should Be Equal As Strings &{output[0]}[first_name] Franz Allan - Should Be Equal As Strings &{output[1]}[first_name] Jerry + Should Be Equal As Strings ${output[0]['first_name']} Franz Allan + Should Be Equal As Strings ${output[1]['first_name']} Jerry Verify Execute SQL String - Row Count person table ${output} = Execute SQL String SELECT COUNT(*) FROM person; diff --git a/test/PostgreSQL_Variables.yaml b/test/PostgreSQL_Variables.yaml new file mode 100644 index 0000000..504be83 --- /dev/null +++ b/test/PostgreSQL_Variables.yaml @@ -0,0 +1,5 @@ +POSTGRESQL_DBHost: localhost +POSTGRESQL_DBName: mydb +POSTGRESQL_DBPass: mypass +POSTGRESQL_DBPort: 54308 +POSTGRESQL_DBUser: myuser diff --git a/test/SQLite3_DB_Tests.robot b/test/SQLite3_DB_Tests.robot index 3b63684..3436a87 100644 --- a/test/SQLite3_DB_Tests.robot +++ b/test/SQLite3_DB_Tests.robot @@ -1,9 +1,11 @@ *** Settings *** Library DatabaseLibrary Library OperatingSystem +Force Tags standard *** Variables *** ${DBName} my_db_test +${SQLITE3_DBName} ${DBName} *** Test Cases *** Remove old DB if exists @@ -118,8 +120,8 @@ Verify Query - Get results as a list of dictionaries [Tags] db smoke ${output} = Query SELECT * FROM person; \ True Log ${output} - Should Be Equal As Strings &{output[0]}[first_name] Franz Allan - Should Be Equal As Strings &{output[1]}[first_name] Jerry + Should Be Equal As Strings ${output[0]['first_name']} Franz Allan + Should Be Equal As Strings ${output[1]['first_name']} Jerry Verify Execute SQL String - Row Count person table [Tags] db smoke diff --git a/test/run_tests.sh b/test/run_tests.sh new file mode 100755 index 0000000..5b46ba8 --- /dev/null +++ b/test/run_tests.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +robot -V DB_Variables.yaml -i standard . From c629f33203ef6cfa484bb642f23277f8dea3618f Mon Sep 17 00:00:00 2001 From: Luke Dziewanowski Date: Mon, 18 Oct 2021 22:33:25 +0200 Subject: [PATCH 2/3] Minor project updates --- .travis.yml | 8 ++++---- README.md | 22 +++++++++++++++++++--- docker-compose.yml | 32 ++++++++++++++++++++++++++++++++ requirements.txt | 7 ++++--- setup.py | 8 ++++---- src/DatabaseLibrary/version.py | 2 +- 6 files changed, 64 insertions(+), 15 deletions(-) create mode 100644 docker-compose.yml diff --git a/.travis.yml b/.travis.yml index 7c84158..15e90a7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,7 +22,7 @@ before_script: - mysql -e 'create database my_db_test;' - mysql -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1';" -uroot script: -# - flake8 src/ - - if [ $DB == 'SQLite' ]; then (cd test/ && pybot SQLite3_DB_Tests.robot); fi - - if [ $DB == 'Postgres' ]; then (cd test/ && pybot PostgreSQL_DB_Tests.robot); fi - - if [ $DB == 'MySQL' ]; then (cd test/ && pybot MySQL_DB_Tests.robot); fi + # - flake8 src/ + - if [ $DB == 'SQLite' ]; then (cd test/ && robot SQLite3_DB_Tests.robot); fi + - if [ $DB == 'Postgres' ]; then (cd test/ && robot PostgreSQL_DB_Tests.robot); fi + - if [ $DB == 'MySQL' ]; then (cd test/ && robot MySQL_DB_Tests.robot); fi diff --git a/README.md b/README.md index 3889120..8ddf170 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,20 @@ -Robotframework-Database-Library -=============================== +# Robotframework-Database-Library -Database Library contains utilities meant for Robot Framework's usage. This can allow you to query your database after an action has been made to verify the results. This is compatible* with any Database API Specification 2.0 module. +Database Library contains utilities meant for Robot Framework's usage. This can allow you to query your database after an action has been made to verify the results. This is compatible\* with any Database API Specification 2.0 module. + +## Testing + +``` +docker-compose up -d +docker-compose ps + +popd test +# Update `DB_Variables.yaml` with proper ports + +robot -V DB_Variables.yaml -i standard . + +# or just +./run_tests.sh + +pushd +``` diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..267001c --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,32 @@ +version: '3.1' + +services: + mysqldb: + image: mysql + restart: always + environment: + MYSQL_DATABASE: mydb + MYSQL_USER: myuser + MYSQL_PASSWORD: mypass + MYSQL_RANDOM_ROOT_PASSWORD: 'yes' + ports: + - '3306' + postgresqldb: + image: postgres + restart: always + environment: + POSTGRES_DB: mydb + POSTGRES_USER: myuser + POSTGRES_PASSWORD: mypass + ports: + - '5432' + db2db: + image: ibmcom/db2 + restart: always + environment: + LICENSE: accept + DBNAME: mydb + DB2INSTANCE: myuser + DB2INST1_PASSWORD: mypass + ports: + - '50000' diff --git a/requirements.txt b/requirements.txt index cb708a2..5fb8bb9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ -#PyMySQL==0.7.4 -#psycopg2==2.6.1 -robotframework>=3.0 +#PyMySQL==1.0.2 +#psycopg2==2.9.1 +robotframework>=4.0.0 + diff --git a/setup.py b/setup.py index fa5c028..566159f 100755 --- a/setup.py +++ b/setup.py @@ -26,13 +26,13 @@ version_file = join(dirname(abspath(__file__)), 'src', 'DatabaseLibrary', 'version.py') +pkg_vars = {} -with open(version_file) as file: - code = compile(file.read(), version_file, 'exec') - exec(code) +with open(version_file) as fp: + exec(fp.read(), pkg_vars) setup(name = 'robotframework-databaselibrary', - version = VERSION, + version = pkg_vars['VERSION'], description = 'Database utility library for Robot Framework', author = 'Franz Allan Valencia See', author_email = 'franz.see@gmail.com', diff --git a/src/DatabaseLibrary/version.py b/src/DatabaseLibrary/version.py index 6937870..204a96f 100644 --- a/src/DatabaseLibrary/version.py +++ b/src/DatabaseLibrary/version.py @@ -1 +1 @@ -VERSION = '1.2.4' +VERSION = '2.0.0' From c936b435f3a405f61ee49d8294802ff9f073bf3b Mon Sep 17 00:00:00 2001 From: Luke Dziewanowski Date: Thu, 21 Oct 2021 09:03:56 +0200 Subject: [PATCH 3/3] Add alias with backward compability --- .gitignore | 8 +- .travis.yml | 6 +- README.md | 18 +- doc/DatabaseLibrary.html | 1435 ++++++++++++++++----- docker-compose.yml | 1 - run_tests.sh | 30 + src/DatabaseLibrary/assertion.py | 46 +- src/DatabaseLibrary/connection_manager.py | 103 +- src/DatabaseLibrary/query.py | 75 +- src/DatabaseLibrary/version.py | 2 +- test/Aliases_SQLite3_DB_Tests.robot | 55 + test/DB2SQL_DB_Tests.robot | 29 +- test/DB2_Variables.yaml | 4 +- test/DB_Variables.yaml | 11 +- test/MySQL_DB_Tests.robot | 43 +- test/PostgreSQL_DB_Tests.robot | 12 +- test/SQLite3_DB_Tests.robot | 51 +- test/run_tests.sh | 3 - 18 files changed, 1404 insertions(+), 528 deletions(-) create mode 100755 run_tests.sh create mode 100644 test/Aliases_SQLite3_DB_Tests.robot delete mode 100755 test/run_tests.sh diff --git a/.gitignore b/.gitignore index 68d5d70..fe6dc4c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,8 +3,8 @@ build/ .idea .py*/ *.egg-info/ -test/log.html -test/my_db_test.db -test/output.xml -test/report.html +log.html +output.xml +report.html test/logs/ +test/*.db diff --git a/.travis.yml b/.travis.yml index 15e90a7..84d4907 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,6 +23,6 @@ before_script: - mysql -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1';" -uroot script: # - flake8 src/ - - if [ $DB == 'SQLite' ]; then (cd test/ && robot SQLite3_DB_Tests.robot); fi - - if [ $DB == 'Postgres' ]; then (cd test/ && robot PostgreSQL_DB_Tests.robot); fi - - if [ $DB == 'MySQL' ]; then (cd test/ && robot MySQL_DB_Tests.robot); fi + - if [ $DB == 'SQLite' ]; then (robot test/SQLite3_DB_Tests.robot test/Aliases_SQLite3_DB_Tests.robot); fi + - if [ $DB == 'Postgres' ]; then (robot test/robot PostgreSQL_DB_Tests.robot); fi + - if [ $DB == 'MySQL' ]; then (robot test/robot MySQL_DB_Tests.robot); fi diff --git a/README.md b/README.md index 8ddf170..c37fd62 100644 --- a/README.md +++ b/README.md @@ -4,17 +4,25 @@ Database Library contains utilities meant for Robot Framework's usage. This can ## Testing +Manualy start databases in docker-compose and then run "main" tests: + ``` docker-compose up -d docker-compose ps -popd test # Update `DB_Variables.yaml` with proper ports -robot -V DB_Variables.yaml -i standard . +robot -V test/DB_Variables.yaml -i main test +``` -# or just -./run_tests.sh +Or just leave it all to the small Bash script that will setup docker-compose environment and set proper values to test/DB_Variables.yaml: -pushd +``` +./run_tests.sh clean +``` + +If you wish to start only tests without setup docker-compose setup: + +``` +./run_tests.sh ``` diff --git a/doc/DatabaseLibrary.html b/doc/DatabaseLibrary.html index 058765e..78e2c96 100644 --- a/doc/DatabaseLibrary.html +++ b/doc/DatabaseLibrary.html @@ -1,165 +1,584 @@ - + + - + + @@ -557,7 +1112,7 @@

Opening library documentation failed

  • Verify that you have JavaScript enabled in your browser.
  • -
  • Make sure you are using a modern enough browser. If using Internet Explorer, version 8 or newer is required.
  • +
  • Make sure you are using a modern enough browser. If using Internet Explorer, version 11 is required.
  • Check are there messages in your browser's JavaScript error log. Please report the problem if you suspect you have encountered a bug.
@@ -565,26 +1120,83 @@

Opening library documentation failed

- + + + + + + + + + diff --git a/docker-compose.yml b/docker-compose.yml index 267001c..5a722cc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -26,7 +26,6 @@ services: environment: LICENSE: accept DBNAME: mydb - DB2INSTANCE: myuser DB2INST1_PASSWORD: mypass ports: - '50000' diff --git a/run_tests.sh b/run_tests.sh new file mode 100755 index 0000000..8d7caf4 --- /dev/null +++ b/run_tests.sh @@ -0,0 +1,30 @@ +#!/bin/bash -xe + +function startup { + docker-compose up -d + sleep 10 +} + +function cleanup { + docker-compose down +} + +if [[ $1 == "clean" ]] +then + trap cleanup EXIT + startup + sleep 10 +fi + +export MYSQL_PORT=`docker-compose port mysqldb 3306 | cut -d ":" -f 2` +export POSTGRESQL_PORT=`docker-compose port postgresqldb 5432 | cut -d ":" -f 2` +export DB2_PORT=`docker-compose port db2db 50000 | cut -d ":" -f 2` + +yq e -i ' + .MYSQL_DBPort = env(MYSQL_PORT) | + .POSTGRESQL_DBPort = env(POSTGRESQL_PORT) | + .DB2_DBPort = env(DB2_PORT) +' test/DB_Variables.yaml + + +robot --randomize none -V test/DB_Variables.yaml -i main test diff --git a/src/DatabaseLibrary/assertion.py b/src/DatabaseLibrary/assertion.py index 70ed6dd..cf94a4f 100644 --- a/src/DatabaseLibrary/assertion.py +++ b/src/DatabaseLibrary/assertion.py @@ -20,7 +20,7 @@ class Assertion(object): Assertion handles all the assertions of Database Library. """ - def check_if_exists_in_database(self, selectStatement, sansTran=False): + def check_if_exists_in_database(self, selectStatement, sansTran=False, alias=None): """ Check if any row would be returned by given the input `selectStatement`. If there are no results, then this will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit transaction @@ -33,6 +33,7 @@ def check_if_exists_in_database(self, selectStatement, sansTran=False): When you have the following assertions in your robot | Check If Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | | Check If Exists In Database | SELECT id FROM person WHERE first_name = 'John' | + | Check If Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | alias=my_alias | Then you will get the following: | Check If Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | # PASS | @@ -41,12 +42,12 @@ def check_if_exists_in_database(self, selectStatement, sansTran=False): Using optional `sansTran` to run command without an explicit transaction commit or rollback: | Check If Exists In Database | SELECT id FROM person WHERE first_name = 'John' | True | """ - logger.info ('Executing : Check If Exists In Database | %s ' % selectStatement) - if not self.query(selectStatement, sansTran): + logger.info ('Executing : Check If Exists In Database [%s] | %s ' % (alias, selectStatement)) + if not self.query(selectStatement, sansTran, alias=alias): raise AssertionError("Expected to have have at least one row from '%s' " "but got 0 rows." % selectStatement) - def check_if_not_exists_in_database(self, selectStatement, sansTran=False): + def check_if_not_exists_in_database(self, selectStatement, sansTran=False, alias=None): """ This is the negation of `check_if_exists_in_database`. @@ -61,6 +62,7 @@ def check_if_not_exists_in_database(self, selectStatement, sansTran=False): When you have the following assertions in your robot | Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'John' | | Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | + | Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | alias=my_alias | Then you will get the following: | Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'John' | # PASS | @@ -70,12 +72,12 @@ def check_if_not_exists_in_database(self, selectStatement, sansTran=False): | Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'John' | True | """ logger.info('Executing : Check If Not Exists In Database | %s ' % selectStatement) - queryResults = self.query(selectStatement, sansTran) + queryResults = self.query(selectStatement, sansTran, alias=alias) if queryResults: raise AssertionError("Expected to have have no rows from '%s' " "but got some rows : %s." % (selectStatement, queryResults)) - def row_count_is_0(self, selectStatement, sansTran=False): + def row_count_is_0(self, selectStatement, sansTran=False, alias=None): """ Check if any rows are returned from the submitted `selectStatement`. If there are, then this will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit transaction commit or @@ -88,6 +90,7 @@ def row_count_is_0(self, selectStatement, sansTran=False): When you have the following assertions in your robot | Row Count is 0 | SELECT id FROM person WHERE first_name = 'Franz Allan' | | Row Count is 0 | SELECT id FROM person WHERE first_name = 'John' | + | Row Count is 0 | SELECT id FROM person WHERE first_name = 'John' | alias=my_alias | Then you will get the following: | Row Count is 0 | SELECT id FROM person WHERE first_name = 'Franz Allan' | # FAIL | @@ -97,12 +100,12 @@ def row_count_is_0(self, selectStatement, sansTran=False): | Row Count is 0 | SELECT id FROM person WHERE first_name = 'John' | True | """ logger.info('Executing : Row Count Is 0 | %s ' % selectStatement) - num_rows = self.row_count(selectStatement, sansTran) + num_rows = self.row_count(selectStatement, sansTran, alias=alias) if num_rows > 0: raise AssertionError("Expected zero rows to be returned from '%s' " "but got rows back. Number of rows returned was %s" % (selectStatement, num_rows)) - def row_count_is_equal_to_x(self, selectStatement, numRows, sansTran=False): + def row_count_is_equal_to_x(self, selectStatement, numRows, sansTran=False, alias=None): """ Check if the number of rows returned from `selectStatement` is equal to the value submitted. If not, then this will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit @@ -116,6 +119,7 @@ def row_count_is_equal_to_x(self, selectStatement, numRows, sansTran=False): When you have the following assertions in your robot | Row Count Is Equal To X | SELECT id FROM person | 1 | | Row Count Is Equal To X | SELECT id FROM person WHERE first_name = 'John' | 0 | + | Row Count Is Equal To X | SELECT id FROM person WHERE first_name = 'John' | 0 | alias=my_alias | Then you will get the following: | Row Count Is Equal To X | SELECT id FROM person | 1 | # FAIL | @@ -125,12 +129,12 @@ def row_count_is_equal_to_x(self, selectStatement, numRows, sansTran=False): | Row Count Is Equal To X | SELECT id FROM person WHERE first_name = 'John' | 0 | True | """ logger.info('Executing : Row Count Is Equal To X | %s | %s ' % (selectStatement, numRows)) - num_rows = self.row_count(selectStatement, sansTran) + num_rows = self.row_count(selectStatement, sansTran, alias=alias) if num_rows != int(numRows.encode('ascii')): raise AssertionError("Expected same number of rows to be returned from '%s' " "than the returned rows of %s" % (selectStatement, num_rows)) - def row_count_is_greater_than_x(self, selectStatement, numRows, sansTran=False): + def row_count_is_greater_than_x(self, selectStatement, numRows, sansTran=False, alias=None): """ Check if the number of rows returned from `selectStatement` is greater than the value submitted. If not, then this will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit @@ -144,6 +148,7 @@ def row_count_is_greater_than_x(self, selectStatement, numRows, sansTran=False): When you have the following assertions in your robot | Row Count Is Greater Than X | SELECT id FROM person | 1 | | Row Count Is Greater Than X | SELECT id FROM person WHERE first_name = 'John' | 0 | + | Row Count Is Greater Than X | SELECT id FROM person WHERE first_name = 'John' | 0 | alias=my_alias | Then you will get the following: | Row Count Is Greater Than X | SELECT id FROM person | 1 | # PASS | @@ -153,12 +158,12 @@ def row_count_is_greater_than_x(self, selectStatement, numRows, sansTran=False): | Row Count Is Greater Than X | SELECT id FROM person | 1 | True | """ logger.info('Executing : Row Count Is Greater Than X | %s | %s ' % (selectStatement, numRows)) - num_rows = self.row_count(selectStatement, sansTran) + num_rows = self.row_count(selectStatement, sansTran, alias=alias) if num_rows <= int(numRows.encode('ascii')): raise AssertionError("Expected more rows to be returned from '%s' " "than the returned rows of %s" % (selectStatement, num_rows)) - def row_count_is_less_than_x(self, selectStatement, numRows, sansTran=False): + def row_count_is_less_than_x(self, selectStatement, numRows, sansTran=False, alias=None): """ Check if the number of rows returned from `selectStatement` is less than the value submitted. If not, then this will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit @@ -172,6 +177,7 @@ def row_count_is_less_than_x(self, selectStatement, numRows, sansTran=False): When you have the following assertions in your robot | Row Count Is Less Than X | SELECT id FROM person | 3 | | Row Count Is Less Than X | SELECT id FROM person WHERE first_name = 'John' | 1 | + | Row Count Is Less Than X | SELECT id FROM person WHERE first_name = 'John' | 1 | alias=my_alias | Then you will get the following: | Row Count Is Less Than X | SELECT id FROM person | 3 | # PASS | @@ -181,12 +187,12 @@ def row_count_is_less_than_x(self, selectStatement, numRows, sansTran=False): | Row Count Is Less Than X | SELECT id FROM person | 3 | True | """ logger.info('Executing : Row Count Is Less Than X | %s | %s ' % (selectStatement, numRows)) - num_rows = self.row_count(selectStatement, sansTran) + num_rows = self.row_count(selectStatement, sansTran, alias=alias) if num_rows >= int(numRows.encode('ascii')): raise AssertionError("Expected less rows to be returned from '%s' " "than the returned rows of %s" % (selectStatement, num_rows)) - def table_must_exist(self, tableName, sansTran=False): + def table_must_exist(self, tableName, sansTran=False, alias=None): """ Check if the table given exists in the database. Set optional input `sansTran` to True to run command without an explicit transaction commit or rollback. @@ -199,21 +205,23 @@ def table_must_exist(self, tableName, sansTran=False): Then you will get the following: | Table Must Exist | person | # PASS | | Table Must Exist | first_name | # FAIL | + | Table Must Exist | first_name | alias=my_alias | Using optional `sansTran` to run command without an explicit transaction commit or rollback: | Table Must Exist | person | True | """ + _, db_api_module_name = self._cache.switch(alias) logger.info('Executing : Table Must Exist | %s ' % tableName) - if self.db_api_module_name in ["cx_Oracle"]: + if db_api_module_name in ["cx_Oracle"]: selectStatement = ("SELECT * FROM all_objects WHERE object_type IN ('TABLE','VIEW') AND owner = SYS_CONTEXT('USERENV', 'SESSION_USER') AND object_name = UPPER('%s')" % tableName) - elif self.db_api_module_name in ["sqlite3"]: + elif db_api_module_name in ["sqlite3"]: selectStatement = ("SELECT name FROM sqlite_master WHERE type='table' AND name='%s' COLLATE NOCASE" % tableName) - elif self.db_api_module_name in ["ibm_db", "ibm_db_dbi"]: + elif db_api_module_name in ["ibm_db", "ibm_db_dbi"]: selectStatement = ("SELECT name FROM SYSIBM.SYSTABLES WHERE type='T' AND name=UPPER('%s')" % tableName) - elif self.db_api_module_name in ["teradata"]: + elif db_api_module_name in ["teradata"]: selectStatement = ("SELECT TableName FROM DBC.TablesV WHERE TableKind='T' AND TableName='%s'" % tableName) else: selectStatement = ("SELECT * FROM information_schema.tables WHERE table_name='%s'" % tableName) - num_rows = self.row_count(selectStatement, sansTran) + num_rows = self.row_count(selectStatement, sansTran, alias=alias) if num_rows == 0: raise AssertionError("Table '%s' does not exist in the db" % tableName) diff --git a/src/DatabaseLibrary/connection_manager.py b/src/DatabaseLibrary/connection_manager.py index 3060a45..2ea31fa 100644 --- a/src/DatabaseLibrary/connection_manager.py +++ b/src/DatabaseLibrary/connection_manager.py @@ -13,6 +13,7 @@ # limitations under the License. import importlib +import robot try: import ConfigParser @@ -29,18 +30,17 @@ class ConnectionManager(object): def __init__(self): """ - Initializes _dbconnection to None. + Initializes dbconnection to None. """ - self._dbconnection = None - self.db_api_module_name = None + self._cache = robot.utils.ConnectionCache('No sessions created') - def connect_to_database(self, dbapiModuleName=None, dbName=None, dbUsername=None, dbPassword=None, dbHost=None, dbPort=None, dbCharset=None, dbDriver=None, dbConfigFile="./resources/db.cfg"): + def connect_to_database(self, dbapiModuleName=None, dbName=None, dbUsername=None, dbPassword=None, dbHost=None, dbPort=None, dbCharset=None, dbDriver=None, dbConfigFile="./resources/db.cfg", alias='default'): """ Loads the DB API 2.0 module given `dbapiModuleName` then uses it to connect to the database using `dbName`, `dbUsername`, and `dbPassword`. Optionally, you can specify a `dbConfigFile` wherein it will load the - default property values for `dbapiModuleName`, `dbName` `dbUsername` + alias (or alias will be "default") property values for `dbapiModuleName`, `dbName` `dbUsername` and `dbPassword` (note: specifying `dbapiModuleName`, `dbName` `dbUsername` or `dbPassword` directly will override the properties of the same key in `dbConfigFile`). If no `dbConfigFile` is specified, it @@ -50,7 +50,7 @@ def connect_to_database(self, dbapiModuleName=None, dbName=None, dbUsername=None your database credentials. Example db.cfg file - | [default] + | [alias] | dbapiModuleName=pymysqlforexample | dbName=yourdbname | dbUsername=yourusername @@ -61,6 +61,7 @@ def connect_to_database(self, dbapiModuleName=None, dbName=None, dbUsername=None Example usage: | # explicitly specifies all db property values | | Connect To Database | psycopg2 | my_db | postgres | s3cr3t | tiger.foobar.com | 5432 | + | Connect To Database | psycopg2 | my_db | postgres | s3cr3t | tiger.foobar.com | 5432 | alias=my_alias | | # loads all property values from default.cfg | | Connect To Database | dbConfigFile=default.cfg | @@ -78,60 +79,62 @@ def connect_to_database(self, dbapiModuleName=None, dbName=None, dbUsername=None config = ConfigParser.ConfigParser() config.read([dbConfigFile]) - dbapiModuleName = dbapiModuleName or config.get('default', 'dbapiModuleName') - dbName = dbName or config.get('default', 'dbName') - dbUsername = dbUsername or config.get('default', 'dbUsername') - dbPassword = dbPassword if dbPassword is not None else config.get('default', 'dbPassword') - dbHost = dbHost or config.get('default', 'dbHost') or 'localhost' - dbPort = int(dbPort or config.get('default', 'dbPort')) + dbapiModuleName = dbapiModuleName or config.get(alias, 'dbapiModuleName') + dbName = dbName or config.get(alias, 'dbName') + dbUsername = dbUsername or config.get(alias, 'dbUsername') + dbPassword = dbPassword if dbPassword is not None else config.get(alias, 'dbPassword') + dbHost = dbHost or config.get(alias, 'dbHost') or 'localhost' + dbPort = int(dbPort or config.get(alias, 'dbPort')) + dbconnection = None + db_api_module_name = None if dbapiModuleName == "excel" or dbapiModuleName == "excelrw": - self.db_api_module_name = "pyodbc" + db_api_module_name = "pyodbc" db_api_2 = importlib.import_module("pyodbc") else: - self.db_api_module_name = dbapiModuleName + db_api_module_name = dbapiModuleName db_api_2 = importlib.import_module(dbapiModuleName) if dbapiModuleName in ["MySQLdb", "pymysql"]: dbPort = dbPort or 3306 logger.info('Connecting using : %s.connect(db=%s, user=%s, passwd=%s, host=%s, port=%s, charset=%s) ' % (dbapiModuleName, dbName, dbUsername, dbPassword, dbHost, dbPort, dbCharset)) - self._dbconnection = db_api_2.connect(db=dbName, user=dbUsername, passwd=dbPassword, host=dbHost, port=dbPort, charset=dbCharset) + dbconnection = db_api_2.connect(db=dbName, user=dbUsername, passwd=dbPassword, host=dbHost, port=dbPort, charset=dbCharset) elif dbapiModuleName in ["psycopg2"]: dbPort = dbPort or 5432 logger.info('Connecting using : %s.connect(database=%s, user=%s, password=%s, host=%s, port=%s) ' % (dbapiModuleName, dbName, dbUsername, dbPassword, dbHost, dbPort)) - self._dbconnection = db_api_2.connect(database=dbName, user=dbUsername, password=dbPassword, host=dbHost, port=dbPort) + dbconnection = db_api_2.connect(database=dbName, user=dbUsername, password=dbPassword, host=dbHost, port=dbPort) elif dbapiModuleName in ["pyodbc", "pypyodbc"]: dbPort = dbPort or 1433 dbDriver = dbDriver or "{SQL Server}" logger.info('Connecting using : %s.connect(DRIVER=%s;SERVER=%s,%s;DATABASE=%s;UID=%s;PWD=%s)' % (dbapiModuleName, dbDriver, dbHost, dbPort, dbName, dbUsername, dbPassword)) - self._dbconnection = db_api_2.connect('DRIVER=%s;SERVER=%s,%s;DATABASE=%s;UID=%s;PWD=%s' % ( dbDriver, dbHost, dbPort, dbName, dbUsername, dbPassword)) + dbconnection = db_api_2.connect('DRIVER=%s;SERVER=%s,%s;DATABASE=%s;UID=%s;PWD=%s' % ( dbDriver, dbHost, dbPort, dbName, dbUsername, dbPassword)) elif dbapiModuleName in ["excel"]: logger.info( 'Connecting using : %s.connect(DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=1;Extended Properties="Excel 8.0;HDR=YES";)' % ( dbapiModuleName, dbName)) - self._dbconnection = db_api_2.connect( + dbconnection = db_api_2.connect( 'DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=1;Extended Properties="Excel 8.0;HDR=YES";)' % ( dbName), autocommit=True) elif dbapiModuleName in ["excelrw"]: logger.info( 'Connecting using : %s.connect(DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=0;Extended Properties="Excel 8.0;HDR=YES";)' % ( dbapiModuleName, dbName)) - self._dbconnection = db_api_2.connect( + dbconnection = db_api_2.connect( 'DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;ReadOnly=0;Extended Properties="Excel 8.0;HDR=YES";)' % ( dbName), autocommit=True) elif dbapiModuleName in ["ibm_db", "ibm_db_dbi"]: dbPort = dbPort or 50000 logger.info('Connecting using : %s.connect(DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s;) ' % (dbapiModuleName, dbName, dbHost, dbPort, dbUsername, dbPassword)) - self._dbconnection = db_api_2.connect('DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s;' % (dbName, dbHost, dbPort, dbUsername, dbPassword), '', '') + dbconnection = db_api_2.connect('DATABASE=%s;HOSTNAME=%s;PORT=%s;PROTOCOL=TCPIP;UID=%s;PWD=%s;' % (dbName, dbHost, dbPort, dbUsername, dbPassword), '', '') elif dbapiModuleName in ["cx_Oracle"]: dbPort = dbPort or 1521 oracle_dsn = db_api_2.makedsn(host=dbHost, port=dbPort, service_name=dbName) logger.info('Connecting using: %s.connect(user=%s, password=%s, dsn=%s) ' % (dbapiModuleName, dbUsername, dbPassword, oracle_dsn)) - self._dbconnection = db_api_2.connect(user=dbUsername, password=dbPassword, dsn=oracle_dsn) + dbconnection = db_api_2.connect(user=dbUsername, password=dbPassword, dsn=oracle_dsn) elif dbapiModuleName in ["teradata"]: dbPort = dbPort or 1025 teradata_udaExec = db_api_2.UdaExec(appName="RobotFramework", version="1.0", logConsole=False) logger.info('Connecting using : %s.connect(database=%s, user=%s, password=%s, host=%s, port=%s) ' % (dbapiModuleName, dbName, dbUsername, dbPassword, dbHost, dbPort)) - self._dbconnection = teradata_udaExec.connect( + dbconnection = teradata_udaExec.connect( method="odbc", system=dbHost, database=dbName, @@ -144,13 +147,15 @@ def connect_to_database(self, dbapiModuleName=None, dbName=None, dbUsername=None dbPort = dbPort or 54321 logger.info('Connecting using : %s.connect(database=%s, user=%s, password=%s, host=%s, port=%s) ' % ( dbapiModuleName, dbName, dbUsername, dbPassword, dbHost, dbPort)) - self._dbconnection = db_api_2.connect(database=dbName, user=dbUsername, password=dbPassword, host=dbHost, + dbconnection = db_api_2.connect(database=dbName, user=dbUsername, password=dbPassword, host=dbHost, port=dbPort) else: logger.info('Connecting using : %s.connect(database=%s, user=%s, password=%s, host=%s, port=%s) ' % (dbapiModuleName, dbName, dbUsername, dbPassword, dbHost, dbPort)) - self._dbconnection = db_api_2.connect(database=dbName, user=dbUsername, password=dbPassword, host=dbHost, port=dbPort) + dbconnection = db_api_2.connect(database=dbName, user=dbUsername, password=dbPassword, host=dbHost, port=dbPort) - def connect_to_database_using_custom_params(self, dbapiModuleName=None, db_connect_string=''): + self._cache.register((dbconnection, db_api_module_name), alias=alias) + + def connect_to_database_using_custom_params(self, dbapiModuleName=None, db_connect_string='', alias='default'): """ Loads the DB API 2.0 module given `dbapiModuleName` then uses it to connect to the database using the map string `db_custom_param_string`. @@ -158,6 +163,7 @@ def connect_to_database_using_custom_params(self, dbapiModuleName=None, db_conne Example usage: | # for psycopg2 | | Connect To Database Using Custom Params | psycopg2 | database='my_db_test', user='postgres', password='s3cr3t', host='tiger.foobar.com', port=5432 | + | Connect To Database Using Custom Params | psycopg2 | database='my_db_test', user='postgres', password='s3cr3t', host='tiger.foobar.com', port=5432 | alias=my_alias | | # for JayDeBeApi | | Connect To Database Using Custom Params | jaydebeapi | 'oracle.jdbc.driver.OracleDriver', 'my_db_test', 'system', 's3cr3t' | @@ -166,24 +172,43 @@ def connect_to_database_using_custom_params(self, dbapiModuleName=None, db_conne db_connect_string = 'db_api_2.connect(%s)' % db_connect_string - self.db_api_module_name = dbapiModuleName + db_api_module_name = dbapiModuleName logger.info('Executing : Connect To Database Using Custom Params : %s.connect(%s) ' % (dbapiModuleName, db_connect_string)) - self._dbconnection = eval(db_connect_string) + dbconnection = eval(db_connect_string) + self._cache.register((dbconnection, db_api_module_name), alias=alias) - def disconnect_from_database(self): + def disconnect_from_database(self, alias=None): """ Disconnects from the database. For example: | Disconnect From Database | # disconnects from current connection to the database | + | Disconnect From Database | alias=my_alias | # disconnects from current connection to the database | """ logger.info('Executing : Disconnect From Database') - if self._dbconnection==None: - return 'No open connection to close' + try: + dbconnection, _ = self._cache.switch(alias) + except: + return 'No connection to close' + if dbconnection: + dbconnection.close() else: - self._dbconnection.close() + return 'No open connection to close' + + def disconnect_from_all_databases(self): + """ + Disconnects from all the databases. + + For example: + | Disconnect From All Databases | # disconnects from all connections to the database | + """ + logger.info('Executing : Disconnect From All Databases') + for dbconnection, _ in self._cache: + if dbconnection: + dbconnection.close() + self._cache.empty_cache() - def set_auto_commit(self, autoCommit=True): + def set_auto_commit(self, autoCommit=True, alias=None): """ Turn the autocommit on the database connection ON or OFF. @@ -196,8 +221,20 @@ def set_auto_commit(self, autoCommit=True): Example: | # Default behaviour, sets auto commit to true | Set Auto Commit + | Set Auto Commit | alias=my_alias | | # Explicitly set the desired state | Set Auto Commit | False """ logger.info('Executing : Set Auto Commit') - self._dbconnection.autocommit = autoCommit + dbconnection, _ = self._cache.switch(alias) + dbconnection.autocommit = autoCommit + + def switch_database(self, alias): + """ + Switch the current database. + + Example: + | Switch Database | my_alias | + | Switch Database | alias=my_alias | + """ + self._cache.switch(alias) diff --git a/src/DatabaseLibrary/query.py b/src/DatabaseLibrary/query.py index 289d048..35fb5a8 100644 --- a/src/DatabaseLibrary/query.py +++ b/src/DatabaseLibrary/query.py @@ -21,7 +21,7 @@ class Query(object): Query handles all the querying done by the Database Library. """ - def query(self, selectStatement, sansTran=False, returnAsDict=False): + def query(self, selectStatement, sansTran=False, returnAsDict=False, alias=None): """ Uses the input `selectStatement` to query for the values that will be returned as a list of tuples. Set optional input `sansTran` to True to run command without an explicit transaction commit or rollback. @@ -40,6 +40,7 @@ def query(self, selectStatement, sansTran=False, returnAsDict=False): When you do the following: | @{queryResults} | Query | SELECT * FROM person | + | @{queryResults} | Query | SELECT * FROM person | alias=my_alias | | Log Many | @{queryResults} | You will get the following: @@ -55,10 +56,11 @@ def query(self, selectStatement, sansTran=False, returnAsDict=False): Using optional `sansTran` to run command without an explicit transaction commit or rollback: | @{queryResults} | Query | SELECT * FROM person | True | """ + dbconnection, _ = self._cache.switch(alias) cur = None try: - cur = self._dbconnection.cursor() - logger.info('Executing : Query | %s ' % selectStatement) + cur = dbconnection.cursor() + logger.info('Executing : Query [%s] | %s ' % (alias, selectStatement)) self.__execute_sql(cur, selectStatement) allRows = cur.fetchall() @@ -77,9 +79,9 @@ def query(self, selectStatement, sansTran=False, returnAsDict=False): finally: if cur: if not sansTran: - self._dbconnection.rollback() + dbconnection.rollback() - def row_count(self, selectStatement, sansTran=False): + def row_count(self, selectStatement, sansTran=False, alias=None): """ Uses the input `selectStatement` to query the database and returns the number of rows from the query. Set optional input `sansTran` to True to run command without an explicit transaction commit or rollback. @@ -91,6 +93,7 @@ def row_count(self, selectStatement, sansTran=False): When you do the following: | ${rowCount} | Row Count | SELECT * FROM person | + | ${rowCount} | Row Count | SELECT * FROM person | alias=my_alias | | Log | ${rowCount} | You will get the following: @@ -106,13 +109,14 @@ def row_count(self, selectStatement, sansTran=False): Using optional `sansTran` to run command without an explicit transaction commit or rollback: | ${rowCount} | Row Count | SELECT * FROM person | True | """ + dbconnection, db_api_module_name = self._cache.switch(alias) cur = None try: - cur = self._dbconnection.cursor() + cur = dbconnection.cursor() logger.info('Executing : Row Count | %s ' % selectStatement) self.__execute_sql(cur, selectStatement) data = cur.fetchall() - if self.db_api_module_name in ["sqlite3", "ibm_db", "ibm_db_dbi", "pyodbc"]: + if db_api_module_name in ["sqlite3", "ibm_db", "ibm_db_dbi", "pyodbc"]: rowCount = len(data) else: rowCount = cur.rowcount @@ -120,9 +124,9 @@ def row_count(self, selectStatement, sansTran=False): finally: if cur: if not sansTran: - self._dbconnection.rollback() + dbconnection.rollback() - def description(self, selectStatement, sansTran=False): + def description(self, selectStatement, sansTran=False, alias=None): """ Uses the input `selectStatement` to query a table in the db which will be used to determine the description. Set optional input `sansTran` to True to run command without an explicit transaction commit or rollback. @@ -133,6 +137,7 @@ def description(self, selectStatement, sansTran=False): When you do the following: | @{queryResults} | Description | SELECT * FROM person | + | @{queryResults} | Description | SELECT * FROM person | alias=my_alias | | Log Many | @{queryResults} | You will get the following: @@ -143,9 +148,10 @@ def description(self, selectStatement, sansTran=False): Using optional `sansTran` to run command without an explicit transaction commit or rollback: | @{queryResults} | Description | SELECT * FROM person | True | """ + dbconnection, _ = self._cache.switch(alias) cur = None try: - cur = self._dbconnection.cursor() + cur = dbconnection.cursor() logger.info('Executing : Description | %s ' % selectStatement) self.__execute_sql(cur, selectStatement) description = list(cur.description) @@ -156,9 +162,9 @@ def description(self, selectStatement, sansTran=False): finally: if cur: if not sansTran: - self._dbconnection.rollback() + dbconnection.rollback() - def delete_all_rows_from_table(self, tableName, sansTran=False): + def delete_all_rows_from_table(self, tableName, sansTran=False, alias=None): """ Delete all the rows within a given table. Set optional input `sansTran` to True to run command without an explicit transaction commit or rollback. @@ -167,6 +173,7 @@ def delete_all_rows_from_table(self, tableName, sansTran=False): When you do the following: | Delete All Rows From Table | person | + | Delete All Rows From Table | person | alias=my_alias | If all the rows can be successfully deleted, then you will get: | Delete All Rows From Table | person | # PASS | @@ -177,24 +184,25 @@ def delete_all_rows_from_table(self, tableName, sansTran=False): Using optional `sansTran` to run command without an explicit transaction commit or rollback: | Delete All Rows From Table | person | True | """ + dbconnection, _ = self._cache.switch(alias) cur = None selectStatement = ("DELETE FROM %s;" % tableName) try: - cur = self._dbconnection.cursor() + cur = dbconnection.cursor() logger.info('Executing : Delete All Rows From Table | %s ' % selectStatement) result = self.__execute_sql(cur, selectStatement) if result is not None: if not sansTran: - self._dbconnection.commit() + dbconnection.commit() return result if not sansTran: - self._dbconnection.commit() + dbconnection.commit() finally: if cur: if not sansTran: - self._dbconnection.rollback() + dbconnection.rollback() - def execute_sql_script(self, sqlScriptFileName, sansTran=False): + def execute_sql_script(self, sqlScriptFileName, sansTran=False, alias=None): """ Executes the content of the `sqlScriptFileName` as SQL commands. Useful for setting the database to a known state before running your tests, or clearing out your test data after running each a test. Set optional input @@ -203,6 +211,8 @@ def execute_sql_script(self, sqlScriptFileName, sansTran=False): Sample usage : | Execute Sql Script | ${EXECDIR}${/}resources${/}DDL-setup.sql | | Execute Sql Script | ${EXECDIR}${/}resources${/}DML-setup.sql | + | Execute Sql Script | ${EXECDIR}${/}resources${/}DDL-setup.sql | alias=my_alias | + | Execute Sql Script | ${EXECDIR}${/}resources${/}DML-setup.sql | alias=my_alias | | #interesting stuff here | | Execute Sql Script | ${EXECDIR}${/}resources${/}DML-teardown.sql | | Execute Sql Script | ${EXECDIR}${/}resources${/}DDL-teardown.sql | @@ -248,11 +258,12 @@ def execute_sql_script(self, sqlScriptFileName, sansTran=False): Using optional `sansTran` to run command without an explicit transaction commit or rollback: | Execute Sql Script | ${EXECDIR}${/}resources${/}DDL-setup.sql | True | """ + dbconnection, _ = self._cache.switch(alias) sqlScriptFile = open(sqlScriptFileName ,encoding='UTF-8') cur = None try: - cur = self._dbconnection.cursor() + cur = dbconnection.cursor() logger.info('Executing : Execute SQL Script | %s ' % sqlScriptFileName) sqlStatement = '' for line in sqlScriptFile: @@ -284,13 +295,13 @@ def execute_sql_script(self, sqlScriptFileName, sansTran=False): self.__execute_sql(cur, sqlStatement) if not sansTran: - self._dbconnection.commit() + dbconnection.commit() finally: if cur: if not sansTran: - self._dbconnection.rollback() + dbconnection.rollback() - def execute_sql_string(self, sqlString, sansTran=False): + def execute_sql_string(self, sqlString, sansTran=False, alias=None): """ Executes the sqlString as SQL commands. Useful to pass arguments to your sql. Set optional input `sansTran` to True to run command without an explicit transaction commit or rollback. @@ -299,6 +310,7 @@ def execute_sql_string(self, sqlString, sansTran=False): For example: | Execute Sql String | DELETE FROM person_employee_table; DELETE FROM person_table | + | Execute Sql String | DELETE FROM person_employee_table; DELETE FROM person_table | alias=my_alias | For example with an argument: | Execute Sql String | SELECT * FROM person WHERE first_name = ${FIRSTNAME} | @@ -306,19 +318,20 @@ def execute_sql_string(self, sqlString, sansTran=False): Using optional `sansTran` to run command without an explicit transaction commit or rollback: | Execute Sql String | DELETE FROM person_employee_table; DELETE FROM person_table | True | """ + dbconnection, _ = self._cache.switch(alias) cur = None try: - cur = self._dbconnection.cursor() + cur = dbconnection.cursor() logger.info('Executing : Execute SQL String | %s ' % sqlString) self.__execute_sql(cur, sqlString) if not sansTran: - self._dbconnection.commit() + dbconnection.commit() finally: if cur: if not sansTran: - self._dbconnection.rollback() + dbconnection.rollback() - def call_stored_procedure(self, spName, spParams=None, sansTran=False): + def call_stored_procedure(self, spName, spParams=None, sansTran=False, alias=None): """ Uses the inputs of `spName` and 'spParams' to call a stored procedure. Set optional input `sansTran` to True to run command without an explicit transaction commit or rollback. @@ -331,6 +344,7 @@ def call_stored_procedure(self, spName, spParams=None, sansTran=False): Example: | @{ParamList} = | Create List | FirstParam | SecondParam | ThirdParam | | @{QueryResults} = | Call Stored Procedure | DBName.SchemaName.StoredProcName | List of Parameters | + | @{QueryResults} = | Call Stored Procedure | DBName.SchemaName.StoredProcName | List of Parameters | alias=my_alias | Example: | @{ParamList} = | Create List | Testing | LastName | @@ -341,14 +355,15 @@ def call_stored_procedure(self, spName, spParams=None, sansTran=False): Using optional `sansTran` to run command without an explicit transaction commit or rollback: | @{QueryResults} = | Call Stored Procedure | DBName.SchemaName.StoredProcName | List of Parameters | True | """ + dbconnection, db_api_module_name = self._cache.switch(alias) if spParams is None: spParams = [] cur = None try: - if self.db_api_module_name in ["cx_Oracle"]: - cur = self._dbconnection.cursor() + if db_api_module_name in ["cx_Oracle"]: + cur = dbconnection.cursor() else: - cur = self._dbconnection.cursor(as_dict=False) + cur = dbconnection.cursor(as_dict=False) PY3K = sys.version_info >= (3, 0) if not PY3K: spName = spName.encode('ascii', 'ignore') @@ -360,12 +375,12 @@ def call_stored_procedure(self, spName, spParams=None, sansTran=False): #logger.info ( ' %s ' % (row)) retVal.append(row) if not sansTran: - self._dbconnection.commit() + dbconnection.commit() return retVal finally: if cur: if not sansTran: - self._dbconnection.rollback() + dbconnection.rollback() def __execute_sql(self, cur, sqlStatement): return cur.execute(sqlStatement) diff --git a/src/DatabaseLibrary/version.py b/src/DatabaseLibrary/version.py index 204a96f..3e5f02a 100644 --- a/src/DatabaseLibrary/version.py +++ b/src/DatabaseLibrary/version.py @@ -1 +1 @@ -VERSION = '2.0.0' +VERSION = '1.3.4' diff --git a/test/Aliases_SQLite3_DB_Tests.robot b/test/Aliases_SQLite3_DB_Tests.robot new file mode 100644 index 0000000..40d7d72 --- /dev/null +++ b/test/Aliases_SQLite3_DB_Tests.robot @@ -0,0 +1,55 @@ +*** Settings *** +Library DatabaseLibrary +Library OperatingSystem +Force Tags main db smoke + +*** Variables *** +${DBName1} my_db_test1 +${DBName2} my_db_test2 + +*** Keywords *** +Remove DB file if exists + [Arguments] ${DB_FILE} + Run Keyword And Ignore Error Remove File ${DB_FILE} + File Should Not Exist ${DB_FILE} + Comment Sleep 1s + +*** Test Cases *** +Remove old DB if exists + Remove DB file if exists ${CURDIR}/${DBName1}.db + Remove DB file if exists ${CURDIR}/${DBName2}.db + +Connect to SQLiteDB + Comment Connect To Database Using Custom Params sqlite3 database='path_to_dbfile\dbname.db' + Connect To Database Using Custom Params sqlite3 database="${CURDIR}/${DBName1}.db", isolation_level=None alias=db1 + Connect To Database Using Custom Params sqlite3 database="${CURDIR}/${DBName2}.db", isolation_level=None alias=db2 + +Create person table + ${output} = Execute SQL String CREATE TABLE person (id integer unique,first_name varchar,last_name varchar); alias=db2 + Log ${output} + Should Be Equal As Strings ${output} None + +Create foobar table + ${output} = Execute SQL String create table foobar (id integer primary key, firstname varchar unique) alias=db1 + Log ${output} + Should Be Equal As Strings ${output} None + +Table Must Exist - person + Table Must Exist person alias=db2 + +Table Shouldn't Exist - person + Run Keyword And Expect Error Table 'person' does not exist in the db Table Must Exist person alias=db1 + +Table Shouldn't Exist - foobar + Run Keyword And Expect Error Table 'foobar' does not exist in the db Table Must Exist foobar alias=db2 + +Switch database without alias + Switch Database db2 + Table Must Exist person + Run Keyword And Expect Error Table 'foobar' does not exist in the db Table Must Exist foobar + +Disconnect from database db1 + Disconnect From Database alias=db1 + +Disconnect from all databases + Disconnect From All Databases diff --git a/test/DB2SQL_DB_Tests.robot b/test/DB2SQL_DB_Tests.robot index 06dc1b5..4cbf491 100644 --- a/test/DB2SQL_DB_Tests.robot +++ b/test/DB2SQL_DB_Tests.robot @@ -1,8 +1,9 @@ *** Settings *** Suite Setup Connect To Database ibm_db_dbi ${DB2_DBName} ${DB2_DBUser} ${DB2_DBPass} ${DB2_DBHost} ${DB2_DBPort} Suite Teardown Disconnect From Database -Resource DB2SQL_DB_Conf.txt Library DatabaseLibrary +Library Collections +Force Tags optional *** Variables *** ${DBName} dbname @@ -23,8 +24,8 @@ Create person table Should Be Equal As Strings ${output} None Execute SQL Script - Insert Data person table - Comment ${output} = Execute SQL Script ./my_db_test_insertData.sql - ${output} = Execute SQL Script ../test/my_db_test_insertData.sql + Comment ${output} = Execute SQL Script ${CURDIR}/my_db_test_insertData.sql + ${output} = Execute SQL Script ${CURDIR}/my_db_test_insertData.sql Log ${output} Should Be Equal As Strings ${output} None @@ -65,11 +66,20 @@ Verify person Description @{queryResults} = Description SELECT * FROM person fetch first 1 rows only; Log Many @{queryResults} ${output} = Set Variable ${queryResults[0]} - Should Be Equal As Strings ${output} ['ID', DBAPITypeObject(['NUM', 'DECIMAL', 'DEC', 'NUMERIC']), 12, 12, 10, 0, True] + Should Be Equal As Strings ${output[0]} ID + ${expected}= Evaluate ['DEC', 'NUMERIC', 'DECIMAL', 'NUM'] + Lists Should Be Equal ${output[1].col_types} ${expected} ignore_order=True + Should Be Equal As Strings ${output[2:]} [12, 12, 10, 0, True] ${output} = Set Variable ${queryResults[1]} - Should Be Equal As Strings ${output} ['FIRST_NAME', DBAPITypeObject(['CHARACTER VARYING', 'CHAR VARYING', 'VARCHAR', 'STRING', 'CHARACTER', 'CHAR']), 30, 30, 30, 0, True] + Should Be Equal As Strings ${output[0]} FIRST_NAME + ${expected}= Evaluate ['VARCHAR', 'CHARACTER VARYING', 'STRING', 'CHARACTER', 'CHAR', 'CHAR VARYING'] + Lists Should Be Equal ${output[1].col_types} ${expected} ignore_order=True + Should Be Equal As Strings ${output[2:]} [30, 30, 30, 0, True] ${output} = Set Variable ${queryResults[2]} - Should Be Equal As Strings ${output} ['LAST_NAME', DBAPITypeObject(['CHARACTER VARYING', 'CHAR VARYING', 'VARCHAR', 'STRING', 'CHARACTER', 'CHAR']), 30, 30, 30, 0, True] + Should Be Equal As Strings ${output[0]} LAST_NAME + ${expected}= Evaluate ['CHAR', 'CHAR VARYING', 'VARCHAR', 'CHARACTER VARYING', 'CHARACTER', 'STRING'] + Lists Should Be Equal ${output[1].col_types} ${expected} ignore_order=True + Should Be Equal As Strings ${output[2:]} [30, 30, 30, 0, True] ${NumColumns} = Get Length ${queryResults} Should Be Equal As Integers ${NumColumns} 3 @@ -87,8 +97,8 @@ Verify Query - Get results as a list of dictionaries [Tags] db smoke ${output} = Query SELECT * FROM person; \ True Log ${output} - Should Be Equal As Strings &{output[0]}[first_name] Franz Allan - Should Be Equal As Strings &{output[1]}[first_name] Jerry + Should Be Equal As Strings ${output[0]['FIRST_NAME']} Franz Allan + Should Be Equal As Strings ${output[1]['FIRST_NAME']} Jerry Insert Data Into Table foobar ${output} = Execute SQL String INSERT INTO foobar VALUES(1,'Jerry'); @@ -109,3 +119,6 @@ Verify Query - Row Count foobar table 0 row Drop person and foobar table Execute SQL String DROP TABLE person; Execute SQL String DROP TABLE foobar; + +Disconnect from all databases + Disconnect From All Databases diff --git a/test/DB2_Variables.yaml b/test/DB2_Variables.yaml index f3f82c1..23b2653 100644 --- a/test/DB2_Variables.yaml +++ b/test/DB2_Variables.yaml @@ -1,5 +1,5 @@ DB2_DBHost: localhost DB2_DBName: mydb DB2_DBPass: mypass -DB2_DBPort: 64481 -DB2_DBUser: myuser +DB2_DBPort: 64382 +DB2_DBUser: db2inst1 diff --git a/test/DB_Variables.yaml b/test/DB_Variables.yaml index b19a352..cd2fc91 100644 --- a/test/DB_Variables.yaml +++ b/test/DB_Variables.yaml @@ -1,13 +1,16 @@ MYSQL_DBHost: localhost MYSQL_DBName: mydb MYSQL_DBPass: mypass -MYSQL_DBPort: 64479 +MYSQL_DBPort: 50653 MYSQL_DBUser: myuser - POSTGRESQL_DBHost: localhost POSTGRESQL_DBName: mydb POSTGRESQL_DBPass: mypass -POSTGRESQL_DBPort: 64480 +POSTGRESQL_DBPort: 50655 POSTGRESQL_DBUser: myuser - SQLITE3_DBName: mydb +DB2_DBHost: localhost +DB2_DBName: mydb +DB2_DBPass: mypass +DB2_DBPort: 50654 +DB2_DBUser: db2inst1 diff --git a/test/MySQL_DB_Tests.robot b/test/MySQL_DB_Tests.robot index bca888f..b1b7909 100644 --- a/test/MySQL_DB_Tests.robot +++ b/test/MySQL_DB_Tests.robot @@ -3,7 +3,7 @@ Suite Setup Connect To Database pymysql ${MYSQL_DBName} ${MYSQL_D Suite Teardown Disconnect From Database Library DatabaseLibrary Library OperatingSystem -Force Tags standard +Force Tags main db smoke *** Variables *** ${DBHost} 127.0.0.1 @@ -19,66 +19,53 @@ ${MYSQL_DBPort} ${DBPort} *** Test Cases *** Create person table - [Tags] db smoke ${output} = Execute SQL String CREATE TABLE person (id integer unique,first_name varchar(20),last_name varchar(20)); Log ${output} Should Be Equal As Strings ${output} None Execute SQL Script - Insert Data person table - [Tags] db smoke - Comment ${output} = Execute SQL Script ./${DBName}_insertData.sql - ${output} = Execute SQL Script ./my_db_test_insertData.sql + Comment ${output} = Execute SQL Script ./my_db_test_insertData.sql + ${output} = Execute SQL Script ${CURDIR}/my_db_test_insertData.sql Log ${output} Should Be Equal As Strings ${output} None Execute SQL String - Create Table - [Tags] db smoke ${output} = Execute SQL String create table foobar (id integer primary key, firstname varchar(20) unique) Log ${output} Should Be Equal As Strings ${output} None Check If Exists In DB - Franz Allan - [Tags] db smoke Check If Exists In Database SELECT id FROM person WHERE first_name = 'Franz Allan'; Check If Not Exists In DB - Joe - [Tags] db smoke Check If Not Exists In Database SELECT id FROM person WHERE first_name = 'Joe'; Table Must Exist - person - [Tags] db smoke Table Must Exist person Verify Row Count is 0 - [Tags] db smoke Row Count is 0 SELECT * FROM person WHERE first_name = 'NotHere'; Verify Row Count is Equal to X - [Tags] db smoke Row Count is Equal to X SELECT id FROM person; 2 Verify Row Count is Less Than X - [Tags] db smoke Row Count is Less Than X SELECT id FROM person; 3 Verify Row Count is Greater Than X - [Tags] db smoke Row Count is Greater Than X SELECT * FROM person; 1 Retrieve Row Count - [Tags] db smoke ${output} = Row Count SELECT id FROM person; Log ${output} Should Be Equal As Strings ${output} 2 Retrieve records from person table - [Tags] db smoke ${output} = Execute SQL String SELECT * FROM person; Log ${output} Should Be Equal As Strings ${output} None Verify person Description - [Tags] db smoke Comment Query db for table column descriptions @{queryResults} = Description SELECT * FROM person LIMIT 1; Log Many @{queryResults} @@ -92,7 +79,6 @@ Verify person Description Should Be Equal As Integers ${NumColumns} 3 Verify foobar Description - [Tags] db smoke Comment Query db for table column descriptions @{queryResults} = Description SELECT * FROM foobar LIMIT 1; Log Many @{queryResults} @@ -104,114 +90,97 @@ Verify foobar Description Should Be Equal As Integers ${NumColumns} 2 Verify Query - Row Count person table - [Tags] db smoke ${output} = Query SELECT COUNT(*) FROM person; Log ${output} Should Be Equal As Strings ${output} ((2,),) Verify Query - Row Count foobar table - [Tags] db smoke ${output} = Query SELECT COUNT(*) FROM foobar; Log ${output} Should Be Equal As Strings ${output} ((0,),) Verify Query - Get results as a list of dictionaries - [Tags] db smoke ${output} = Query SELECT * FROM person; \ True Log ${output} Should Be Equal As Strings ${output[0]['first_name']} Franz Allan Should Be Equal As Strings ${output[1]['first_name']} Jerry Verify Execute SQL String - Row Count person table - [Tags] db smoke ${output} = Execute SQL String SELECT COUNT(*) FROM person; Log ${output} Should Be Equal As Strings ${output} None Verify Execute SQL String - Row Count foobar table - [Tags] db smoke ${output} = Execute SQL String SELECT COUNT(*) FROM foobar; Log ${output} Should Be Equal As Strings ${output} None Insert Data Into Table foobar - [Tags] db smoke ${output} = Execute SQL String INSERT INTO foobar VALUES(1,'Jerry'); Log ${output} Should Be Equal As Strings ${output} None Verify Query - Row Count foobar table 1 row - [Tags] db smoke ${output} = Query SELECT COUNT(*) FROM foobar; Log ${output} Should Be Equal As Strings ${output} ((1,),) Verify Delete All Rows From Table - foobar - [Tags] db smoke Delete All Rows From Table foobar Comment Sleep 2s Verify Query - Row Count foobar table 0 row - [Tags] db smoke Row Count Is 0 SELECT * FROM foobar; Comment ${output} = Query SELECT COUNT(*) FROM foobar; Comment Log ${output} Comment Should Be Equal As Strings ${output} [(0,)] Begin first transaction - [Tags] db smoke ${output} = Execute SQL String SAVEPOINT first True Log ${output} Should Be Equal As Strings ${output} None Add person in first transaction - [Tags] db smoke ${output} = Execute SQL String INSERT INTO person VALUES(101,'Bilbo','Baggins'); True Log ${output} Should Be Equal As Strings ${output} None Verify person in first transaction - [Tags] db smoke Row Count is Equal to X SELECT * FROM person WHERE last_name = 'Baggins'; 1 True Begin second transaction - [Tags] db smoke ${output} = Execute SQL String SAVEPOINT second True Log ${output} Should Be Equal As Strings ${output} None Add person in second transaction - [Tags] db smoke ${output} = Execute SQL String INSERT INTO person VALUES(102,'Frodo','Baggins'); True Log ${output} Should Be Equal As Strings ${output} None Verify persons in first and second transactions - [Tags] db smoke Row Count is Equal to X SELECT * FROM person WHERE last_name = 'Baggins'; 2 True Rollback second transaction - [Tags] db smoke ${output} = Execute SQL String ROLLBACK TO SAVEPOINT second True Log ${output} Should Be Equal As Strings ${output} None Verify second transaction rollback - [Tags] db smoke Row Count is Equal to X SELECT * FROM person WHERE last_name = 'Baggins'; 1 True Rollback first transaction - [Tags] db smoke ${output} = Execute SQL String ROLLBACK TO SAVEPOINT first True Log ${output} Should Be Equal As Strings ${output} None Verify first transaction rollback - [Tags] db smoke Row Count is 0 SELECT * FROM person WHERE last_name = 'Baggins'; True Drop person and foobar tables - [Tags] db smoke ${output} = Execute SQL String DROP TABLE IF EXISTS person,foobar; Log ${output} Should Be Equal As Strings ${output} None + +Disconnect from all databases + Disconnect From All Databases diff --git a/test/PostgreSQL_DB_Tests.robot b/test/PostgreSQL_DB_Tests.robot index 89c293e..b25ee47 100644 --- a/test/PostgreSQL_DB_Tests.robot +++ b/test/PostgreSQL_DB_Tests.robot @@ -4,7 +4,7 @@ Suite Teardown Disconnect From Database Library DatabaseLibrary Library OperatingSystem Library Collections -Force Tags standard +Force Tags main db smoke *** Variables *** ${DBHost} localhost @@ -25,8 +25,8 @@ Create person table Should Be Equal As Strings ${output} None Execute SQL Script - Insert Data person table - Comment ${output} = Execute SQL Script ./${DBName}_insertData.sql - ${output} = Execute SQL Script ./my_db_test_insertData.sql + Comment ${output} = Execute SQL Script ./my_db_test_insertData.sql + ${output} = Execute SQL Script ${CURDIR}/my_db_test_insertData.sql Log ${output} Should Be Equal As Strings ${output} None @@ -67,7 +67,6 @@ Retrieve records from person table Should Be Equal As Strings ${output} None Verify person Description - [Tags] db smoke Comment Query db for table column descriptions @{queryResults} = Description SELECT * FROM person LIMIT 1; Log Many @{queryResults} @@ -81,7 +80,6 @@ Verify person Description Should Be Equal As Integers ${NumColumns} 3 Verify foobar Description - [Tags] db smoke Comment Query db for table column descriptions @{queryResults} = Description SELECT * FROM foobar LIMIT 1; Log Many @{queryResults} @@ -109,7 +107,6 @@ Verify Query - Row Count foobar table Should be equal as Integers ${val} 0 Verify Query - Get results as a list of dictionaries - [Tags] db smoke ${output} = Query SELECT * FROM person; \ True Log ${output} Should Be Equal As Strings ${output[0]['first_name']} Franz Allan @@ -152,3 +149,6 @@ Drop person and foobar tables ${output} = Execute SQL String DROP TABLE IF EXISTS person,foobar; Log ${output} Should Be Equal As Strings ${output} None + +Disconnect from all databases + Disconnect From All Databases diff --git a/test/SQLite3_DB_Tests.robot b/test/SQLite3_DB_Tests.robot index 3436a87..a966093 100644 --- a/test/SQLite3_DB_Tests.robot +++ b/test/SQLite3_DB_Tests.robot @@ -1,7 +1,7 @@ *** Settings *** Library DatabaseLibrary Library OperatingSystem -Force Tags standard +Force Tags main db smoke *** Variables *** ${DBName} my_db_test @@ -9,77 +9,62 @@ ${SQLITE3_DBName} ${DBName} *** Test Cases *** Remove old DB if exists - [Tags] db smoke - ${Status} ${value} = Run Keyword And Ignore Error File Should Not Exist ./${DBName}.db - Run Keyword If "${Status}" == "FAIL" Run Keyword And Ignore Error Remove File ./${DBName}.db - File Should Not Exist ./${DBName}.db + ${Status} ${value} = Run Keyword And Ignore Error File Should Not Exist ${CURDIR}/${DBName}.db + Run Keyword If "${Status}" == "FAIL" Run Keyword And Ignore Error Remove File ${CURDIR}/${DBName}.db + File Should Not Exist ${CURDIR}/${DBName}.db Comment Sleep 1s Connect to SQLiteDB - [Tags] db smoke Comment Connect To Database Using Custom Params sqlite3 database='path_to_dbfile\dbname.db' - Connect To Database Using Custom Params sqlite3 database="./${DBName}.db", isolation_level=None + Connect To Database Using Custom Params sqlite3 database="${CURDIR}/${DBName}.db", isolation_level=None Create person table - [Tags] db smoke ${output} = Execute SQL String CREATE TABLE person (id integer unique,first_name varchar,last_name varchar); Log ${output} Should Be Equal As Strings ${output} None Execute SQL Script - Insert Data person table - [Tags] db smoke - ${output} = Execute SQL Script ./${DBName}_insertData.sql + ${output} = Execute SQL Script ${CURDIR}/${DBName}_insertData.sql Log ${output} Should Be Equal As Strings ${output} None Execute SQL String - Create Table - [Tags] db smoke ${output} = Execute SQL String create table foobar (id integer primary key, firstname varchar unique) Log ${output} Should Be Equal As Strings ${output} None Check If Exists In DB - Franz Allan - [Tags] db smoke Check If Exists In Database SELECT id FROM person WHERE first_name = 'Franz Allan'; Check If Not Exists In DB - Joe - [Tags] db smoke Check If Not Exists In Database SELECT id FROM person WHERE first_name = 'Joe'; Table Must Exist - person - [Tags] db smoke Table Must Exist person Verify Row Count is 0 - [Tags] db smoke Row Count is 0 SELECT * FROM person WHERE first_name = 'NotHere'; Verify Row Count is Equal to X - [Tags] db smoke Row Count is Equal to X SELECT id FROM person; 2 Verify Row Count is Less Than X - [Tags] db smoke Row Count is Less Than X SELECT id FROM person; 3 Verify Row Count is Greater Than X - [Tags] db smoke Row Count is Greater Than X SELECT * FROM person; 1 Retrieve Row Count - [Tags] db smoke ${output} = Row Count SELECT id FROM person; Log ${output} Should Be Equal As Strings ${output} 2 Retrieve records from person table - [Tags] db smoke ${output} = Execute SQL String SELECT * FROM person; Log ${output} Should Be Equal As Strings ${output} None Verify person Description - [Tags] db smoke Comment Query db for table column descriptions @{queryResults} = Description SELECT * FROM person LIMIT 1; Log Many @{queryResults} @@ -93,7 +78,6 @@ Verify person Description Should Be Equal As Integers ${NumColumns} 3 Verify foobar Description - [Tags] db smoke Comment Query db for table column descriptions @{queryResults} = Description SELECT * FROM foobar LIMIT 1; Log Many @{queryResults} @@ -105,114 +89,97 @@ Verify foobar Description Should Be Equal As Integers ${NumColumns} 2 Verify Query - Row Count person table - [Tags] db smoke ${output} = Query SELECT COUNT(*) FROM person; Log ${output} Should Be Equal As Strings ${output} [(2,)] Verify Query - Row Count foobar table - [Tags] db smoke ${output} = Query SELECT COUNT(*) FROM foobar; Log ${output} Should Be Equal As Strings ${output} [(0,)] Verify Query - Get results as a list of dictionaries - [Tags] db smoke ${output} = Query SELECT * FROM person; \ True Log ${output} Should Be Equal As Strings ${output[0]['first_name']} Franz Allan Should Be Equal As Strings ${output[1]['first_name']} Jerry Verify Execute SQL String - Row Count person table - [Tags] db smoke ${output} = Execute SQL String SELECT COUNT(*) FROM person; Log ${output} Should Be Equal As Strings ${output} None Verify Execute SQL String - Row Count foobar table - [Tags] db smoke ${output} = Execute SQL String SELECT COUNT(*) FROM foobar; Log ${output} Should Be Equal As Strings ${output} None Insert Data Into Table foobar - [Tags] db smoke ${output} = Execute SQL String INSERT INTO foobar VALUES(1,'Jerry'); Log ${output} Should Be Equal As Strings ${output} None Verify Query - Row Count foobar table 1 row - [Tags] db smoke ${output} = Query SELECT COUNT(*) FROM foobar; Log ${output} Should Be Equal As Strings ${output} [(1,)] Verify Delete All Rows From Table - foobar - [Tags] db smoke Delete All Rows From Table foobar Comment Sleep 2s Verify Query - Row Count foobar table 0 row - [Tags] db smoke Row Count Is 0 SELECT * FROM foobar; Begin first transaction - [Tags] db smoke ${output} = Execute SQL String SAVEPOINT first True Log ${output} Should Be Equal As Strings ${output} None Add person in first transaction - [Tags] db smoke ${output} = Execute SQL String INSERT INTO person VALUES(101,'Bilbo','Baggins'); True Log ${output} Should Be Equal As Strings ${output} None Verify person in first transaction - [Tags] db smoke Row Count is Equal to X SELECT * FROM person WHERE last_name = 'Baggins'; 1 True Begin second transaction - [Tags] db smoke ${output} = Execute SQL String SAVEPOINT second True Log ${output} Should Be Equal As Strings ${output} None Add person in second transaction - [Tags] db smoke ${output} = Execute SQL String INSERT INTO person VALUES(102,'Frodo','Baggins'); True Log ${output} Should Be Equal As Strings ${output} None Verify persons in first and second transactions - [Tags] db smoke Row Count is Equal to X SELECT * FROM person WHERE last_name = 'Baggins'; 2 True Rollback second transaction - [Tags] db smoke ${output} = Execute SQL String ROLLBACK TO SAVEPOINT second True Log ${output} Should Be Equal As Strings ${output} None Verify second transaction rollback - [Tags] db smoke Row Count is Equal to X SELECT * FROM person WHERE last_name = 'Baggins'; 1 True Rollback first transaction - [Tags] db smoke ${output} = Execute SQL String ROLLBACK TO SAVEPOINT first True Log ${output} Should Be Equal As Strings ${output} None Verify first transaction rollback - [Tags] db smoke Row Count is 0 SELECT * FROM person WHERE last_name = 'Baggins'; True Drop person and foobar tables - [Tags] db smoke ${output} = Execute SQL String DROP TABLE IF EXISTS person; Log ${output} Should Be Equal As Strings ${output} None ${output} = Execute SQL String DROP TABLE IF EXISTS foobar; Log ${output} Should Be Equal As Strings ${output} None + +Disconnect from all databases + Disconnect From All Databases diff --git a/test/run_tests.sh b/test/run_tests.sh deleted file mode 100755 index 5b46ba8..0000000 --- a/test/run_tests.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -robot -V DB_Variables.yaml -i standard .