简体   繁体   中英

Python unit test advice

Can I get some advice on writing a unit test for the following piece of code?

%python

import sys
import json

sys.argv = []
sys.argv.append('{"product1":{"brand":"x","type":"y"}}')
sys.argv.append('{"product1":{"brand":"z","type":"a"}}')

products = sys.argv

yy= {}
my_products = []

for n, i in enumerate(products[:]):
    xx = json.loads(i)
    for j in xx.keys():
        yy["brand"] = xx[j]['brand']
        yy["type"] = xx[j]["type"]
        my_products.append(yy)

print my_products

As it stands there aren't any units to test!!!

A test might consist of:

  • packaging your program in a script
  • invoking your program from python unit test as a subprocess
  • piping the output of your command process to a buffer
  • asserting the buffer is what you except it to be

While the above would technically allow you to have an automated test on your code it comes with a lot of burden: - multi processing - weak assertions by not having types - coarse interaction (have to invoke a script, can't just assert on the brand/type logic

One way to address those issues could be to package your code into smaller units, ie create a method to encapsulate:

  for j in xx.keys():
        yy["brand"] = xx[j]['brand']
        yy["type"] = xx[j]["type"]
        my_products.append(yy)

Import it, exercise it and assert on its output. Then there might be something to map the loading and application of xx.keys() loop to an array (which you could also encapsulate as a function).

And then there could be the highest level taking in args and composing the product mapper loader transformer. And since your code will be thoroughly unit tested at this point, you may get away with not having a test for your top level script?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM