Getting Started With Python Unit Testing After Learning JUnit

Christian Shadis

CS-443 Self-Directed Blog Post #5

This past semester I have been spending a lot of time in my QA class working with JUnit 5. I want to be able to take my familiarity with JUnit and apply the same principles with unit testing in Python. I am leaning toward a data-centric career path and Python is widely used for data analytics, so this would be valuable information for me.

This post is not an expert-authored tutorial on Python unit testing because I, myself, am just getting started with it. In this post I will instead give tiny, bite-sized examples of just the basics, translating it from JUnit to Python unittest. I built identical, small classes in Java and Python, and will build tests to go with them. Below are the classes in Java and Python, respectively.

/**
 * Simple class with basic methods, written in Java
 * @author Christian Shadis
 */
public class main {
    public static void main(String[] args){
        int i = 0; // dummy code to keep compiler happy
    }

    public static int addTwoNumbers(int x, int y){
        return x + y;
    }

    public static String toCapital(String str){
        return str.toUpperCase();
    }
}

# Simple class with basic functions, written in Python
# Author: Christian Shadis

class main:
    def add_two_numbers(x, y):
        return x+y

    def to_capital(string):
        return string.upper()

Writing the unit tests in JUnit is simple: we import the JUnit assertions, and the @Test annotation. Then we create the test class, each of the two tests, setup, exercise, and verify just as always.

/**
 * Test Class for main.java
 * @author: Christian Shadis
 */
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class maintest {

    @Test
    void testAddTwoNumbers(){
        int result; // setup
        result = main.addTwoNumbers(566, 42); // exercise
        assertEquals(result, 608); // verify
    }

    @Test
    void testToCapital(){
        String result; // setup
        result = main.toCapital("string"); // exercise
        assertEquals(result, "STRING"); // verify
    }
}

Luckily, writing unit tests is just as easy in Python as Java. We import the unittest library and the other class, define the class, and add a Test Case object as the parameter.

import unittest
from main import *

class maintest(unittest.TestCase):
import unittest
from main import *

class maintest(unittest.TestCase):

    def test_add_two_numbers(self):

        pass
    def test_to_capital(self):

        pass

Now we need a test case for each of our two functions, add_two_numbers and to_capital. Python’s unittest objects have very similar assertions as in JUnit. Use assertEqual(x, y) to check that x == y. This is the assertion we will use in this example, but any of the following are commonly used unittest assertions:

  • assertEqual
  • assertNotEqual
  • assertTrue
  • assertFalse
  • assertIs
  • assertIsNot
  • assertIsNone
  • assertIsNotNone
  • assertIn
  • assertNotIn
  • assertIsInstance
  • assertIsNotInstance

assertEqual takes two arguments and, as the name suggests, asserts their equality. See the implementation below:

    def test_add_two_numbers(self):
        result = main.add_two_numbers(33, 44)
        self.assertEqual(result, 77)

    def test_to_capital(self):
        result = main.to_capital("hi")
        self.assertEqual(result, "HI")

Run the tests and you will see them both pass. Below is a screenshot of the tests executing in Python and then in JUnit. As you can see, the Python tests are slightly faster than the Java tests, but not by much. I used IntelliJ IDEA and Pycharm IDE.

I have found the most helpful way to learn testing is to just play around with the unit tests, see what works and what doesn’t, see what causes failures and what those failures look like, and so forth. I would suggest any other beginner QA student to do the same. Playing around with different assertions and looking at the unittest documentation is a great way to learn this library. I hope this post gave you some insight on how to get started with unit testing your Python modules if you have done some work with JUnit in the past.

4/28/2021

Works Cited:
Unittest – unit testing framework¶. (n.d.). Retrieved April 28, 2021, from https://docs.python.org/3/library/unittest.html

From the blog CS@Worcester – Christian Shadis' Blog by ctshadis and used with permission of the author. All other rights reserved by the author.

Mockito mocking

On the Vogella Mockito tutorial page, there is a brief overview and explanation of what mocking is and what a mock object is. There is a simple diagram showing the sequence of what typically happens when you use Mockito in your tests. This tutorial also mentions that when using the Mockito libraries, it is best to do so with either Maven or Gradle, which are supported by all of the modern IDEs. Here you can also find code examples, and even where to put them in your code. This tutorial is packed with visual representation of the information given and I find that to be extremely helpful.

I would say this particular article/tutorial can be very helpful in bettering one’s understanding of how to use Mockito. It’s filled with tips and simple to understand diagrams, explanations and code examples. It even dives into using the spy() method to wrap Java objects, mocking static methods, creating mock objects (in the exercise provided, you can create a sample Twitter API), and testing an API using Mockito.

I have included in this blog post two other articles I found interesting and informative on the subject of Mocks/Mocking

From the blog cs@worcester – Coding_Kitchen by jsimolaris and used with permission of the author. All other rights reserved by the author.

Record What You Learn

            The learning pattern “Record What You Learn” from the Apprenticeship Patterns book is mostly self-explanatory from the title. The main concern of someone who gains a lot of knowledge quickly, such as a new software developer, or, in my case, a software development student, is retaining that knowledge. The chapter describes some good ways to track this learning, like with a wiki or a blog (hey!). Having to relearn or continuously practice concepts or bits of skill is time consuming and wasteful, especially if you don’t have something to quickly reference. This is a solution to that problem.

            Recording and retaining my learning has definitely been a problem in the past, although I’m trying to get better at it. At the start of my sophomore year, I realized I had forgotten a solid chunk of the programming skills that I had learned at the end of my freshman year. I had to work a lot over that summer, so I didn’t have a ton of time to practice these skills through personal projects or places like LeetCode. Getting back into the swing of things, especially as difficulty was ramping up, was a struggle. Luckily, I haven’t hit a patch like that since, but there have been plenty of times that I found smaller, but still useful concepts, escaping me.

            Some things in this department might be like remembering some concepts, but forgetting the implementation, or even just one key part of implementation. This is exactly where a wiki/blog would be super useful. I find I usually follow my own train of thought best, as I assume is the same for everyone, so having something to reference in my own writing, in a way that I find is useful in understanding a topic, is best as well. Just in recent memory, I had some trouble trying to remember how to create a custom comparator for two objects. I had just done it last week, at which point I had to look it up. It was excusable the first time, but just a pain the second time. So, even after a week, I still face these troubles. I definitely need to get better as recording my learning, so this learning pattern is a great point of emphasis for me.

From the blog CS@Worcester – Marcos Felipe's CS Blog by mfelipe98 and used with permission of the author. All other rights reserved by the author.

Apprenticeship Patterns: Passion

I decided to once again choose patterns that cover related issues, this one being about passion. This is something that I find myself struggling with on and off between projects, where I have moments of excitement starting a project and successfully implementing a function, but often encounter issues that can stifle this passion. Beyond this I simply have times where I lose the drive to work on personal projects and struggle to find the desire to continue working with software design of any sort. Thus for this post post I chose to focus on the Nurture Your Passion pattern.


There are a few key points mentioned to help with this issue. The first mentioned is that you might just have to put any current work you are struggling with aside if possible to focus on another aspect that interests you. This can be in the form of a different part of the system you are currently working on or even just a breakable toy that will help you learn and grow, rather than stifling this advancement. Additionally, you should try to find a community that you can participate in. More often than not there are others in similar situations, and if you look online you can find discussion boards or even whole websites that have a variety of programmers discussing with each other. Getting different perspectives on the craft from others can reveal new insights to you, reigniting your interest in what you do. Furthermore there are even online study groups if you need particular help with specific issues. Beyond this you can also try reading some of the classic, well-regarded books in your free time. This will allow you to learn in a very low risk environment, removing the immediate stress of having to have functional code and allowing you to enjoy the intricacies of whatever is discussed in the book. Finally, if you are in a professional setting, you have to set work environment standards ahead of time. This can mean setting a hard time for when you stop working to ensure any toxic conversations are steered towards a productive topic.

While I am not in a professional setting yet, this information has helped me. I have never really thought about having to set standards for myself going into a job and will keep that in mind for the future. Many of these tips, as always, sound like they will be very helpful in the future and i have nothing to disagree with.

Source

https://www.oreilly.com/library/view/apprenticeship-patterns/9780596806842/ch03s04.html

From the blog CS@Worcester – My Bizarre Coding Adventures by Michael Mendes and used with permission of the author. All other rights reserved by the author.

Apprenticeship Patterns: Failure

Something that I am sure many others who have pursued a career in computer science have encountered is failure. Throughout my attempts at coding, I have found that a vast majority of my time is spent trying to fix my own failed programs. This was, and can still be, a pretty large barrier to my enjoyment of programming, as simply trying to fix your own broken code over and over give the impression that you are not really making progress. To get a different perspective on this issue I chose to cover the Learn How You Fail pattern for this week.


This pattern gives a few key ideas to keep in mind when you feel like you find yourself stuck in a rut of failure. Firstly you should try not to focus on the disappointment of your failure, but focus on determining what happened that caused this failure. Work back through what you did to get to the point of failure and determine exactly what you did that caused this, then make note of the cause. If you can record these issues you will be able to determine your own strengths and weaknesses. This may lead you to realize that you have to put in a large amount of effort for seemingly small gains, but this will allow you to set accordingly realistic limitations on your goals. Accepting these limitations is also important, as it allows you to determine where you should and should not spend your time, which may require you to drop some projects for now. This will allow you to focus on any other issues you are encountering, and you can always return to the previous issue later.

So far I have found that failure is something that goes hand-in-hand with software design, especially when learning something new. Personally, I have always taken the very straightforward hit your head against the brick wall until it breaks method with failure, often  spending a long time solving small issues. After reading this pattern I have realized I should be recording what I am doing wrong each time, and that would certainly save me some time in the long run. Though I am still early in my career I found this pattern to be useful yet again and had nothing to disagree with.

Source

https://www.oreilly.com/library/view/apprenticeship-patterns/9780596806842/ch05s09.html

From the blog CS@Worcester – My Bizarre Coding Adventures by Michael Mendes and used with permission of the author. All other rights reserved by the author.

Concrete Skills

The section “Concrete Skills”, found in chapter two in Apprenticeship Patterns by Dave Hoover and Adewale Oshineye discusses the issue of needing some quality that will convince hiring managers to choose you over other candidates. In particular, this issue centers around the question “If we hire you today, what can you do on Monday morning that will benefit us?”. The solution the authors suggest is that one should develop concrete skills. What they mean by concrete skills is abilities that show that you don’t need to be babysat such as writing build files in popular languages or having knowledge of popular open-source frameworks. Skills like these show people like hiring managers that you have something of worth outside the basic skills expected of an entry level position. In the long term, the specific skill doesn’t matter too much as it’s just a stepping stone to the path to journeyman.

A concrete skill isn’t something that I’ve put too much thought into. I guess some could say that skills I’ve learned in class like knowing how to use docker or SQL would count as concrete skills, but that depends on the position I apply to. There’s also the projects and work connected to my GitLab account which I could show to a potential employer. Still, I have this feeling that it won’t be enough since most of my peers have a similar advantage if not more. That’s why I feel that I should do some independent study, not an internship mind you, something that I can do on my own time.

I feel like I could showcase a concrete skill by working on a personal project which I’ve been toying with but haven’t settled on a specific plan. I’d like to make a simple chess program, partly just as an excuse to learn the game but it would also be something to show to say “this is something I’m able to do and contribute”. I don’t know what exact skill this would convey; it could be that I’m proficient in so and so language or I can make a program by myself even if it’s on the simpler side. Despite my lack of direction right now, I feel it’s still worth a shot.

From the blog CS@Worcester – Rainiery's Blog by rainiery and used with permission of the author. All other rights reserved by the author.

Expose Your Ignorance

This chapter’s opening quote was a very insightful one for me. It says: ” Tomorrow I need to look stupider and feel better about it. This staying quiet and trying to guess what’s going on isn’t working so well.” The whole point of this chapter is that there are going to be times when you do not understand what is happening, what you need to do, or how to accomplish the task at hand. This is ok. Even if there are people depending on you to just know the right answer you will not always. You must ask questions and show that you are capable of learning how to do your job. That is how you grow as a craftsman.

“Expose your ignorance” is a pattern I have a lot to learn from. The opening quote talks about staying quiet when you do not know what is going on and that is something I am often guilty of. Just like the author says, I am afraid of looking incompetent. I often feel this way despite knowing I am not yet expected to be a competent programmer; if I were then I probably would not be in this class (I would consider some of my peers to be pretty competent though). As I student I am surrounded by professors who are literally being paid for me to expose my ignorance to, and they are happy to hear it. I am confident all the faculty in the CS department would love to hear more students ask questions and admit they do not have any idea what is going on. Most classes are silent though, especially in online courses. I am not sure if it is from a lack of interest in the course, the difficulties of online courses, or a fear of asking questions (it is probably a combination of the three.)

Moving forward I will really keep this pattern in mind, both as I finish this course and as I go out into the workforce. Not knowing everything does not mean you are not good enough. It simply means you are not good enough yet. Asking questions and actively working to improve shows that you are willing to put in the effort to become better.

From the blog CS@Worcester – Half-Cooked Coding by alexmle1999 and used with permission of the author. All other rights reserved by the author.

Use the Source

 When working on an open-source project, please get in the habit of downloading the latest version of the code (preferably from their source control system), so you can review its history and track future developments. Please take a look at the codebase structure and think about why it is organized the way it is. Look at how developers manage their code modules to see if it makes sense and compare them to how they might have used them. Try to refactor the code to understand why its coders made the decisions they did, and think about what the code would look like if you were the one coding it. It will give you a better understanding of the projects; Also, make sure you can build those projects. If you’ve found a better way to do something, you’re ready to contribute code to the project. Inevitably, as you go through the code, you’ll come across decisions you completely disagree with it. Ask yourself if the developers of the project might know something you don’t or vice versa. Consider whether this is a legacy design that needs to be refactored; consider whether making a toy implementation for the relevant feature would help clarify the issue.

You end up with a toolbox filled with all sorts of quirks that you’ve collected from other people’s code. This will hone your ability to solve minor problems more quickly and quickly. You’ll be able to tackle issues that others think are impossible to solve because they don’t have access to your toolbox. Take a look at the Git distributed source control system written by Linus Torvalds or any code written by Daniel J. Bernstein (known as DJB). Programmers like Linus and DJB occasionally use data structures and algorithms that most of us have never even heard of. They’re not magicians — they’ve just spent their time building bigger and better toolboxes than most people. The great thing about open source is that you can look at their toolbox and make their tools. One of the problems in software development is the lack of teachers. But thanks to the proliferation of open-source projects on sites such as SourceForge. Net and GitHub, you can learn from relatively representative code examples from the world’s programmer community.

In ODS, Bill Gates says: “The most subtle test of programming ability is giving the programmer about 30 pages of code and seeing how quickly he can read through it and understand it.” He realized something significant. People who quickly learn directly from the source code will soon become better programmers because their teachers are the lines of code written by every programmer in the world. The best way to learn patterns, idioms, and best practices is to read the open-source. Look at how other people to code. It’s a great way to stay relevant, and it’s free. — Chris Wanstrath at Ruby 2008 [

Pick an open-source project with deep algorithms, such as Subversion, Git, or Mercurial source control system. Browse through the project’s source code and jot down any algorithms, data structures, and design ideas that seem novel to you. Then write a blog post describing the project’s construction and highlighting the new ideas you’ve learned. Can you find a situation in your daily work where the same concept can be applied?

From the blog haorusong by Unknown and used with permission of the author. All other rights reserved by the author.

Use the Source

 When working on an open-source project, please get in the habit of downloading the latest version of the code (preferably from their source control system), so you can review its history and track future developments. Please take a look at the codebase structure and think about why it is organized the way it is. Look at how developers manage their code modules to see if it makes sense and compare them to how they might have used them. Try to refactor the code to understand why its coders made the decisions they did, and think about what the code would look like if you were the one coding it. It will give you a better understanding of the projects; Also, make sure you can build those projects. If you’ve found a better way to do something, you’re ready to contribute code to the project. Inevitably, as you go through the code, you’ll come across decisions you completely disagree with it. Ask yourself if the developers of the project might know something you don’t or vice versa. Consider whether this is a legacy design that needs to be refactored; consider whether making a toy implementation for the relevant feature would help clarify the issue.

You end up with a toolbox filled with all sorts of quirks that you’ve collected from other people’s code. This will hone your ability to solve minor problems more quickly and quickly. You’ll be able to tackle issues that others think are impossible to solve because they don’t have access to your toolbox. Take a look at the Git distributed source control system written by Linus Torvalds or any code written by Daniel J. Bernstein (known as DJB). Programmers like Linus and DJB occasionally use data structures and algorithms that most of us have never even heard of. They’re not magicians — they’ve just spent their time building bigger and better toolboxes than most people. The great thing about open source is that you can look at their toolbox and make their tools. One of the problems in software development is the lack of teachers. But thanks to the proliferation of open-source projects on sites such as SourceForge. Net and GitHub, you can learn from relatively representative code examples from the world’s programmer community.

In ODS, Bill Gates says: “The most subtle test of programming ability is giving the programmer about 30 pages of code and seeing how quickly he can read through it and understand it.” He realized something significant. People who quickly learn directly from the source code will soon become better programmers because their teachers are the lines of code written by every programmer in the world. The best way to learn patterns, idioms, and best practices is to read the open-source. Look at how other people to code. It’s a great way to stay relevant, and it’s free. — Chris Wanstrath at Ruby 2008 [

Pick an open-source project with deep algorithms, such as Subversion, Git, or Mercurial source control system. Browse through the project’s source code and jot down any algorithms, data structures, and design ideas that seem novel to you. Then write a blog post describing the project’s construction and highlighting the new ideas you’ve learned. Can you find a situation in your daily work where the same concept can be applied?

From the blog haorusong by Unknown and used with permission of the author. All other rights reserved by the author.

Use the Source

 When working on an open-source project, please get in the habit of downloading the latest version of the code (preferably from their source control system), so you can review its history and track future developments. Please take a look at the codebase structure and think about why it is organized the way it is. Look at how developers manage their code modules to see if it makes sense and compare them to how they might have used them. Try to refactor the code to understand why its coders made the decisions they did, and think about what the code would look like if you were the one coding it. It will give you a better understanding of the projects; Also, make sure you can build those projects. If you’ve found a better way to do something, you’re ready to contribute code to the project. Inevitably, as you go through the code, you’ll come across decisions you completely disagree with it. Ask yourself if the developers of the project might know something you don’t or vice versa. Consider whether this is a legacy design that needs to be refactored; consider whether making a toy implementation for the relevant feature would help clarify the issue.

You end up with a toolbox filled with all sorts of quirks that you’ve collected from other people’s code. This will hone your ability to solve minor problems more quickly and quickly. You’ll be able to tackle issues that others think are impossible to solve because they don’t have access to your toolbox. Take a look at the Git distributed source control system written by Linus Torvalds or any code written by Daniel J. Bernstein (known as DJB). Programmers like Linus and DJB occasionally use data structures and algorithms that most of us have never even heard of. They’re not magicians — they’ve just spent their time building bigger and better toolboxes than most people. The great thing about open source is that you can look at their toolbox and make their tools. One of the problems in software development is the lack of teachers. But thanks to the proliferation of open-source projects on sites such as SourceForge. Net and GitHub, you can learn from relatively representative code examples from the world’s programmer community.

In ODS, Bill Gates says: “The most subtle test of programming ability is giving the programmer about 30 pages of code and seeing how quickly he can read through it and understand it.” He realized something significant. People who quickly learn directly from the source code will soon become better programmers because their teachers are the lines of code written by every programmer in the world. The best way to learn patterns, idioms, and best practices is to read the open-source. Look at how other people to code. It’s a great way to stay relevant, and it’s free. — Chris Wanstrath at Ruby 2008 [

Pick an open-source project with deep algorithms, such as Subversion, Git, or Mercurial source control system. Browse through the project’s source code and jot down any algorithms, data structures, and design ideas that seem novel to you. Then write a blog post describing the project’s construction and highlighting the new ideas you’ve learned. Can you find a situation in your daily work where the same concept can be applied?

From the blog haorusong by and used with permission of the author. All other rights reserved by the author.