Home>Article>Backend Development> Summary of Python basics

Summary of Python basics

巴扎黑
巴扎黑 Original
2017-07-17 15:56:28 1736browse

Testing code

When writing functions and classes, you can also write test functions. Through testing, you can confirm that the code can work normally in the face of various inputs. As you add new code to your program, you can also test it to make sure that they don't break the program's existing routines. Test modules frequently.

Test the code through the tools in the python module unittest. You will understand what it looks like to pass a test, what it looks like to fail, know how to improve the code if you know that the test fails, and know how many tests to write for the project. Know how to test functions and classes.

During the running of the program, various errors will always be encountered. Some errors are caused by problems in program writing. For example, a string should be output instead of an integer. This kind of error is usually called a bug, and bugs must be fixed.

Test function

Unit test and test case

The unittest module in Python provides code testing tools,Unit testis used to verify certain aspects of the function no problem.Test caseis a set of unit tests to ensure that the function has no problems in all aspects.

Full coverage test cases include a complete set of test cases, covering various possible ways of using functions.

Can pass the test

To write a test function for a function, first import the module unittest and the function to be tested, then create a class that inherits unittest.TestCase, and write a series of methods for the function Different aspects of behavior are tested. It is best to name it with test.

name_function.py

##def get_formatted_name(first, last):

""" Get the full name."""

full_name = first + ' ' + last

return full_name.title()

 names.py

##from name_function import get_formatted_name

print("Enter 'q' at any time to quit .")

while True:

first = input("\nPlease give me a first name: ")

if first == 'q':

break

last = input("Please give me a last name: ")

if last == 'q':

break

formatted_name = get_formatted_name(first, last)

print("\tNeatly formatted name: " + formatted_name + '.')

Test_name_function.py

##import unittest Failed tests
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase ):

"""Test name_function.py"""

def test_first_last_name(self): ? """

formatted_name = get_formatted_name('janis', 'joplin') self.assertEqual(formatted_name, 'Janis Joplin')

unittest.main()

One of the most useful functions of unittest: an assertion method. The assertEqual assertion method is used to verify whether the result obtained is the same as the expected value.
If the test fails, do not modify the test, but fix the code that caused the test to fail: check the modifications just made to the function to find out what caused the function to behave inconsistently Anticipated modifications.

Various assertion methods in the module

6 common assertions

##Methods

Purpose Verify a == b Verify a != b Verify that x is True ##assertFalse(x) Verify that x is False assertIn(item, list) Verify that item is in In list assertNotIn(item, list) Verify that item is not in list

##assertEqual(a, b)

assertNotEqual(a, b)

assertTrue(x)

Method setUp()

The unittest.TestCase class contains the method setUp(), which allows us to create objects only once and use them in every test method.

 survey.py

##class AnonymousSurvey():

"""Collect anonymous surveys Answers to the questionnaire"""

def __init__(self, question): """Store a question and prepare to store the answer"""

self. question = question

self.responses = []

def show_question(self):

"""Show Questionnaire""" print( question)

def store_response(self, new_response):

def show_results(self): responSes:

PRINT ('- + Response)

Language_survey.py

############################################## ###########from survey import AnonymousSurvey#######Define a question and create an AnonymousSurvey object representing the survey######question = "What language did you first learn to speak?"######my_survey = AnonymousSurvey(question)#######Show questions and store answers my_survey.show_question()######print("Enter 'q' at any time to quit .\n")######while True: ######response = input("Language: ") ######if response == 'q': ######break ######my_survey.store_response(response)###### # Display survey results######print("\nThank you to everyone who participated in the survey!")###### my_survey.show_results()################

test_survey.py

height = input("How tall are you, in inches? ")

import unittest

from survey import AnonymousSurvey

class TestAnonymousSurvey (unittest.TestCase):

"""A test for the AnonymousSurvey class"""

def setUp(self):

"""Create a survey object and a Set of answers for the test method used"""

question = "What language did you first learn to speak?"

self.my_survey = AnonymousSurvey(question)

self.responses = ['English', 'Spanish', 'Mandarin'] self.my_survey.store_response(self.responses[0])

#"""The three answers to the test will be properly stored""" ##for response in self.responses:

self.assertIn(response, self.my_survey.responses)

unittest.main()

Method setUp()

Does two things: creates a survey object; creates an answer list.

The variable name that stores these two things contains the prefix self (that is, stored in the attribute), so it can be used anywhere in this class. This makes both testing methods simpler, since neither creates survey respondents nor answers.

Use int() to input numbers

Because the data type returned by input() is str (string), python will convert the directly input number into a string. str cannot be directly compared with an integer, str must be converted to an integer first. Python provides the int() function to accomplish this

height = int(height) #Convert to integer

##Modulo operator


When processing numerical information, the modulo operator (%) is a very useful tool. It divides two numbers and returns the remainder:

>>> 4 % 3

1

>>> 5 % 3


2

>>> 6 % 30>>> 7 % 3

1

If one number is divisible by another number, the remainder is 0, so the modulo operator will return 0. You can use this to determine whether a number is odd or even.

The above is the detailed content of Summary of Python basics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn