Category Archives: Java

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.

API Design with Java 8

In this blog post, Per-Åke Minborg talks about the fundamentals of good API design. His inspiration for writing this article is a blog post by Ference Mihaly which is essentially a check-list for good Java API design.

“API combines the best of two worlds, a firm and precise commitment combined with a high degree of implementation flexibility, eventually benefiting both the API designers and the API users.”

Do not Return Null to Indicate the Absence of a Value

Using the Optional class that was introduced in Java 8 can alleviate Javas problem with handling nulls. An example below shows the implementation of the Optional class.

Without Optional class

public String getComment() {

    return comment; // comment is nullable

}


With Optional class

public Optional getComment() {

    return Optional.ofNullable(comment);

}

Do not Use Arrays to Pass Values to and From the API

“In the general case, consider exposing a Stream, if the API is to return a collection of elements. This clearly states that the result is read-only (as opposed to a List which has a set() method).”

Not exposing a Stream

public String[] comments() {

    return comments; // Exposes the backing array!

}

Exposing a Stream

public Optional getComment() {

    return Optional.ofNullable(comment);

}

Consider Adding Static Interface Methods to Provide a Single Entry Point for Object Creation

Adding static interface methods allows the client code to create onjects that implement the interface. “For example, if we have an interface Point with two methods int x() and int y(), then we can expose a static method Point.of(int x, int y) that produces a (hidden) implementation of the interface.”

Not using static interface methods

Point point = new PointImpl(1,2);

Using static interface methods

Point point = Point.of(1,2);

I selected this resource because it relates to design principles, and it’s something that I do not know well. I would like to learn more about APIs and good practices for designing them using Java. The article had useful information and topics that I didn’t know well. A few more pointers from the article I learned:

  • Favor Composition With Functional Interfaces and Lambdas Over Inheritence – Avoid API inheritance, instead use static interface methods that take “one or several lambda parameters and apply those given lambdas to a default internal API implementation class.”
  • Ensure That You Add the @FunctionalInterface Annotation to Functional Interfaces – signals that API users may use lambdas to implement the interface
  • Avoid Overloading Methods With Functional Interfaces as Parameters – Can cause lambda ambiguity on the client side.

I would like to learn more about using AWS Lambdas, and learning more about APIs in general. I plan to use this information if I am ever to work on Java APIs which is possible. I want to make sure I have the best practices and the check list mentioned in the start of the article seems like a good starting point.

The post API Design with Java 8 appeared first on code friendly.

From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.

First Meet With Dhimitri

Jon, Dhimitri and I had a meeting today to catch Dhimitri up on what we have been doing and the plan for the next few months.  We met in the library and discussed how to set up Action Bar Sherlock and demo’d the app again.  We plan on following the style guide very thoroughly so the app will flow how normal Android apps work.  We also talked about trying the app done to a point where we could start field testing the app with students around campus and get a feel for what works and what will need improvement.

 

Everything seemed to go pretty well, I’ll be working on editing a task that has been previously made using ‘add task’ and I think I may just have the edit copy the old task and replace the new data instead of just updating, not too sure yet.

 

We talked about doing SQLite a little bit but the point still stands about leaving it out until later (if we want/need it).

From the blog jamescelona » WSU CS by jamescelona and used with permission of the author. All other rights reserved by the author.

Catching Up on GIT

Howdy all,

Luckily Jon and I have been working internships all summer using some sort of variation of a Version Control System.  I guess I didn’t learn as much as I thought in 401 for GIT as I really needed.  My git-foo has improved significantly (Jon’s is still way above mine, though. )  Right now I’m working on my james-dev branch (at least the one I push to) and usually branch when I’m trying something new.  I’m really digging the issue tracker but, I think one day this week I am going to take some time out, probably with Jon, and really get our Wiki in gear.

In other news, old news that I never mentioned, Joe was MIA for a while and I finally got in contact with him and he said he was too busy and couldn’t commit I emailed Karl about it but I never got a response, I’m sure he’s just enjoying summer.

From the blog jamescelona » WSU CS by jamescelona and used with permission of the author. All other rights reserved by the author.

Method chaining

While experimenting with adding context menus and alert dialogs to the app, I discovered a cool Java feature that I didn’t know existed: method chaining. By taking normally void methods and instead having them return a reference to their object, you can turn this:

Person p = new Person();
p.setName(“Bill”);
p.setAge(40);
p.setZip(01701);

into this:

Person p = new Person();
p.setName(“Bill”).setAge(40).setZip(01749);

As far as I can tell, efficiency doesn’t change when using method chaining vs. the traditional way. But it looks a lot cleaner and I may start using it.

From the blog Code Your Enthusiasm » WSU CS by Jon and used with permission of the author. All other rights reserved by the author.

The basics of an Android app

Learning the structure of an Android app is overwhelming at first, but it’s not too difficult after some familiarization. I recommend using Lars Vogel’s excellent Android tutorials here. They are among the best tutorials I have found, and I am sure I will keep using them as a reference as this project continues.

An Android app is made up of two parts: the front end and the back end. The front end is the visual part of the app that the user interacts with, and the back end, which contains all the code that drives the app.

The front end is written using XML. I have never used XML before, but it is very similar to HTML in that it is a markup language that uses nested tags as its programming structure. Android uses several XML files to create the app’s front end. There is at least one XML layout file for each activity (or several if you are supporting multiple device sizes), as well as layout files for custom views. XML is also used to define constant strings that will be placed in the layouts, such as the text on a button.

The back end is written in Java, which is great because it is a language that I am very familiar with. You can use the Java standard library in addition to the Android library when coding your app. This gives you access to a ton of pre-made objects, and the APIs are thoroughly documented online by Oracle and Google.

Each screen in an app is known as an activity. Activities are classes that you extend from a base activity class. Each activity is tied to an XML layout file which provides the front end visuals. Activities are created, resumed, and closed by the Android OS through a series of callback methods, which are called automatically by the OS at the appropriate times. Some examples of callback methods: onCreate, onPause, onResume, onStop. These methods have to be overwritten for your activity to work correctly.

Information sent between activities is called an intent. Intents carry standard data like strings or can be modified to carry custom extra data. For example, our AddTaskActivity creates a new Task object, adds it to an intent, and sends it back to the MainActivity where it will be displayed for the user.

There are other basics, such as fragments, services, and notifications, but I don’t know enough about them yet. I’ll comment on those after I’ve learned them!

From the blog Code Your Enthusiasm » WSU CS by Jon and used with permission of the author. All other rights reserved by the author.

My First App

I never mentioned in my previous post that I have been watching www.thenewboston.org ‘s video series throughout the past few weeks.  He’s a young guy and it’s kind of funny learning from him sometimes, weird little things bother me sometimes, I’m weird, it’s weird.  But!

I wrote my first app, you can push a button to add or push a button to subtract! Can’t wait to publish it to Google play..  It’s a good building block to start from.

————————————-

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >

<TextView
android:id=”@+id/tvDisplay”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_gravity=”center”
android:gravity=”center”
android:text=”Total =”
android:textSize=”45dp” />

<Button
android:id=”@+id/addButton”
android:layout_width=”250dp”
android:layout_height=”wrap_content”
android:layout_gravity=”center”
android:text=”Add One”
android:textSize=”20dp” />
<Button
android:id=”@+id/subButton”
android:layout_width=”244dp”
android:layout_height=”wrap_content”
android:layout_gravity=”center”
android:text=”Subtract One”
android:textSize=”20dp” />

</LinearLayout>

——————–

Does wordpress not have a <code> tag? Gross.

But, that’s XML a lot of referencing android:layout, or just android in general, who would have thunk it?!  XML seems pretty straight forward, oddly enough the day after I learned some of it I had to write it a bit for my internship, which was pretty cool.

From the blog jamescelona » WSU CS by jamescelona and used with permission of the author. All other rights reserved by the author.

First Week install/configure

It’s been a slow start to the project, nice weather tends to do that to me.  I manged to find a great video series about Android development that really starts from the ground up.  Actually, it’s kind of boring at times when he begins to talk about what’s going on in the Java code he’s typing, the XML I am lost but the Java is pretty straight forward (for now).

I have mixed feelings about using Eclipse for this project, I think it will come in handy most of the time but, it’s really bloated.  I like Gedit, or I guess notepad++ for windows.

I watched the first videos, downloaded Eclipse, downloaded everything I needed, John wants to work on Android 4.03 since his phone will be able to use it.  It’s going to work fine but, just won’t be available to as many people considering it’s a much newer version than the API level 8 that was suggested in the video series.   The videos came in handy since I thought it was always kind of a pain in the neck to set up Eclipse in Java.

It’s pretty convenient that I am learning XML because I had to use it recently at my job, and knew where I was because of watching a few videos.

From the blog jamescelona » WSU CS by jamescelona and used with permission of the author. All other rights reserved by the author.

Setting up the Android SDK & Eclipse

This summer I will be developing an Android app with James, who is also a senior CS major at Worcester State. Neither of us have ever done anything like this, so needless to say it will be an adventure. The first thing I had to do was to properly set up my development environment. Google has a guide here, but it wasn’t the smoothest process. There was a bit of trial and error along the way. I have a fairly modern computer running Windows 7 64-bit. Here’s my rundown of setting everything up:

Step one was to install the JDK, Java Development Kit. That was easy enough. Oracle’s website has lots of options, so it was important to choose the standard 32-bit JDK installer. Even though I have a 64-bit system, I chose 32-bit in order to maximize compatibility.

Step two was to install the Android SDK. Once that has been installed, running the SDK Manager lets you choose what Android platforms to download. For now, I only downloaded the latest version, 4.0.3/API15.

Next was to install Eclipse. Eclipse.org has a lot of options. I opted for Eclipse for Java Developers 32-bit (matching my 32-bit JDK), though I hear Eclipse Classic works too. There is no installer exe for Eclipse, only a zip file, which might confuse Windows users. You just need to extract the zip file into your JDK directory, and that’s it. In my case, Eclipse ended up in “C:\Program Files (x86)\Java\jdk1.7.0_04\eclipse”. Then you run eclipse.exe from that folder and off you go.

Inside Eclipse, the next step is to install the ADT plugin, which will integrate several Android tools into Eclipse. This is where things started getting a little hairy. According to the Google guide, Eclipse should be able to grab the tools from a repository located here: “https://dl-ssl.google.com/android/eclipse/”. Eclipse did that, then proceeded to tell me that the tools couldn’t be installed. After a lot of searching, I didn’t find a fix, but I learned the problem possibly has to do with the fact that I am using a newer version of Eclipse (Indigo) than when the guide was written (Helios). Thankfully, Google offers a manual download of the tools here, so I was finally able to get the ADT plugin up and running.

Now that the Android SDK and Eclipse were both configured, it was time to write a program! The Google guide has a very nice-looking series of tutorials, starting with a Hello World app. The first thing to do was to make an AVD (Android Virtual Device), an Android phone emulator. This went smoothly. So did creating the new project, and writing up the simple code. Now to run my very first Android program…

FAIL. In the console, in bright red, I see the message “PANIC: Could not open: C:\Users\Jon\.android/avd/my_avd.ini”. What is this?? Why can’t it find my emulator??? I check, and sure enough, there is no .android folder in my Jon directory. The .android folder is on the root of my D:\ drive, and the AVD is in there. So why is Eclipse looking in my user folder, and how can I fix it? After a lot of searching, I found my answers here. It turns out that this is an ADT bug, and to fix it, I had to make a symbolic link between the two locations. So, in a Windows command prompt, I ran:

mklink /J “C:\Users\Jon\.android” “D:\.android”

An .android folder showed up inside my user directory, identical to the one in D:\. It’s important to note that if I ever want to delete this link, I need to run rmdir rather than just delete the folder. Otherwise, Windows will delete both locations instead of just the symbolic link. I went back to Eclipse and tried running my program again, and it worked! I’ve never been so happy to see “Hello World” appear on my screen.

From the blog Code Your Enthusiasm » WSU CS by Jon and used with permission of the author. All other rights reserved by the author.