Static and Code Analysis

Loading concept...

Test Design Techniques: Static and Code Analysis πŸ”

The Story of the Bug Detective Agency πŸ•΅οΈ

Imagine you run a Bug Detective Agency. Your job? Find problems in buildings before people move in. You have two ways to work:

  1. Walk around and look (without touching anything) β€” this is Static Testing
  2. Actually live in the house and use everything β€” this is Dynamic Testing

Both are super important! Let’s explore how testers become the best bug detectives in the software world.


🏠 Static Testing Overview

What Is Static Testing?

Think of it like reading a recipe before cooking. You don’t turn on the stove yet. You just read and check:

  • β€œWait, it says add 10 cups of salt. That’s way too much!”
  • β€œHmm, step 3 comes before step 2. That’s wrong!”

Static testing = Finding bugs WITHOUT running the code.

graph TD A[πŸ“„ Code Written] --> B[πŸ‘€ Review & Inspect] B --> C{Found Bugs?} C -->|Yes| D[πŸ”§ Fix Now] C -->|No| E[βœ… Ready for Next Step] D --> B

Why Is Static Testing Awesome?

Benefit Why It Matters
πŸš€ Fast Find bugs before running anything
πŸ’° Cheap Fixing early costs less
🎯 Catches logic errors Spots wrong thinking
πŸ“š Improves understanding Everyone learns the code

Simple Example

Bad Code (spotted statically):

def divide(a, b):
    return a / b  # What if b is 0?

A reviewer reads this and says: β€œHey, what happens if someone passes 0 for b? It will crash!”

Fixed:

def divide(a, b):
    if b == 0:
        return "Cannot divide by zero!"
    return a / b

No code was run. The bug was found just by reading!


πŸƒ Dynamic Testing

What Is Dynamic Testing?

Now you actually cook the recipe. Turn on the stove. Mix ingredients. Taste the food!

Dynamic testing = Running the code and checking if it works correctly.

graph TD A[πŸš€ Run the Program] --> B[πŸ“₯ Give It Input] B --> C[πŸ“€ Check Output] C --> D{Correct?} D -->|Yes| E[βœ… Test Passed] D -->|No| F[πŸ› Bug Found!]

Real-Life Example

You have a login page. Dynamic testing means:

  1. Type a username and password
  2. Click the login button
  3. See what happens
Test Case Input Expected Result Actual Result
Valid login user: β€œsam”, pass: β€œ1234” Welcome Sam! Welcome Sam! βœ…
Wrong password user: β€œsam”, pass: β€œwrong” Error message Error message βœ…
Empty fields user: β€œβ€, pass: β€œβ€ Please fill all fields Crashed! πŸ›

Static vs Dynamic: The Difference

Think of buying a used car:

Static Testing Dynamic Testing
πŸ‘€ Look at the car πŸš— Test drive the car
Read the manual Feel how it drives
Check for rust spots Hear if engine sounds weird
Look at oil color See if brakes work

You need BOTH! Looking finds some problems. Driving finds others.


πŸ”¬ Static Code Analysis

What Is Static Code Analysis?

Imagine you have a robot helper that reads your code and says:

  • β€œHey, you made a spelling mistake in this variable!”
  • β€œThis line will never run!”
  • β€œYou forgot to close the file!”

Static Code Analysis = Using tools to automatically scan code for problems.

graph TD A[πŸ“ Your Code] --> B[πŸ€– Analysis Tool] B --> C[πŸ“‹ Report] C --> D[⚠️ Warnings] C --> E[❌ Errors] C --> F[πŸ’‘ Suggestions]

What Do These Tools Find?

Problem Type Example Why It’s Bad
Unused variables x = 5 (never used) Wastes memory, confuses readers
Dead code Code after return Never runs, misleading
Security issues Using eval() Hackers can attack
Style problems Inconsistent spacing Hard to read

Popular Static Analysis Tools

Language Tool What It Catches
Python PyLint, Flake8 Style, errors, complexity
JavaScript ESLint Bugs, bad practices
Java SonarQube Security, bugs, smells
C/C++ Cppcheck Memory leaks, bugs

Simple Example

Code with issues:

function greet(name) {
    var unused = 42;
    console.log("Hello " + nme);
    return;
    console.log("Goodbye");
}

Static analyzer output:

Line 2: 'unused' is declared but never used
Line 3: 'nme' is not defined (did you mean 'name'?)
Line 5: Unreachable code after return

You haven’t run the code, but the tool found 3 bugs!


πŸ‘₯ Code Review Techniques

What Is Code Review?

Remember group projects at school? Before submitting, your friend reads your work and says:

  • β€œThis sentence doesn’t make sense.”
  • β€œYou repeated this paragraph twice.”
  • β€œThis answer is wrong!”

Code Review = Team members read each other’s code to find problems and share knowledge.

graph TD A[πŸ‘¨β€πŸ’» Developer Writes Code] --> B[πŸ“€ Submits for Review] B --> C[πŸ‘€ Reviewer Reads Code] C --> D{Approved?} D -->|No| E[πŸ’¬ Comments & Suggestions] E --> F[πŸ”§ Developer Fixes] F --> B D -->|Yes| G[βœ… Code Merged]

Types of Code Review

Type How It Works Best For
Pair Programming Two people code together Learning, complex problems
Over-the-Shoulder Reviewer watches coder Quick informal checks
Tool-Based (Pull Request) Review on GitHub/GitLab Remote teams, async work
Formal Inspection Scheduled meetings, checklists Critical systems

What Reviewers Look For

  1. Correctness β€” Does it work right?
  2. Readability β€” Can others understand it?
  3. Efficiency β€” Is it fast enough?
  4. Security β€” Is it safe from hackers?
  5. Standards β€” Does it follow team rules?

Example Code Review Comment

Original code:

def calc(x, y, z):
    return x + y * z

Reviewer comments:

πŸ’¬ β€œWhat do x, y, and z represent? Please use meaningful names like base, rate, hours. Also, should multiplication happen before addition? Add parentheses to make it clear: base + (rate * hours)”

Improved code:

def calculate_pay(base, rate, hours):
    return base + (rate * hours)

Code Review Checklist Example

  • [ ] Does the code do what it’s supposed to?
  • [ ] Are variable names clear?
  • [ ] Are there any bugs I can spot?
  • [ ] Is there duplicate code that could be simplified?
  • [ ] Are error cases handled?
  • [ ] Is it easy to read and understand?

🧬 Mutation Testing

What Is Mutation Testing?

Here’s a fun story! Imagine you have a guard dog. You want to know: Is this dog actually good at catching burglars?

So you send fake burglars! If the dog catches them, it’s a good dog. If fake burglars sneak past, your dog needs training.

Mutation Testing = Making tiny changes to your code (mutations) to see if your tests catch them.

graph TD A[πŸ“ Original Code] --> B[🧬 Create Mutants] B --> C[πŸ‘Ύ Mutant 1] B --> D[πŸ‘Ύ Mutant 2] B --> E[πŸ‘Ύ Mutant 3] C --> F[πŸ§ͺ Run Tests] D --> F E --> F F --> G{Test Failed?} G -->|Yes| H[βœ… Mutant Killed - Good Test!] G -->|No| I[😱 Mutant Survived - Weak Test!]

How Mutation Testing Works

Step 1: Start with working code and a test

# Original code
def is_adult(age):
    return age >= 18

# Test
def test_is_adult():
    assert is_adult(20) == True

Step 2: Create mutants (tiny changes)

Mutant Change Made New Code
Mutant 1 Change >= to > return age > 18
Mutant 2 Change >= to <= return age <= 18
Mutant 3 Change 18 to 17 return age >= 17

Step 3: Run tests against each mutant

Mutant Test Result Verdict
Mutant 1 is_adult(20) still returns True 😱 SURVIVED!
Mutant 2 is_adult(20) returns False, test fails βœ… KILLED!
Mutant 3 is_adult(20) still returns True 😱 SURVIVED!

Problem found! Two mutants survived. Our test isn’t good enough!

Better test:

def test_is_adult():
    assert is_adult(20) == True
    assert is_adult(18) == True  # Boundary!
    assert is_adult(17) == False # Below boundary!

Now all mutants would be killed!

Mutation Score

Mutation Score = (Killed Mutants / Total Mutants) Γ— 100%

Score Meaning
100% Perfect! All mutants caught
80%+ Good test suite
60-80% Needs improvement
Below 60% Tests are too weak

Common Mutation Types

Mutation Type Original Mutated
Arithmetic a + b a - b
Relational x > y x >= y
Logical a && b a || b
Constant return 0 return 1
Negation if (x) if (!x)

🎯 Bringing It All Together

Here’s how all these techniques work together in the real world:

graph TD A[πŸ‘¨β€πŸ’» Developer Writes Code] --> B[πŸ€– Static Analysis] B --> C[πŸ‘₯ Code Review] C --> D[πŸ§ͺ Write Tests] D --> E[πŸƒ Dynamic Testing] E --> F[🧬 Mutation Testing] F --> G{All Good?} G -->|Yes| H[πŸš€ Deploy!] G -->|No| A

Quick Comparison

Technique When Who/What Finds
Static Testing Before running Humans reading Logic errors, design flaws
Dynamic Testing While running Running the code Runtime bugs, crashes
Static Code Analysis Anytime Automated tools Style, security, common bugs
Code Review Before merging Team members All kinds of issues
Mutation Testing After writing tests Special tools Weak tests

🌟 Key Takeaways

  1. Static Testing is like proofreading β€” find mistakes without running code
  2. Dynamic Testing is like test-driving β€” run the code and check it works
  3. Static Code Analysis uses robots to scan your code automatically
  4. Code Review is teamwork β€” humans checking each other’s work
  5. Mutation Testing tests your tests β€” makes sure your safety net has no holes

Remember: Great testers use ALL these tools! Like a detective using magnifying glass, fingerprint kit, AND asking witnesses. Each technique catches different types of bugs.

You’re now ready to be a Bug Detective! Go find those bugs before users do! πŸŽ‰

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.