Python Unit Test

Source: Internet
Author: User

Introduction to Python development and combat 11-Unit test 1. Unit Test

In this section we talk about how to implement unit testing in Django Engineering, how unit testing is written, and the importance of unit testing in a sustainable project.

Here is the definition of the unit test:

Unit testing is a small piece of code written by a developer to verify that a small, well-defined function of the code being tested is correct.

1. It is a validation behavior

Each function in the program is tested to verify its correctness. It provides support for future development. Even in the late stages of development, we can easily add functionality or change the structure of the program without worrying about breaking important things in the process, which provides a guarantee for refactoring the code. In this way, we can improve the program more freely.

2. It is a design behavior

Writing unit tests will allow us to see and think from the caller. Especially the first write test (Test-first), forcing us to design the program into easy to call and testable, that forces us to remove the coupling in the software. What time is the test? The earlier the unit test, the better, early to what extent? Extreme Programming (Extreme programming, or XP, for short) is about TDD, which is test-driven development, where you write test code before you develop it.

However, in the actual coding process, we do not have to overemphasize the first to write what, it is important to be efficient and personal comfort. From the author's experience, according to the design or demand to write a functional function of the framework, and then proceed to write test functions, for the function of the product to write test cases, and finally write the implementation code of the function, each completion of a function point is run unit test, at any time to complement the test case. This kind of test peer Code writing mode, will be a function of the idea of a great help, how to write the function of the unit test will slowly become the writing and thinking habits.

The so-called first writing function framework of the product function, is to write the function empty implementation, consider the parameters of the parameters and the verifiable return value, while the default directly returns an appropriate value ( assuming the value ), compiled through the code can be written, then the function name, parameter table, The return type should be determined, the test code written after the possibility of modification is relatively small, of course, due to the individual coding maturity, the actual development process adjustment is unavoidable, fortunately unit testing can quickly track the impact of the adjustment.

3. It is a document-writing behavior

Unit testing is a priceless document, which is the best document to show how a function or class is used. This document is compiled, can be run, and it remains up-to-date, always in sync with your code.

4. It has a regressive nature.

Automated unit testing avoids code regressions, and when written, you can run tests quickly and anywhere. The author's experience shows that a responsible unit test method will find many bugs in the early stages of software development, and the cost of modifying them is low. In the late stages of software development, the discovery and modification of bugs can become more difficult, especially when modifying bugs can lead to the introduction of new bugs and consume significant time and development costs.

The author's experience of the project encountered such a problem, the project on the previous day of a bug modification, causing the night has been overtime late to solve the newly introduced bug problem, so later unit testing regression in the author's project experience favorite features. You can avoid modifying the bugs that may be introduced whenever you make changes to complete regression testing. Testing software products early in the life cycle will ensure the best possible efficiency and quality. The system integration process is greatly simplified in the case of a tested unit. Developers can focus on the interaction between the units and the implementation of the global functionality, rather than being stuck in a unit full of bugs.

Unit testing is important if you are considering a project that can be continuously improved and maintained, especially with a large number of business rules and logical systems, and unit testing primarily writes the test code for the business logic to determine whether the encoding meets the test requirements. Let's go into Django's unit testing practice.

1.1. Run unit Tests

We create a Django app each app creates a unit test file for unit test tests.py, with the following code:

"" This file demonstrates writing tests using the UnitTest module. These'll passwhen you run "manage.py test". Replace this with the more appropriate tests for your application. "" " From django.test import Testcaseclass simpletest (TestCase):    def test_basic_addition (self): "" "    Tests That's 1 + 1 always equals 2.    "" " Self.assertequal (1 + 1, 2)

We can now run this test example in the IDE environment Test->all tests to see the effect of the unit test run.

1.2. Start our first unit test

Let's take a look at the submission of the warehousing order for this business, The current views.py function Addinstockbill is not able to carry out unit testing, should be a parameter for the Web request content parameter requests, how to write a functional code that can have unit testing is also the early writing unit test, you can let us gradually grasp the code decoupling thinking mode.

Warehousing single Business is the key point, that is, after the submission of warehousing orders we need to update the inventory data of the corresponding items, pseudo-code as follows:

1. Find the inventory record of the current item in the inventory table according to the item of the current warehousing order;

2. If there is a current inventory record returning the current inventory object, create a new object if one is not present;

3. Update the current inventory data of the corresponding item in the inbound order;

Let's take a look at how to try out the test-first development model to consider an incoming single model submission that will lead to an inventory of the update scenario, using code to speak:

From django.test import testcasefrom inventory.models import *from Inventory Import views Class Inventorytest (TestCase):d EF test_updating_inventory_in (self):    #1. Creates an item instance; Item    = Item () Item    . ItemId = 1    item. ItemCode = ' 1001 '    item. ItemName = ' normal nut '    #2. Bed Building a new inbound single object    Instockbill = Instockbill ()    instockbill.instockbillcode= ' 201501010001 '    instockbill.instockdate = ' 2015-01-01 '    instockbill.operator = ' Zhang San '    instockbill.amount = ten    Instockbill.item = Item    #3. Creates an inventory object for the current item    inventory = Inventory ()    inventory. Inventoryid = 1
    Inventory. Item = Item    inventory. Amount = ten #当前库存数量        #如何构建更新库存的函数 so that it can have test call views    . Updatinginventoryin (instockbill,inventory)    #校验测试是否满足当前场景    self.assertequal (inventory. Amount, 20)

Currently we are currently running unit tests that are definitely going wrong because we haven't written views yet. Updatinginventoryin function:

def updatinginventoryin (instockbill,inventory):    inventory. Amount = inventory. Amount + Instockbill.amount
1.3. Performing unit Tests

In the IDE environment to execute the unit tests we have written, we see results such as test pass.

Here our unit tests are primarily built for the core business, regardless of how the related objects are acquired, that is, the test case is built from the test scenario, regardless of whether the object is in the database or not, which is not related to the persistence layer. The author of the early years here is also a great expense, test data and persistent layer data tightly coupled, the results of the replacement database or after the deletion of data, Unit test regression test can not be implemented, unit testing advantages greatly reduced. The regression of unit test has great advantage in subsequent code refactoring, business change, the unit test can not return a lot less value, so when we consider unit testing, we should try to decouple from the persistent layer data, test case data is built in the test code.

1.4. Continuous improvement of the code

In the preceding code, our test case scenario assumes that the item is already in stock, and if the item has no previous inventory data, how does our code write it, and we start with the test case and add the test case code.

    ...
#校验测试是否满足当前场景 self.assertequal (inventory. Amount, inventory = inventory () #当前没有库存数据, we create object properties without assigning views . Updatinginventoryin (instockbill,inventory) self.assertequal (inventory. Amount, self.assertequal (inventory). Item.itemid, InStockBill.Item.ItemId)

Perform a test error because of views . Updatinginventoryin (instockbill,inventory) did not deal with the inventory empty case, I improved the code to meet such requirements. The function code then becomes the following:

def updatinginventoryin (instockbill,inventory):
if (inventory. Inventoryid = = None): inventory. Item = Instockbill.item inventory. Amount = 0inventory. Amount = inventory. Amount + Instockbill.amount

Execute the test pass, just the test case is written in a test function or separate writing, mainly to see our test case complexity, the complexity of the high of the separate to write, simply written in a test function. The selection of the granularity of the function is considered by the programmer, the core is the attention to readability, the function is too long we will be the function of small, improve readability. (Here I strongly recommend "code refactoring", a classic book many years ago).

The last of the views of the increase in the storage of the single function is composed of the following code:

@transaction. Commit_on_successdef Addinstockbill (Request): if Request.method = = ' POST ': Form = Instockbillform (r Equest. POST) if Form.is_valid (): cd = Form.cleaned_data Instockbill = Instockbill () insto Ckbill.instockbillcode = cd[' Instockbillcode '] instockbill.instockdate = cd[' instockdate '] inStockBi ll.            Amount = cd[' Amount '] instockbill.operator = cd[' Operator '] Instockbill.item = cd[' Item '] Inventorys = InStockBill.Item.inventory_set.all () if (Inventorys.count () ==0): Currentinventory              = Inventory () else:currentinventory = Inventorys[0] #注意的函数调用, you will find the update inventory fully decoupled from how to get the inventory object Updatinginventoryin (instockbill,currentinventory) currentinventory.save () #更新库存 Instoc             Kbill.save () #保存入库单数据 return httpresponseredirect ('/success/') Else:form = Instockbillform () ReTurn render_to_response (' instockadd.html ', {' form ': Form}, Context_instance = RequestContext (Request) )

1.5. Summary

How to write unit test code, test-first mode will let the coder to think how to abstract the business logic into a unit test can be tracked by the function unit is very helpful, if we are writing a database to deal with the application system, It is quite important to decouple the business logic from how to get the data, especially when we intend to build a system that can be continuously improved.

Tags: python, django, unit test

Python Unit Test

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.