COURSE 2 – USING PYTHON TO INTERACT WITH THE OPERATING SYSTEM

Module 5: Testing in Python

GOOGLE IT AUTOMATION WITH PYTHON PROFESSIONAL CERTIFICATE

Complete Coursera Study Guide

Last updated:

INTRODUCTION – Testing in Python

In this module, you’ll learn how to create tests in Python. We’ll cover what testing is all about and dive into the differences between manual versus automated testing. Next, we’ll explore what unit tests are intended to do and how to write them. Then, we’ll learn about other test concepts like black box versus white box tests and how test-driven development can frame how you design and write your code. Finally, you’ll learn about errors and exceptions, and how to combat them.

Learning Objectives

  • Explain what testing is and the different types of testing available
  • Describe the difference between black box and white box testing
  • Explain test-driven development
  • Apply a try-except construct to catch errors and exceptions

PRACTICE QUIZ: SIMPLE TESTS

1. You can verify that software code behaves correctly using test ___.

  • Loops
  • Arguments
  • Cases (CORRECT)
  • Functions

Awesome! The software code should behave the way you expect with as many possible values or test cases.

2. What is the most basic way of testing a script?

  • Codifying tests into the software.
  • Different parameters with expected results. (CORRECT)
  • Let a bug slip through.
  • Write code to do the tests.

Right on! The most basic way of testing a script is to use different parameters and get the expected results.

3. When a test is codified into its own software, what kind of test is it?

  • Unit test
  • Integration test
  • Automatic test (CORRECT)
  • Sanity testing

Nice job!  Codifying tests into its own software and code that can be run to verify that our programs do what we expect them to do is automatic testing.

4. Using _____ simplifies the testing process, allowing us to verify the program’s behavior repeatedly with many possible values.

  • integration tests
  • test cases (CORRECT)
  • test-driven development
  • interpreter

Great work! Test cases automatically test with a range of possible values to verify the program’s behavior.

5. The more complex our code becomes, the more value the use of _____ provides in managing errors.

  • loops
  • functions
  • parameters
  • software testing (CORRECT)

Awesome! Software testing is the process of evaluating computer code to determine whether or not it does what you expect it to do, and the more complex the code, the more likely failure is.

6. When you test software, what are you really looking for?

  • Loops
  • Conditionals
  • Modules
  • Defects (CORRECT)

Right on! You want to find errors and defects when testing software.

7. The advantage of running automated tests is that they will always get the same expected ___ if the software code is good.

  • Command line arguments
  • Interpreters
  • Results (CORRECT)
  • Parameters

Way to go! Automatic tests will always get the same expected result if the software code is good.

PRACTICE QUIZ: OTHER TEST CONCEPTS

1. In what type of test is the code not transparent?

  • White-box test
  • Black-box test (CORRECT)
  • Smoke test
  • Test-driven development

Nice work! This type of test relies on the tester having no knowledge of the code.

2. Verifying an automation script works well with the overall system and external entities describes what type of test?

  • Integration test (CORRECT)
  • Load test
  • Regression test
  • Smoke test

Great job! This test verifies that the different parts of the overall system interact as expected.

3. _____ ensures that any success or failure of a unit test is caused by the behavior of the unit in question, and doesn’t result from some external factor.

  • Regression testing
  • Integration
  • Isolation (CORRECT)
  • White-box testing

Right on! By ensuring the unit of code we are testing is isolated, we can ensure we know where the bug originated.

4. A test that is written after a bug has been identified in order to ensure the bug doesn’t show up again later is called _____

  • Load test
  • Black-box test
  • Smoke test
  • Regression test (CORRECT)

Excellent! Regression testing is a type of software test used to confirm that a recent program or code change has not adversely affected existing features, by re-executing a full or partial selection test cases.

5. What type of software testing is used to verify the software’s ability to behave well under significantly stressed testing conditions?

  • Load test (CORRECT)
  • Black-box test
  • Smoke test
  • Regression test

Way to go! Load testing verifies the behavior of the software remains consistent under conditions of significant load.

6. An important characteristic of a unit test is ___.

  • A production environment
  • Isolation. (CORRECT)
  • An external database
  • Automation.

Nice job! Unit tests test the piece of code they target.

7. What module can you load to use a bunch of testing methods for your unit tests?

  • unittest
  • Test
  • assertEqual
  • TestCase (CORRECT)

Nice job! This module provides a TestCase class with a bunch of testing methods.

8. Which of the following is NOT an advantage of running an automatic unit test in a suite for a single function?

  • Efficiency
  • Reusable test cases
  • Creating one script for multiple test cases
  • Creating multiple test scripts (CORRECT)

Nicely done! It’s harder to manage multiple test scripts.

9. Which of the following is descriptive of a black-box test case?

  • Code is opaque. (CORRECT)
  • The code is open-source.
  • Tests are created alongside the code development.
  • The tester is familiar with the code.

You got it! Black-box tests have no knowledge of the code.

10. Running a piece of software code as-is to see if it runs describes what type of testing?

  • Smoke test (CORRECT)
  • Load test
  • Regression test
  • Integration test

Keep it up! This test finds out if the program can run in its basic form before undergoing more refined test cases.

11. Which of the following is NOT an advantage of test-driven development (TDD)?

  • A problem is well thought out
  • Faster development of code (CORRECT)
  • Test cases written before writing code
  • Test while you develop code

Nailed it! Testing while developing code may increase the code completion time.

IMPLEMENT UNIT TESTING

1. What is the cause of an IndexError?

  • Attempting to index a list with invalid parameters.
  • Attempting to access an index that’s outside the bounds of a list. (CORRECT)
  • Not specifying classes.
  • Searching a list that contains errors.

Correct

2. The function find_emails(argv) searches a dictionary using the employee’s first and last name, and then returns the matching email address. How does the script accept the input of the employee’s name? 

  • The script accepts the employee’s first name and last name as tests. 
  • The script accepts the employee’s first name and last name as dictionaries. 
  • The script accepts the employee’s first name and last name as usernames.
  • The script accepts the employee’s first name and last name as command-line arguments. (CORRECT)

Correct

3. When you began working with the existing emails.py script, what mode did you need to open it in? 

  • Edit mode (CORRECT)
  • Script mode
  • Automation mode
  • Test mode

Correct

4. Which of the following statements accurately describes how try/except blocks work? Select all that apply.

  • If no exceptions occur, the try clause is ignored.
  • If an exception occurs during the execution of the try clause, the rest of the try clause is then skipped. (CORRECT)
  • The try clause is executed. (CORRECT)
  • If an exception occurs during the execution of the try clause, the try clause is executed and ignored.

Correct

5. When referring to unit testing, what is a “test runner”?

  • A test runner automatically determines the type of clause you will need to solve an issue.
  • A test runner allows a Python file to access scripts from another Python file.
  • A test runner automatically determines the type of loop you will need to solve an issue. 
  • A test runner is a component that orchestrates the execution of tests and provides an outcome. (CORRECT)

Correct

6. The following code will either return an email address for an employee or an error message if there is no employee matching the name entered. What would the error message be?

if email_dict.get(fullname.lower()):
    return email_dict.get(fullname.lower())
else:
    return "No email"
  • “Missing parameters”
  • “No email address found”
  •  “No employee found” 
  • “No email” (CORRECT)

Correct

7. The following import statement allows a Python file to access the script from another Python file. What exactly will this statement cause to be imported? 

from emails import find_email

  • It imports the function emails.py, which is defined in the script find_email.
  • It imports the function find_email, which is defined in the script emails.py. (CORRECT)
  • It imports the emails listed in the script find_email.
  • It imports the script find_email, which is defined in the function emails.py.

Correct

8. When a try block is not able to execute a function, which of the following return examples will an exception block most likely NOT return?

  • Zero
  • Empty String
  • Error (CORRECT)
  • Empty List

Awesome! An exception is not meant to produce an error, but to bypass it.

9. What keyword can help provide a reason an error has occurred in a function?

  • minlen
  • raise
  • return
  • assert (CORRECT)

Right on! This keyword is used to produce a message when a conditional is false.

10. When using the assertRaises method, what is passed first?

  • Function name
  • Error (CORRECT)
  • Parameters
  • Conditional

Way to go! The expected error is passed first.

11. Which command did you use to view the contents of the user_emails.csv file? 

  • ls user_emails.csv
  • nano ~/scripts/emails_test.py 
  • cd ~/scripts
  • cat user_emails.csv (CORRECT)

Correct

12. If a try clause is executed and an exception occurs, but there is no match for the exception in any of the except clauses, what happens?

  • It’s an unhandled exception and the execution stops with an error message. (CORRECT)
  • The parameters are automatically adjusted.
  • The try clause will be executed again.
  • The except clauses will be automatically updated.

Correct

13. Before software can ship, you have been asked to test the software. What specifically should you be testing for? 

  • To find all possible bugs
  • To identify unnecessary features
  • To prove the software works correctly
  • To make sure the software meets the specified requirements (CORRECT)

Correct

14. When searching for an employee, the method email_dict.get(username) should return a valid email address unless the searched employee doesn’t exist. To return a message like, “No email address found” for a non-existent employee, what type of loop will do the job? 

  • A unittesting loop
  • An if-else loop (CORRECT)
  • A try/except loop
  • An edge case loop

Correct

15. What is the following code an example of?

if email_dict.get(fullname.lower()):
    return email_dict.get(fullname.lower())
else:
    return "No email address found"
  • A try/except loop
  • An if-else loop (CORRECT)
  • An email search
  • A try/except clause

Correct

16. When testing a working script with a known bug, what should be the overall order of your approach? 

  • Review the script, make obvious corrections, try to reproduce the bug.
  • Verify all the tests, make necessary corrections, try to reproduce the bug. 
  • Rewrite the script, test for bugs, use this to replace the existing script.
  • Reproduce the bug, make necessary corrections, and verify that all the tests pass. (CORRECT)

Correct

17. The following portion of code will return an error message if a user fails to enter the full name of the employee for a search. What will the error message be?

def find_email(argv):
 """ Return an email address based on the username given."""
 # Create the username based on the command line input.
 try:
   fullname = str(argv[1] + " " + argv[2])
   # Preprocess the data
   email_dict = populate_dictionary('/home/<username>/data/user_emails.csv')
   # Find and print the email
   return email_dict.get(fullname.lower())
 except IndexError:
   return "Missing name"
  • “Missing username”
  • “IndexError”
  • “No email address found”
  • “Missing name” (CORRECT)

Correct

18. When writing a try/except clause, how many except clauses can be included? 

  • As many as needed as long as there is one try clause per except clause. 
  • One more except clauses than there are specific handlers for different exceptions.
  • As many except clauses are needed to specify handlers for different exceptions. (CORRECT)
  • Only one.

Correct

19. When you looked for the script emails.py in the scripts directory, what command did you use to navigate to the scripts directory? 

  • ls user_emails.csv
  • nano ~/scripts/emails_test.py 
  • cd ~/scripts (CORRECT)
  • cat emails.py

Correct

20. There are plenty of practical reasons for writing a test case for a script. From a developer’s perspective, what is a good reason to write test cases for your scripts? 

  • Writing a test enables developers to write longer code. 
  • Scripts will work on updated platforms as long as tests are used. 
  • Writing a test makes developers examine the script’s design, leading you to create better scripts in the future.  (CORRECT)
  • Writing a test ensures a developer’s code will be bug free. .

Correct

21. When testing a working script with a known bug, what is the first step in the testing process? 

  • Use the software so that it works correctly
  • Create a list of features that are unnecessary. 
  • Reproduce the bug.  (CORRECT)
  • Find all bugs in the software.

Correct

22. In the Implementing Unit Testing lab, you navigated to a data directory and a scripts directory. What did the commands to navigate to these directories begin with?

  • ls
  • cd ~/ (CORRECT)
  • nano ~/scripts/emails_test.py 
  • cat

Correct

23. Your first test case was for missing parameters. What methods could you use to solve this issue? Select all that apply.

  • Pass random names that aren’t present in user_emails.csv and check the output. . 
  • Use a try/except clause to handle IndexError. (CORRECT)
  • Check the length of input parameters before traversing the user_emails.csv file for the email address. (CORRECT)
  • Add an if-else loop.

Correct

24. What is the purpose of software testing? 

  • To identify the features that are not needed
  • To find all bugs in the software so they can be repaired.
  • To prove that the software works correctly
  • To determine whether the software meets the specified requirements (CORRECT)

Correct

25. Why is it important to perform regression testing?

  • To check software performance
  • To check software usability
  • To validate the software meets all the specified requirements
  • To verify new code changes did not adversely affect functionality (CORRECT)

Correct

26. Which of the following code blocks is an if-else loop which will return a valid email address or inform a user “No email address found”?

if email_dict.get(fullname.lower()):
    return email_dict.get(fullname.lower())
then:
    return "No email address found"
if email_dict.get(fullname.lower()):
    return email_dict.get(fullname.lower())
else:
    return "Invalid search"
if email_dict.get(fullname.lower()):
    return email_dict.get(fullname.lower())
else:
    return "No email address found" (CORRECT)
when email_dict.get(fullname.lower()):
    return email_dict.get(fullname.lower())
else:
    return "No email address found"

Correct

27. In the lab, you imported the unittest package, which you used to write test cases that correct bugs in the emails.py script. Which of the following does the unittest package support? 

  • User_emails.csv, emails.py, and emails_test.py.
  • Import statements, class definitions, and csv files.
  • Test automation, sharing setup and shutdown code for tests, and aggregation of tests into collections. (CORRECT)
  • Step by step instructions, data, and functionality.

Correct

CONCLUSION – Testing in Python

To sum up, this module equips you with the essential capabilities for crafting Python tests. It encompasses a comprehensive exploration of testing fundamentals, a nuanced comparison between manual and automated testing approaches, a detailed examination of the significance and construction of unit tests, insights into vital concepts like black-box and white-box testing, and an initiation into the principles of test-driven development shaping your approach to code design. The module culminates with a dedicated focus on effectively managing errors and exceptions in your code.