[PYTHON] I wrote unit tests for various languages

Repository

The ones introduced below are available on Github.

Introduction

Let's try writing a simple unit test to try out various languages. I will not explain in detail, so please refer to the external doc for that.

Since ~~~~ can be easily executed by using each IDE, it is not necessary to execute it on the command line and it is not described. It's just a lack of knowledge ~~

It's all running on Windown 10 Pro Insider Preview Build 17025.

Python

Execution environment

Python 3.6.1

Overview

In Python, the'unittest'package is available as standard, so use it.

File

Python/
 ├ src/
 │ └ sample.py
 ├ test/
 │ └ sample_test.py
 └ setup.py

sample.py

sample.py


class Calc:
    def add(self, x, y):
        return x + y

    def pow(self, x, y):
        return x ** y

sample_test.py

sample_test.py


import sys
import unittest

from sample import Calc


class TestSample(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.calc = Calc()

    def test_add(self):
        self.assertEqual(15, self.calc.add(10, 5))
        self.assertEqual(5, self.calc.add(8, -3))

    def test_pow(self):
        self.assertEqual(125, self.calc.pow(5, 3))
        self.assertEqual(sys.maxsize, self.calc.pow(2, 31) - 1)

setup.py

setup.py


from setuptools import setup, find_packages
import sys
import unittest

#Pip install even during development-e .You can refer to the sample module from any file by doing
#In that case, the following sys.path.append is no longer needed.
sys.path.append('./src')


def my_test_suite():
    """Under the test directory,*_test.Recognize py as a test module"""
    test_loader = unittest.TestLoader()
    test_suite = test_loader.discover('test', pattern='*_test.py')
    return test_suite


setup(
    name="Sample",
    version="1.0",
    #If you want to support pip when src is the root, set as follows, for example.
    package_dir={'': 'src'},
    packages=find_packages('src'),

    test_suite='setup.my_test_suite'
)

Execution method

Execute python setup.py test from the terminal.

Example of testing with doctest

sample.py


"""doctest example

Running this module directly will start doctest.
If there is a failed test

File "sample.py", line 11, in __main__
Failed example:
    calc.pow(5, 3)
Expected:
    126
Got:
    125
**********************************************************************
1 items had failures:
   1 of   4 in __main__
***Test Failed*** 1 failures.
Is displayed.

>>> calc = Calc()
>>> calc.add(10, 5)
15
>>> calc.add(8, -3)
5
>>> calc.pow(5, 3)
126

"""

class Calc:
    def add(self, x, y):
        return x + y

    def pow(self, x, y):
        return x ** y


if __name__ == "__main__":
    import doctest
    doctest.testmod()


Java

Execution environment

Java 9 JUnit 5

Overview

Java has various stand-alone libraries, but uses the famous JUnit.

File

Java/
 ├ src/
 │ └ Calc.java
 └ test/
    └ CalcTest.java

Calc.java

Calc.java


public class Calc {
	public int add(int x, int y) {
		return x + y;
	}

	public double pow(int x, int y) {
		return Math.pow(x, y);
	}
}

CalcTest.java

CalcTest.java


import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class CalcTest {
	private Calc calc = new Calc();

	@Test
	void add() {
		assertEquals(15, calc.add(10, 5));
		assertEquals(5, calc.add(8, -3));
	}

	@Test
	void pow() {
		assertEquals(125, calc.pow(5, 3));
		assertEquals(Integer.MAX_VALUE, calc.pow(2, 31) - 1);
	}

}

Execution method

Since JUnit can be easily executed by using each IDE, it is not necessary to execute it on the command line and it is not described.

JavaScript(Node.js)

Execution environment

NodeJS v8.6.0 npm v5.3.0

Overview

There are various libraries, but this time we will use mocha. Babel-cli and babel-preset-env were used to handle the class syntax.

File

NodeJS/
 ├ src/
 │ └ Calc.js
 ├ test/
 │ └ calc.spec.js
 └ package.json

Calc.js

Calc.js


class Calc {
	add(x, y) {
		return x + y;
	}

	pow(x, y) {
		return Math.pow(x, y);
	}
}

export default Calc

calc.spec.js

js:calc.spec.js


import Calc from '../src/Calc';

const assert = require('assert');

describe('Calc', () => {
	const calc = new Calc();

	describe('add()', () => {
		assert.equal(15, calc.add(10, 5));
		assert.equal(5, calc.add(8, -3));
	});

	describe('pow', () => {
		assert.equal(125, calc.pow(5, 3));
		assert.equal(0x7FFFFFFF, calc.pow(2, 31) - 1);
	});
});

package.json

package.json


//Omission
 "scripts": {
    "test": "mocha --compilers js:babel-register --recursive $(find test -name '*.spec.js')"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "mocha": "^4.0.1"
  },
  "babel": {
    "presets": [
      "env"
    ]
  }

Execution method

Run npm test in the NodeJS folder.

PHP

Execution environment

PHP 7.1.0

Overview

There are various libraries, but this time I will use PHPUnit.

File

PHP/
 ├ src/
 │ ├ autoload.php
 │ └ Calc.php
 ├ tests/
 │ └ CalcTest.php
 ├ composer.json
 └ phpunit.xml

autoload.php

autoload.php


<?php
require_once "Calc.php";

Calc.php

Calc.php


<?php
namespace Sample;

class Calc
{
    public function add($x, $y)
    {
        return $x + $y;
    }

    public function pow($x, $y)
    {
        return $x ** $y;
    }
}

CalcTest.php

CalcTest.php


<?php
namespace Sample;

use PHPUnit\Framework\TestCase;

class CalcTest extends TestCase
{
    public $calc;

    function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct($name, $data, $dataName);
        $this->calc = new Calc();
    }

    public function testAdd()
    {
        $this->assertEquals(15, $this->calc->add(10, 5));
        $this->assertEquals(5, $this->calc->add(8, -3));
    }

    public function testPow()
    {
        $this->assertEquals(125, $this->calc->pow(5, 3));
        $this->assertEquals(0x7FFFFFFF, $this->calc->pow(2, 31) - 1);
    }
}

composer.json

composer.json


{
  //Omission
  "require": {
    "phpunit/phpunit": "6.4.4"
  }
}

phpunit.php

phpunit.php


<phpunit bootstrap="src/autoload.php">
    <testsuites>
        <testsuite name="calc">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

Execution method

Since PHPUnit can be easily executed by using each IDE, execution on the command line is unnecessary and is not described.

Go

Execution environment

Go 1.9.2

Overview

Go has a testing package as standard, so use it. ~~ At first I thought that there was no assertion system, but I was convinced for a good reason ~~

File

Go/
 └ src/
   └ sample/
     ├ calc.go
     └ calc_test.go

calc.go

calc.go


package sample

import (
	"math"
)

type Calc struct {}

func (calc *Calc) Add(x, y int) int {
	return x + y
}

func (calc *Calc) Pow(x, y float64) float64 {
	return math.Pow(x, y)
}

calc_test.go

calc_test.go


package sample_test

import (
	"testing"
	c "."
)

var calc = c.Calc{}

func TestCalc_Add(t *testing.T) {
	if calc.Add(10, 5) != 15 {
		t.Error("Add Failed");
	}
	if calc.Add(8, -3) != 5 {
		t.Error("Add Failed");
	}
}

func TestCalc_Pow(t *testing.T) {
	if calc.Pow(5, 3) != 125 {
		t.Error("Pow Failed");
	}
	if calc.Pow(2, 31) - 1 != 0x7FFFFFFF {
		t.Error("Pow Failed");
	}
}

Execution method

In the Go directory go test ./src/sample/calc_test.go Execute .

Finally

I would like to touch various languages, so I may increase it (requests are also invited)

Recommended Posts

I wrote unit tests for various languages
Decorator for unit tests using random numbers
I wrote the code for Gibbs sampling
[Python] I searched for various types! (Typing)
I want to connect to PostgreSQL from various languages
I wrote matplotlib
Give pytest clean parameters for flask unit tests
Python unit tests
I wrote an automatic kitting script for OpenBlocks IoT
How to make unit tests Part.2 Class design for tests
I wrote an automatic installation script for Arch Linux
HMAC in various languages
I wrote the code for Japanese sentence generation with DeZero
I wrote a demo program for linear transformation of a matrix
Compete for file IO in various languages and compare speeds
I just wrote the original material for the python sample code
I implemented N-Queen in various languages and measured the speed