Data should be rolled back in case of failed transactions.
Language: Java
Framework: JUnit using JDBC
1//Assuming the database name as "test_db" and table name as "test_table"2//Assuming the JDBC driver is added to the project's build path34import java.sql.Connection;5import java.sql.DriverManager;6import java.sql.SQLException;7import java.sql.Statement;8import java.sql.ResultSet;910import org.junit.After;11import org.junit.Assert;12import org.junit.Before;13import org.junit.Test;1415public class DatabaseTest {16 17 private static final String DB_URL = "jdbc:postgresql://localhost/test_db";18 private static final String DB_USER = "username";19 private static final String DB_PASS = "password";20 21 private Connection connection;22 private Statement statement;23 private ResultSet resultSet;24 25 @Before26 public void setUp() {27 try {28 //Connecting to the database29 connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);30 31 //Creating the test table32 statement = connection.createStatement();33 String createTableQuery = "CREATE TABLE test_table (id SERIAL PRIMARY KEY, name VARCHAR(255))";34 statement.executeUpdate(createTableQuery);35 }36 catch(SQLException e) {37 e.printStackTrace();38 }39 }40 41 @Test42 public void testRollbackData() {43 try {44 //Inserting sample data45 String insertQuery = "INSERT INTO test_table (name) VALUES ('John')";46 statement.executeUpdate(insertQuery);47 48 //Simulating a failed transaction49 String invalidInsertQuery = "INSERT INTO test_table (id, name) VALUES (1, 'Jane')";50 statement.executeUpdate(invalidInsertQuery);51 52 //Checking if data has been rolled back53 String selectQuery = "SELECT * FROM test_table";54 resultSet = statement.executeQuery(selectQuery);55 56 int rowCount = 0;57 while(resultSet.next()) {58 rowCount++;59 }60 61 //Asserting that only one row exists (i.e. the valid insert)62 Assert.assertEquals(1, rowCount);63 }64 catch(SQLException e) {65 e.printStackTrace();66 }67 }68 69 @After70 public void tearDown() {71 try {72 //Dropping the test table73 String dropTableQuery = "DROP TABLE test_table";74 statement.executeUpdate(dropTableQuery);75 76 //Closing the database connection77 connection.close();78 }79 catch(SQLException e) {80 e.printStackTrace();81 }82 }83 84 85 /*86 * Uncomment and update the desired capabilities to connect to remote client87 *88 @Before89 public void setUpRemote() {90 Caps caps = new Caps();91 caps.setCapability("platformName", "ANDROID");92 caps.setCapability("deviceName", "pixels");93 94 try {95 //Connecting to the remote client96 RemoteWebDriver driver = new RemoteWebDriver(new URL("<remote_server_url>"), caps);97 98 //TODO: Add test logic99 100 //Closing the driver101 driver.quit();102 }103 catch(MalformedURLException e) {104 e.printStackTrace();105 }106 }107 */108 109}110111//Note: This code uses JUnit and JDBC to test the rollback functionality of the database. It assumes a PostgreSQL database named "test_db" and a table named "test_table". It creates the table before running the test and drops it after the test. The test case inserts an invalid row and checks if it has been rolled back. The test code also includes commented code to connect to a remote client using desired capabilities.
Language: Python
Framework: Pytest
1import pytest2import psycopg234#Assuming that database credentials are stored in Environment Variables5DB_HOST = os.environ['DB_HOST']6DB_NAME = os.environ['DB_NAME']7DB_USER = os.environ['DB_USER']8DB_PASSWORD = os.environ['DB_PASSWORD']910@pytest.fixture(scope='function')11def db_connection():12 #Assuming that we are using PostgreSQL Database13 conn = psycopg2.connect(14 host=DB_HOST,15 dbname=DB_NAME,16 user=DB_USER,17 password=DB_PASSWORD18 )19 yield conn20 conn.close()2122def test_data_rollback(db_connection):23 cursor = db_connection.cursor()24 try:25 #Assuming that the table 'users' has an 'id' column which is set to auto-increment26 cursor.execute("INSERT INTO users (name) VALUES ('John')")27 cursor.execute("INSERT INTO users (name) VALUES ('Mary')")28 #Assuming that we will intentionally cause an error to test the rollback29 cursor.execute("INSERT INTO users (name) VALUES ('Kate', 'Doe')")30 except Exception as e:31 #Assuming that an error will be raised due to the invalid number of columns in the query32 assert 'invalid input syntax for type integer' in str(e)33 db_connection.rollback() #Rollback the transaction on failure34 finally:35 cursor.execute("SELECT COUNT(*) FROM users")36 result = cursor.fetchone()37 assert result[0] == 2 #Two users should be inserted in the table38 39#Assuming that we connect to a remote client with the following desired capabilities40REMOTE_HOST = os.environ['REMOTE_HOST']41REMOTE_PORT = os.environ['REMOTE_PORT']42BROWSER_NAME = os.environ['BROWSER_NAME']43BROWSER_VERSION = os.environ['BROWSER_VERSION']4445from selenium.webdriver import DesiredCapabilities, Remote4647def test_data_rollback_remote():48 desired_capabilities = DesiredCapabilities.{BROWSER_NAME.upper()}49 desired_capabilities['version'] = BROWSER_VERSION5051 driver = Remote(52 command_executor=f'http://{REMOTE_HOST}:{REMOTE_PORT}/wd/hub',53 desired_capabilities=desired_capabilities54 )5556 #Test code for remote client will differ based on the application and environment.
Disclaimer: Following code snippets and related information have been sourced from GitHub and/or generated using AI code generation tools. LambdaTest takes no responsibility in the accuracy of the code and is not liable for any damages.
Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.
Test Intelligently and ship faster. Deliver unparalleled digital experiences for real world enterprises.
Start Free Testing