How to Regression Test your SQL database
Building a Regression Testing Framework for your SQL Database
When it comes to testing software, there is a myriad of ways of doing it. Regression testing is one of those ways, and it is essentially a way to compare the output of two different versions of the software.
Comparing the output of two versions of the software will quickly highlight both the similarities and differences. If a change in the software caused an unexpected difference, it would promptly be highlighted. The same goes for when a difference was expected but not found.
As solutions grow in size and their output increases both in volume and complexity, a framework must be put in place to allow for this type of test to be carried out quickly and painlessly. Manual tests are prone to error and time-consuming.
The Idea
The idea then is very simple. Build a python script that allows us to compare two SQL databases quickly and effectively. The script needs to be extendable and as configurable as possible.
More specifically, the script should allow for a multi-environment setup and multi dataset comparison. In other words, the user should be able to set up their different environments and SQL commands to execute, and then with a couple of config changes have it run.
Without further ado then, let us jump into the details.
The Magic
Connecting to the SQL Server
Connecting to a SQL server is straightforward, but depending on the SQL server type, you will need to use a different library. For this example, I am using a Microsoft SQL server and consequently using the pyodbc library.
import pyodbc
import pandas as pd
Env1 = pyodbc.connect('Driver = {SQL Server}; Server = ServerName; Database = DatabaseName; Trusted_Connection = yes;')
SQL = 'SELECT * FROM Table1'
print(pd.read_sql_query(SQL, con = Env1)
import pyodbc
import pandas as pd
Env1 = pyodbc.connect('Driver = {SQL Server}; Server = ServerName; Database = DatabaseName; Trusted_Connection = yes;')
SQL = 'SELECT * FROM Table1'
print(pd.read_sql_query(SQL, con = Env1)
Comparing two data frames
There is no point reinventing the wheel here; we will use an existing library for comparing data sets.
import datacompy
import pandas as pd
df1 = pd.read_csv('FL_insurance_sample.csv')
df2 = pd.read_csv('FL_insurance_sample - Copy.csv')
compare = datacompy.Compare(
df1,
df2,
join_columns='policyID', #You can also specify a list of columns eg ['policyID','statecode']
abs_tol=0, #Optional, defaults to 0
rel_tol=0, #Optional, defaults to 0
df1_name='Original', #Optional, defaults to 'df1'
df2_name='New' #Optional, defaults to 'df2'
)
print(compare.report())
import datacompy
import pandas as pd
df1 = pd.read_csv('FL_insurance_sample.csv')
df2 = pd.read_csv('FL_insurance_sample - Copy.csv')
compare = datacompy.Compare(
df1,
df2,
join_columns='policyID', #You can also specify a list of columns eg ['policyID','statecode']
abs_tol=0, #Optional, defaults to 0
rel_tol=0, #Optional, defaults to 0
df1_name='Original', #Optional, defaults to 'df1'
df2_name='New' #Optional, defaults to 'df2'
)
print(compare.report())
Where it gets interesting
The interesting part of this exercise is bringing everything together. In essence, we need to create a list of SQL statements we want to execute as well as the result’s associated data key for the comparison.
Once that is defined, we can go through the SQL statement list, executing each one on both of our environments. Once we get the results back, using our comparison library, we can assess whether there are any differences. For efficiency purposes and reduce the data returned, we will first do a ‘dumb’ like for like comparison before attempting to get more granular feedback.
The Code
import pyodbc, datacompy
import pandas as pd
###############Set up your Environment connections#########################
Env1 = pyodbc.connect('Driver = {SQL Server}; Server = ServerName; Database = DatabaseName; Trusted_Connection = yes;')
Env2 = pyodbc.connect('Driver = {SQL Server}; Server = ServerName2; Database = DatabaseName2; Trusted_Connection = yes;')
########Environment Set Up###################################
Original = Env1
Target = Env2
######SQL Statements to Execute#############################
SQLStatement = [
#[ReportName, Stored Proc, [data keys]]
['Report1','EXEC StoredProc1 @Var1 = "Woop" , @Var2 = "Woop2"', ['Key1', 'Key2']],
['Report2','EXEC StoredProc2 @Var1 = "Woop", @Var2 = "Woop2"', ['Key3','Key4']]
]
###############################
def compareResults(reportName, df1, df2, joinOnKeys):
if df1.equals(df2) == True:
print('###########################################################')
print(reportName, 'Success')
else:
print('###########################################################')
print(reportName, 'Fail')
compare = datacompy.Compare(
df1,
df2,
join_columns= joinOnKeys,
abs_tol = 0,
rel_tol = 0,
df1_name= 'Original',
df2_name= 'Target'
)
print(compare.report(sample_count=20))
for i in SQLStatement:
results1 = pd.read_sql_query(i[1], con = Original)
results2 = pd.read_sql_query(i[1], con = Target)
compareResults(i[0], results1, results2, i[2])
import pyodbc, datacompy
import pandas as pd
###############Set up your Environment connections#########################
Env1 = pyodbc.connect('Driver = {SQL Server}; Server = ServerName; Database = DatabaseName; Trusted_Connection = yes;')
Env2 = pyodbc.connect('Driver = {SQL Server}; Server = ServerName2; Database = DatabaseName2; Trusted_Connection = yes;')
########Environment Set Up###################################
Original = Env1
Target = Env2
######SQL Statements to Execute#############################
SQLStatement = [
#[ReportName, Stored Proc, [data keys]]
['Report1','EXEC StoredProc1 @Var1 = "Woop" , @Var2 = "Woop2"', ['Key1', 'Key2']],
['Report2','EXEC StoredProc2 @Var1 = "Woop", @Var2 = "Woop2"', ['Key3','Key4']]
]
###############################
def compareResults(reportName, df1, df2, joinOnKeys):
if df1.equals(df2) == True:
print('###########################################################')
print(reportName, 'Success')
else:
print('###########################################################')
print(reportName, 'Fail')
compare = datacompy.Compare(
df1,
df2,
join_columns= joinOnKeys,
abs_tol = 0,
rel_tol = 0,
df1_name= 'Original',
df2_name= 'Target'
)
print(compare.report(sample_count=20))
for i in SQLStatement:
results1 = pd.read_sql_query(i[1], con = Original)
results2 = pd.read_sql_query(i[1], con = Target)
compareResults(i[0], results1, results2, i[2])
Example Output
###########################################################
Report1 Success
###########################################################
Report2 Fail
DataComPy Comparison
--------------------
DataFrame Summary
-----------------
DataFrame Columns Rows
0 Original 18 36634
1 New 18 36634Column Summary
--------------
Number of columns in common: 18
Number of columns in Original but not in New: 0
Number of columns in New but not in Original: 0
Row Summary
-----------
Matched on: policyid
Any duplicates on match values: No
Absolute Tolerance: 0
Relative Tolerance: 0
Number of rows in common: 36,634
Number of rows in Original but not in New: 0
Number of rows in New but not in Original: 0
Number of rows with some compared columns unequal: 2
Number of rows with all compared columns equal: 36,632
Column Comparison
-----------------
Number of columns compared with some values unequal: 2
Number of columns compared with all values equal: 16
Total number of values which compare unequal: 2
Columns with Unequal Values or Types
------------------------------------
Column Original dtype New dtype # Unequal Max Diff # Null Diff
0 eq_site_limit float64 float64 1 190601.40 0
1 hu_site_limit float64 float64 1 79375.76 0
Sample Rows with Unequal Values
-------------------------------
policyid eq_site_limit (Original) eq_site_limit (New)
2 206893 190724.4 123.0
policyid hu_site_limit (Original) hu_site_limit (New)
3 333743 79520.76 145.0
###########################################################
Report1 Success
###########################################################
Report2 Fail
DataComPy Comparison
--------------------
DataFrame Summary
-----------------
DataFrame Columns Rows
0 Original 18 36634
1 New 18 36634Column Summary
--------------
Number of columns in common: 18
Number of columns in Original but not in New: 0
Number of columns in New but not in Original: 0
Row Summary
-----------
Matched on: policyid
Any duplicates on match values: No
Absolute Tolerance: 0
Relative Tolerance: 0
Number of rows in common: 36,634
Number of rows in Original but not in New: 0
Number of rows in New but not in Original: 0
Number of rows with some compared columns unequal: 2
Number of rows with all compared columns equal: 36,632
Column Comparison
-----------------
Number of columns compared with some values unequal: 2
Number of columns compared with all values equal: 16
Total number of values which compare unequal: 2
Columns with Unequal Values or Types
------------------------------------
Column Original dtype New dtype # Unequal Max Diff # Null Diff
0 eq_site_limit float64 float64 1 190601.40 0
1 hu_site_limit float64 float64 1 79375.76 0
Sample Rows with Unequal Values
-------------------------------
policyid eq_site_limit (Original) eq_site_limit (New)
2 206893 190724.4 123.0
policyid hu_site_limit (Original) hu_site_limit (New)
3 333743 79520.76 145.0
Conclusion
There you have it folk! With less than 50 lines of code, you have a full SQL regression testing framework to help you ascertain the validity of your next release candidate.
All you need to do is choose the right two environments and define the list of stored procs that you would like executed.
Would you have done things differently or have a suggestion for improving this code? Let me know!
If you found this blogpost useful, you may also like:
Building a Python UI for Comparing Data
How to quickly enable your non-technical team to compare data
Automate UI Testing with PyAutoGUI in Python
A quick and easy way to regression test your UIs
From Excel and Pandas DataFrames to SQL
How to use your SQL knowledge to take advantage of Python’s Pandas

