I got into the habit of using Python unit tests in a job a few about a year ago. I eventually created the jsonhunt.py unit test in my Toys repository but it stopped working. I haven't even used the jsonhunt script in a while and am no longer certain of its usefulness but I don't like the idea of not being able to do unit tests if I wanted to.
Simple working example
So I sat down and got a simple unit test working. Here's the test script:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
import os | |
import logging | |
from unittest import TestCase | |
import random | |
logging.basicConfig(format='%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(msg)s') | |
log = logging.getLogger() | |
class Tests(TestCase): | |
def __init__(self, *args, **vargs): | |
super(Tests, self).__init__(*args, **vargs) | |
log.setLevel(int(os.environ.get('LOG_LEVEL') or '30')) | |
def test1(self): | |
log.info('This is a test') | |
self.assertTrue((random.randint(0,9) % 2) == 0) |
Notes
- I wish I had found a way to see options or arguments in the test but I couldn't find a way to do that. I had to settle for an environment variable to control the logging level.
- From the job I mentioned, I remembered we had a way of specifying the log level through some sort of option but I couldn't find a opportunity to get such an option, even through the superclass.
- At first I was trying to use a zero-argument constructor method but that wasn't working so I added *args, **vargs.
From the command line
I have a copy of the script in a git repository so a way to run the test is using that copy of the script:- get clone https://github.com/pfuntner/fun.git
- cd fun/test
- python -m unittest test1.Tests.test1
From PyCharm
Using the same repository as above:- Install the pytest package in PyCharm if it's not already installed
- Create a PyCharm Run Configuration using the pytest Python test template:
Notes
- I couldn't get the PyCharm debugger working - at least not yet!
Comments
Post a Comment