Module 1: Introduction to Git and Version Control for Testing

Understand why version control is critical for test automation projects. Learn the fundamental concepts of Git, set up your environment, and make your first commits with test scripts. Explore how Git solves common problems test engineers face: tracking changes in test cases, collaborating on automation frameworks, and maintaining test data.

The Three Git Areas: Managing Test Script Changes Like a Pro

Why This Matters

Imagine you’re working on an automated test suite with 50 test scripts. You’ve just spent two hours updating 10 of them to support a new application feature. Suddenly, you realize three of those changes broke unrelated tests. How do you commit only the good changes while fixing the broken ones? Or worse—how do you explain to your team lead exactly which test files you modified today?

This is where understanding Git’s three-area architecture becomes your superpower.

Real-World Problem This Solves:

As a test automation engineer, you face these challenges daily:

  • Selective commits: You need to commit stable test changes without including experimental or broken tests
  • Change verification: Before committing, you must review exactly what’s changed in your test scripts, page objects, or test data files
  • Incremental progress: You want to save logical chunks of work (like “added login tests” separate from “updated API assertions”)
  • Mistake recovery: You need to undo accidental changes to configuration files without losing your actual test improvements

When You’ll Use This Skill:

  • Every time you modify test automation code and want to save your progress
  • When collaborating with other test engineers and need to share only completed features
  • During code reviews, to present clean, logical commits of test changes
  • When troubleshooting which specific change caused a test to fail

Common Pain Points Addressed:

Without understanding Git’s three areas, test engineers often:

  • Commit everything at once, creating messy, hard-to-review changes
  • Accidentally commit sensitive test data, API keys, or temporary debugging files
  • Struggle to explain what they changed when tests break
  • Can’t easily revert specific changes without losing hours of work
  • Fear making experimental changes because they might “break” their repository

What You’ll Learn

This lesson demystifies Git’s three-area workflow—the foundation of all version control operations. By the end, you’ll confidently manage test script changes with precision and clarity.

Here’s How We’ll Cover Each Objective:

  1. Understanding the Three Areas: We’ll use visual diagrams and analogies to explain how Git’s working directory, staging area, and repository work together—think of it as organizing test scripts on your desk, a review folder, and a filing cabinet.

  2. Purpose of Each Area: You’ll learn why Git has three areas instead of two, and how this design specifically helps test engineers manage complex automation projects with multiple moving parts.

  3. Using git status: We’ll practice checking file states across all three areas—your radar for knowing exactly what’s changed, what’s staged, and what’s committed in your test suite.

  4. Using git add: Through hands-on examples with real test files (test scripts, configuration files, test data), you’ll learn to selectively stage changes and prepare perfect commits.

  5. Using git commit: You’ll master saving staged changes to your repository with meaningful commit messages that explain what test scenarios you added or why you refactored assertions.

  6. Visualizing File Movement: Interactive diagrams will show you how test files transition between areas, making the abstract concrete and building your mental model.

  7. Applying the Workflow: We’ll walk through complete real-world scenarios: creating new test cases, modifying existing ones, handling test data updates, and managing configuration changes—all using the three-area workflow.

By the end of this lesson, you’ll handle test automation changes with the confidence of a version control professional, making intentional, well-organized commits that your future self (and your teammates) will thank you for.


Core Content

Core Content: The Three Git Areas

Core Concepts Explained

Understanding the Three Git Areas

Git organizes your test automation code changes through three distinct areas. Think of it like a quality control pipeline for your test scripts:

graph LR
    A[Working Directory<br/>Your local files] -->|git add| B[Staging Area<br/>Changes ready to commit]
    B -->|git commit| C[Local Repository<br/>Permanent history]
    C -->|git push| D[Remote Repository<br/>Shared with team]

1. Working Directory (Modified Files)

This is where you actively write and edit your test scripts. Any changes you make to files exist only here until you tell Git to track them.

Example: You create a new Selenium test file login_test.py or modify an existing test. These changes exist only on your local machine.

2. Staging Area (Index)

The staging area is a preparation zone where you select which changes should be included in your next commit. This gives you fine-grained control over what gets saved to history.

Why it matters for test automation: You might fix a bug and add a new test simultaneously, but want to commit them separately for clearer history.

3. Local Repository (Committed History)

Once you commit staged changes, they become part of your project’s permanent history. Each commit is a snapshot of your test suite at that point in time.

Setting Up Git for Test Automation

Step 1: Install Git

# macOS (using Homebrew)
brew install git

# Ubuntu/Debian Linux
sudo apt-get update
sudo apt-get install git

# Windows (download installer from git-scm.com or use Chocolatey)
choco install git

Verify installation:

$ git --version
git version 2.40.0

Step 2: Configure Git

# Set your identity (appears in commit history)
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Set default branch name to 'main'
git config --global init.defaultBranch main

# Enable colorful output
git config --global color.ui auto

# Verify configuration
git config --list

Step 3: Initialize a Repository

# Create a new test automation project directory
mkdir selenium-tests
cd selenium-tests

# Initialize Git repository
git init

# Verify initialization
$ ls -la
drwxr-xr-x  3 user  staff   96 Jan 15 10:00 .git

The .git folder contains all Git metadata. Your working directory is now ready to track test scripts.

Practical Code Examples

Example 1: Creating and Tracking Your First Test Script

Step 1: Create a test file in the Working Directory

# test_login.py
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_valid_login():
    """Test successful login with valid credentials"""
    driver = webdriver.Chrome()
    driver.get("https://practiceautomatedtesting.com/login")
    
    # Enter credentials
    driver.find_element(By.ID, "username").send_keys("testuser")
    driver.find_element(By.ID, "password").send_keys("password123")
    driver.find_element(By.ID, "login-button").click()
    
    # Verify successful login
    assert "Dashboard" in driver.title
    driver.quit()

Step 2: Check the status

$ git status
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        test_login.py

nothing added to commit but untracked files present (use "git add" to track)

Step 3: Add to Staging Area

# Stage the specific file
git add test_login.py

$ git status
On branch main

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file:   test_login.py

Step 4: Commit to Local Repository

git commit -m "Add login test for valid credentials"

$ git log
commit a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0
Author: Your Name <your.email@example.com>
Date:   Mon Jan 15 10:30:00 2024 -0500

    Add login test for valid credentials

Example 2: Working with Multiple Changes

# test_login.py (modified - added new test)
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_valid_login():
    """Test successful login with valid credentials"""
    driver = webdriver.Chrome()
    driver.get("https://practiceautomatedtesting.com/login")
    
    driver.find_element(By.ID, "username").send_keys("testuser")
    driver.find_element(By.ID, "password").send_keys("password123")
    driver.find_element(By.ID, "login-button").click()
    
    assert "Dashboard" in driver.title
    driver.quit()

def test_invalid_login():
    """Test login failure with invalid credentials"""
    driver = webdriver.Chrome()
    driver.get("https://practiceautomatedtesting.com/login")
    
    driver.find_element(By.ID, "username").send_keys("wronguser")
    driver.find_element(By.ID, "password").send_keys("wrongpass")
    driver.find_element(By.ID, "login-button").click()
    
    # Verify error message appears
    error = driver.find_element(By.CLASS_NAME, "error-message")
    assert "Invalid credentials" in error.text
    driver.quit()
# test_registration.py (new file)
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_user_registration():
    """Test new user registration process"""
    driver = webdriver.Chrome()
    driver.get("https://practiceautomatedtesting.com/register")
    
    driver.find_element(By.ID, "email").send_keys("newuser@test.com")
    driver.find_element(By.ID, "password").send_keys("SecurePass123")
    driver.find_element(By.ID, "confirm-password").send_keys("SecurePass123")
    driver.find_element(By.ID, "register-button").click()
    
    assert "Welcome" in driver.page_source
    driver.quit()

Check status of multiple changes:

$ git status
On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   test_login.py

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        test_registration.py

no changes added to commit (use "git add" and/or "git commit -a")

Selective staging - commit tests separately:

# Stage only the modified login test
git add test_login.py
git commit -m "Add invalid login test case"

# Stage the registration test separately
git add test_registration.py
git commit -m "Add user registration test"

$ git log --oneline
b2c3d4e Add user registration test
a1b2c3d Add invalid login test case
9z8y7x6 Add login test for valid credentials

Example 3: Using .gitignore for Test Automation

Create a .gitignore file to exclude generated files:

# .gitignore
# Virtual environment
venv/
env/

# Test reports and screenshots
reports/
screenshots/
*.png
*.jpg

# Browser driver executables
chromedriver
geckodriver
*.exe

# Python compiled files
__pycache__/
*.pyc
*.pyo

# IDE settings
.vscode/
.idea/

# Test result files
test-results.xml
coverage.xml
# Add and commit the gitignore
git add .gitignore
git commit -m "Add gitignore for test automation project"

Example 4: Viewing and Understanding Changes

# See what changed in working directory (before staging)
$ git diff test_login.py

diff --git a/test_login.py b/test_login.py
--- a/test_login.py
+++ b/test_login.py
@@ -10,3 +10,14 @@ def test_valid_login():
     assert "Dashboard" in driver.title
     driver.quit()
 
+def test_invalid_login():
+    """Test login failure with invalid credentials"""
+    # New test function added

# See what's staged (after git add)
git diff --staged

# View commit history with details
git log --stat

Example 5: Unstaging and Discarding Changes

# Unstage a file (move from Staging back to Working Directory)
git restore --staged test_login.py

# Discard changes in Working Directory (careful - this is destructive!)
git restore test_login.py

# Remove untracked files (be careful!)
git clean -n  # Preview what would be deleted
git clean -f  # Actually delete untracked files

Common Mistakes Section

Mistake 1: Committing Without Reviewing Changes

Problem: Blindly using git add . can stage unwanted files (test reports, screenshots, credentials).

Solution:

# Instead of: git add .
# Use selective staging:
git add test_login.py test_registration.py

# Or use interactive mode:
git add -i

Mistake 2: Forgetting to Configure Git

Problem: Commits have incorrect author information.

# Check if configured
git config user.name
git config user.email

# If empty, configure before committing
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Mistake 3: Not Using .gitignore

Problem: Accidentally committing sensitive data or large files.

Debug:

# If you already committed sensitive data
git rm --cached config/credentials.py
echo "config/credentials.py" >> .gitignore
git add .gitignore
git commit -m "Remove credentials file from tracking"

Mistake 4: Confusing Working Directory and Staging

Problem: Making more changes after git add but before git commit.

Solution:

# Check what's staged vs what's modified
git status

# Stage all current changes
git add test_file.py

# Or just commit all tracked file changes
git commit -am "Update test file"

Mistake 5: Large Binary Files in Repository

Problem: Screenshots or videos make repository slow.

Debug:

# Check repository size
du -sh .git

# Find large files
git rev-list --objects --all | \
  git cat-file --batch-check='%(objectsize:disk) %(objectname) %(rest)' | \
  sort -rn | head -20

# Solution: Use .gitignore for test artifacts
echo "screenshots/" >> .gitignore
echo "videos/" >> .gitignore

Quick Reference: Git Status Interpretation

$ git status
On branch main
Changes to be committed:           # STAGING AREA (ready to commit)
  (use "git restore --staged <file>..." to unstage)
        modified:   test_login.py

Changes not staged for commit:     # WORKING DIRECTORY (modified, not staged)
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes)
        modified:   test_checkout.py

Untracked files:                   # WORKING DIRECTORY (new files)
  (use "git add <file>..." to include in what will be committed)
        test_payment.py

Hands-On Practice

EXERCISE

Hands-On Exercise: Version Control Your First Test Script

🎯 Objective

Practice moving files through Git’s three areas (Working Directory, Staging Area, Repository) while managing a test automation script.

📋 Task

You’ll create a simple test script, track its changes through Git’s three areas, make modifications, and learn to check the status at each stage.

📝 Step-by-Step Instructions

Part 1: Initial Setup

  1. Create a new project directory:

    mkdir test-automation-git
    cd test-automation-git
    
  2. Initialize a Git repository:

    git init
    
  3. Create your first test script file:

    touch login_test.py
    
  4. Check Git status:

    git status
    

    Expected output: File appears as “Untracked” (in Working Directory)

Part 2: Moving Through the Three Areas

  1. Add content to your test file:

    # login_test.py
    def test_login_valid_credentials():
        username = "testuser"
        password = "password123"
        # TODO: Add login logic
        pass
    
  2. Check status again:

    git status
    

    Question: Which area is the file in now?

  3. Add the file to the Staging Area:

    git add login_test.py
    
  4. Verify it’s staged:

    git status
    

    Expected output: File appears as “Changes to be committed” (green text)

  5. Commit to the Repository:

    git commit -m "Add initial login test structure"
    
  6. Confirm clean status:

    git status
    

    Expected output: “nothing to commit, working tree clean”

Part 3: Making Changes

  1. Modify the test file to add a new test:

    # login_test.py
    def test_login_valid_credentials():
        username = "testuser"
        password = "password123"
        # TODO: Add login logic
        pass
    
    def test_login_invalid_credentials():
        username = "testuser"
        password = "wrongpassword"
        # TODO: Add login logic
        pass
    
  2. Check what changed:

    git status
    git diff
    

    Expected output: Shows file as “modified” with red additions

  3. Stage and commit the changes:

    git add login_test.py
    git commit -m "Add invalid credentials test case"
    

Part 4: Working with Multiple Files

  1. Create a configuration file:

    echo "BASE_URL=https://example.com" > config.txt
    echo "TIMEOUT=30" >> config.txt
    
  2. Create a README file:

    echo "# Test Automation Project" > README.md
    
  3. Check status - you should see two untracked files:

    git status
    
  4. Stage only one file:

    git add config.txt
    git status
    

    Question: Where is config.txt? Where is README.md?

  5. Stage the remaining file and commit both:

    git add README.md
    git commit -m "Add configuration and documentation"
    
  6. View your commit history:

    git log --oneline
    

✅ Expected Outcomes

By the end of this exercise, you should have:

  • ✓ A Git repository with 3 commits
  • ✓ Three files: login_test.py, config.txt, and README.md
  • ✓ A clean working directory (nothing to commit)
  • ✓ Understanding of how files move through the three areas

🔍 Self-Check Questions

  1. What command moves files from Working Directory to Staging Area?
  2. What command moves files from Staging Area to Repository?
  3. If you modify a file after staging it, where are the changes located?
  4. How can you see which files are in the Staging Area?

CONCLUSION

🎓 Key Takeaways

  • The Three Git Areas work as a pipeline: Working Directory → Staging Area → Repository. Every file change must flow through these areas to be permanently saved.

  • git status is your best friend: Use it constantly to understand where your files are in the Git workflow. It shows untracked files (Working Directory), staged files (Staging Area), and confirms clean commits (Repository).

  • The Staging Area gives you control: You can selectively choose which changes to commit, allowing you to create logical, organized commit history even when working on multiple features.

  • Commits are snapshots, not differences: Each commit creates a complete snapshot of your staged files in the Repository, creating a time machine for your test automation code.

  • Files can exist in multiple areas simultaneously: A modified file can have some changes in the Repository, some in the Staging Area, and some in the Working Directory – understanding this prevents confusion.

🚀 Next Steps

What to Practice

  • Create a test automation project and make 10 commits, verifying the three areas after each change
  • Practice using git diff to see changes before staging
  • Experiment with git add . vs. adding individual files
  • Try modifying a file after staging it, then check git status and git diff --staged
  • Branching: Create separate branches for different test features
  • Undoing Changes: Learn git restore, git reset, and git revert
  • .gitignore: Exclude files like test reports and virtual environments
  • Remote Repositories: Push your test code to GitHub/GitLab
  • Git Hooks: Automate test runs before commits
  • Merge Conflicts: Handle conflicts when collaborating on test scripts

“Branching Strategies for Test Automation Teams” – Learn how to organize test development across features using Git branches.


Remember: Mastering Git’s three areas is foundational for professional test automation. Every change you track, every bug you catch, and every test you version starts with understanding these core concepts. Keep practicing! 🎯