Bird
Raised Fist0
Testing Fundamentalstesting~15 mins

Why database testing ensures data integrity in Testing Fundamentals - Automation Benefits in Action

Choose your learning style10 modes available
Verify data integrity after inserting a new user record in the database
Preconditions (3)
Step 1: Connect to the test database
Step 2: Insert a new user record with username 'testuser' and email 'testuser@example.com'
Step 3: Query the user table to retrieve the record with username 'testuser'
Step 4: Verify that the retrieved record's email matches 'testuser@example.com'
Step 5: Delete the test user record to clean up
✅ Expected Result: The inserted user record is found with the correct email, confirming data integrity
Automation Requirements - pytest with psycopg2 for PostgreSQL
Assertions Needed:
Assert that the inserted record exists
Assert that the email field matches the inserted value
Best Practices:
Use setup and teardown methods to manage test data
Use parameterized queries to prevent SQL injection
Use assertions to verify data correctness
Close database connections properly
Automated Solution
Testing Fundamentals
import psycopg2
import pytest

class TestDatabaseIntegrity:
    @pytest.fixture(scope='class')
    def db_connection(self):
        conn = psycopg2.connect(
            dbname='testdb', user='testuser', password='testpass', host='localhost'
        )
        yield conn
        conn.close()

    def test_insert_and_verify_user(self, db_connection):
        cursor = db_connection.cursor()
        # Insert user record
        insert_query = """INSERT INTO users (username, email) VALUES (%s, %s) RETURNING id"""
        cursor.execute(insert_query, ('testuser', 'testuser@example.com'))
        user_id = cursor.fetchone()[0]
        db_connection.commit()

        # Query inserted record
        select_query = "SELECT email FROM users WHERE username = %s"
        cursor.execute(select_query, ('testuser',))
        result = cursor.fetchone()

        # Assert record exists and email matches
        assert result is not None, "User record not found"
        assert result[0] == 'testuser@example.com', f"Email mismatch: expected 'testuser@example.com', got {result[0]}"

        # Clean up
        delete_query = "DELETE FROM users WHERE id = %s"
        cursor.execute(delete_query, (user_id,))
        db_connection.commit()
        cursor.close()

This test connects to the test database using psycopg2. It inserts a user record with a specific username and email. Then it queries the database to retrieve the email for that username. Assertions check that the record exists and the email matches the inserted value, ensuring data integrity. Finally, it deletes the test record to keep the database clean. Using parameterized queries prevents SQL injection. The database connection is properly closed after tests.

Common Mistakes - 4 Pitfalls
Hardcoding SQL queries with string concatenation
Not cleaning up test data after test execution
Not closing database connections or cursors
Not asserting the query result before accessing it
Bonus Challenge

Now add data-driven testing with 3 different user records to verify data integrity for multiple inputs

Show Hint

Practice

(1/5)
1. Why is database testing important for ensuring data integrity?
easy
A. It verifies that data is accurate and consistent in the database.
B. It improves the speed of the database server.
C. It changes the database schema automatically.
D. It deletes duplicate data without user approval.

Solution

  1. Step 1: Understand the purpose of database testing

    Database testing checks if data stored is correct and consistent.
  2. Step 2: Identify the role of data integrity

    Data integrity means data is accurate and reliable over its lifecycle.
  3. Final Answer:

    It verifies that data is accurate and consistent in the database. -> Option A
  4. Quick Check:

    Data integrity = Accurate and consistent data [OK]
Hint: Data integrity means data is correct and consistent [OK]
Common Mistakes:
  • Confusing data integrity with performance
  • Thinking testing changes data automatically
  • Assuming testing deletes data
2. Which SQL query is best to check if a column has any NULL values to ensure data integrity?
easy
A. SELECT * FROM table WHERE column IS NULL;
B. SELECT * FROM table WHERE column = 0;
C. SELECT * FROM table WHERE column LIKE '%NULL%';
D. SELECT * FROM table WHERE column IS NOT NULL;

Solution

  1. Step 1: Identify how to find NULL values in SQL

    SQL uses 'IS NULL' to check for NULL values, not '=' or LIKE.
  2. Step 2: Match the correct query

    SELECT * FROM table WHERE column IS NULL; uses 'WHERE column IS NULL' which correctly finds NULLs.
  3. Final Answer:

    SELECT * FROM table WHERE column IS NULL; -> Option A
  4. Quick Check:

    Check NULL with IS NULL [OK]
Hint: Use IS NULL to find missing data in SQL [OK]
Common Mistakes:
  • Using '=' to check NULL values
  • Using LIKE to find NULLs
  • Confusing IS NULL with IS NOT NULL
3. Consider this SQL query to check data integrity:
SELECT COUNT(*) FROM users WHERE email = '' OR email IS NULL;

What does this query return?
medium
A. The number of users with valid email addresses.
B. The number of users missing an email address.
C. The total number of users in the database.
D. The number of users with duplicate emails.

Solution

  1. Step 1: Analyze the WHERE clause conditions

    The query counts rows where email is empty string or NULL, meaning missing emails.
  2. Step 2: Understand the COUNT(*) function

    COUNT(*) returns the number of rows matching the condition.
  3. Final Answer:

    The number of users missing an email address. -> Option B
  4. Quick Check:

    Empty or NULL emails counted = missing emails [OK]
Hint: Empty or NULL means missing data [OK]
Common Mistakes:
  • Thinking it counts valid emails
  • Confusing COUNT(*) with COUNT(column)
  • Assuming it finds duplicates
4. You wrote this SQL to check for duplicate user IDs:
SELECT user_id, COUNT(*) FROM users GROUP BY user_id;

Why might this query fail to find duplicates?
medium
A. COUNT(*) cannot be used with GROUP BY.
B. It uses GROUP BY incorrectly on user_id.
C. It should use WHERE instead of GROUP BY.
D. It does not filter groups having more than one record.

Solution

  1. Step 1: Understand GROUP BY with COUNT(*)

    The query groups rows by user_id and counts each group size.
  2. Step 2: Identify missing filter for duplicates

    Without filtering COUNT(*) > 1, it shows all groups, not just duplicates.
  3. Final Answer:

    It does not filter groups having more than one record. -> Option D
  4. Quick Check:

    Filter COUNT(*) > 1 to find duplicates [OK]
Hint: Add HAVING COUNT(*) > 1 to find duplicates [OK]
Common Mistakes:
  • Assuming GROUP BY alone finds duplicates
  • Thinking COUNT(*) is invalid with GROUP BY
  • Using WHERE instead of HAVING for group filters
5. A database tester wants to ensure no invalid dates are stored in the orders table's order_date column. Which approach best ensures data integrity?
hard
A. Ignore date checks because the application handles it.
B. Delete all records with dates older than one year without checking.
C. Run a query to find dates outside the allowed range and report errors.
D. Update all dates to the current date automatically.

Solution

  1. Step 1: Identify how to check invalid dates

    Querying for dates outside allowed range finds invalid data without changing it.
  2. Step 2: Understand importance of reporting errors

    Reporting errors helps fix data issues without data loss or wrong updates.
  3. Final Answer:

    Run a query to find dates outside the allowed range and report errors. -> Option C
  4. Quick Check:

    Find and report invalid data to keep integrity [OK]
Hint: Find errors first, don't delete or change data blindly [OK]
Common Mistakes:
  • Deleting data without validation
  • Trusting application without testing
  • Automatically changing data without review
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard