Module 5: Testing in Python

Spread the love

INTRODUCTION – Testing in Python

During this session, you will learn the A to Z of Python testing, beginning with testing principles, and exploring unique approaches to testing, such as manual and automation. Such knowledge will be of great assistance in generating an understanding of the test process.

The next level of learning will be its specifics, which include unit test writing techniques, and why do we need effective unit tests. Some basic testing like black box or white box testing will be discussed. Impact of test-driven development (TDD) on the architecture of and writing code will also be considered. Finally, learners will now discuss errors and exceptions handling strategies.

Learning Objectives:

  • What testing means and the types of testing conducted at the moment
  • Differentiating between black box and white box testing
  • Understanding the principles behind test-driven development (TDD)
  • Knowing how to work with exceptions and errors by using a try-except construct.

PRACTICE QUIZ: SIMPLE TESTS

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

  • Loops
  • Arguments
  • Cases (CORRECT)
  • Functions

Awesome! Software code should execute as expected for a wide spectrum of input values, which includes varying units of test cases to test it under very many different conditions. thorough testing exposes the program to, among other things, correct handling of different inputs also under edge cases. This is crucial because this way you get to know more about every possible bug that can be found in your code, thereby ensuring more reliable software and sound operation across all scenarios.

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 quickest way one could test a script was to take different parameters and find out if that brought forth any results that matched the expected output.

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! Automated testing is a system that includes some unique code and software programs. By having this in place, a set of instructions are given that allow verification of the state at the desired point in time.

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! Indeed, with that! Test cases are created for the automatic inspection of the program operation when testing it with plural numbers and handling different test cases for ensuring the proper positive working and performance of a code. Utilizing various possible values (where the range includes boundary conditions, special case scenarios, and invalid inputs), you can make sure that your program will work as required in any situation.

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

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

Awesome! Any computer code is subjected to software testing to determine whether it operates satisfactorily or not-Coding complexity- increases the possibility of failure.

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

Absolutely! Automated tests are almost completely reliable and consistent by virtue of their use, as long as the software code that surrounds them is well-written and stable. This is so because they help in making sure the software addresses the requirements of each system and does not throw up some unexpected surprises.

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! It is really important that the system perform exactly as planned so that all modular components work as a singular efficient entity.

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! One way debugging can be done is by putting the code into its own unit, after which one can find the smallest corner in which the bug originated and use the indicated information to squash the bug.

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 may be termed as the process of executing an arrangement of test cases just to ensure that the most recent changes in the program or code have not caused damages to the tested features.

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

Implications would be that stability in performance is maintained and that the software can provide its expected behavior under heavy use or when using it in a heavy-traffic environment.

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)

That seems really like what you are doing with unit tests in Python! Come up to write the test case report using the Python code in the TestCase class, and how it has been written with the unittest module. It has the several methods available to evaluate its behavior, such as for instance assertEqual(), assertTrue(), assertFalse(), etc., to help you validate your work.

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.

Black box tests are conducted by not using the code knowing anything.

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! It is practically necessary when you will test if the basic form program runs before going into the detailed 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

Where in the code development programming process can tests prolong the overall time needed to finalize the code?

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)

In programming, the most probable keyword is else. Else expression is used inside conditional constructs like if statements to define a body of codes to be executed when the given value in the if statement should be 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

This module imparts training on setting the foundation right to write Python tests with essential skills. It covers introductory testing, contrasts manual and automated methods of testing, goes deep into the understanding of the presence and creation of unit tests. You are thrown some of the key concepts here, such as black-box and white-box testing, and a glimpse into test-driven development (TDD), which is an important concept to let you direct your coding towards well-structured code. The module is closed here with how errors and exceptions can be best managed and used in your code.

Leave a Comment