2

I am new to Python and I was asked to write script to do some test, what Python module can I start with? unittest?

example tests would be:

if not host_is_pingable():
     print "Unable to ping"
     sys.exit()
if not able_to_ssh():
     print "Unable to ssh into the host"
     sys.exit()
if not mounts_are_ok():
     print "Missing mounts"
     sys.exit()
if not misc_test():
     print "some error"
     sys.exit()
3
  • Those don't look like unit tests. They look like precondition checks. What exactly do you mean by "tests"? Commented Jan 8, 2018 at 23:16
  • 1
    If you want to do purely string based tests you can use doctests docs.python.org/3/library/doctest.html Commented Jan 8, 2018 at 23:17
  • Thanks surfer190, this helps too. Commented Jan 31, 2018 at 13:17

1 Answer 1

2

There are many ways to do tests, often it depends on what framework you use. But, just assuming that you want some form of a formal test framework, you can use pytest.

Step 1, install pytest

$ pip install pytest

Step 2, Format your code. You will test your output according to the return of the function.

def host_is_pingable(x):
    #Do your verification logic here... putting the result in a string valid
    return valid

Step 3, Now write the tests

def test_answer():
    assert host_is_pingable(ip_address) != "some error"

Step 4, run the tests

$ py.test

This is not a unittest, but a boilerplate test framework.

If you want to do unittests, there is a great guide to it here: http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html

Update 2019

The unittest introductory guide link is now dead but you can find it archived at WayBackMachine here https://web.archive.org/web/20180121231649/http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.