应用节点和容器的关系_使用Dockunit对节点应用程序进行容器化测试

  • Post author:
  • Post category:其他


应用节点和容器的关系

This tutorial covers setting up containerized unit testing for Node applications. Containerized unit testing allows you to ensure your software works across a wide variety of platforms.

本教程涵盖为Node应用程序设置容器化单元测试。 容器化的单元测试使您可以确保您的软件可以在多种平台上运行。

总览

(

Overview

)

Writing and distributing Node.js applications necessitates supporting as many versions of Node.js as possible.

npm

, the most popular Node.js package manager, requires Node.js 0.8 or higher. Therefore to support your users, potential downloaders, or even your customers, it behooves you to test your program on Node.js versions 0.8 and up. Node.js 0.8 was released in 2012; many versions have been released since then. io.js and Node.js were combined in version 4.0.0. You have a lot of testing ground to cover!

编写和分发Node.js应用程序需要支持尽可能多的Node.js版本。

npm

是最受欢迎的Node.js软件包管理器,它要求Node.js 0.8或更高版本。 因此,为了支持您的用户,潜在的下载者甚至您的客户,您应该在Node.js 0.8及更高版本上测试程序。 Node.js 0.8于2012年发布; 从那时起,已经发布了许多版本。 io.js和Node.js在4.0.0版中合并。 您有很多需要测试的地方!

There are a few ways to run your code in multiple versions of Node.js:

n

and

nvm

are npm packages that allow you to switch between different versions of Node.js. It’s difficult quickly switch between versions to test your code. It’s also difficult to batch run your code against a list of versions. Travis CI is a continuous integration service that allows you to run your code across multiple versions of Node.js. However, you are stuck with the versions of Node.js that they want to support, or you can use their new Docker based system which is somewhat experimental and cumbersome to operate.

有几种方法可以在多个版本的Node.js中运行代码:

n



nvm

是npm软件包,允许您在不同版本的Node.js之间进行切换。 很难在版本之间快速切换以测试代码。 也很难对版本列表进行批处理运行。 Travis CI是一项持续集成服务,可让您跨多个版本的Node.js运行代码。 但是,您会被他们想要支持的Node.js版本所困扰,或者您可以使用他们的基于Docker的新系统,该系统有些实验性且操作麻烦。

Neither of these ways did the trick for me. Enter Dockunit.

这两种方式都不对我有用。 输入Dockunit。


Dockunit

is a utility for running containerized software tests.

Dockunit.io

is a continuous integration service built for Dockunit. Let’s setup Dockunit to be used with our Node.js application.


Dockunit

是用于运行容器化软件测试的实用程序。

Dockunit.io

是为Dockunit构建的持续集成服务。 让我们设置Dockunit与我们的Node.js应用程序一起使用。

Prerequisites:

先决条件:

  • A Unix based operating system such as OSX or Ubuntu.

    基于Unix的操作系统,例如OSX或Ubuntu。


  • Docker

    (boot2docker in case of OSX) A version of

    Node.js

    and npm


    Docker

    (在OSX中为boot2docker)

    Node.js

    和npm的版本

  • Basic terminal knowledge Basic knowledge of JavaScript and Node

    基本的终端知识JavaScript和Node的基本知识

第1部分:开发简单节点应用程序(如果有现有应用程序,请跳过)

(

Part 1: Develop a Simple Node Application (skip if you have an existing application)

)

We need a simple Node application to test for the purposes of this tutorial. We will write a simple app that prints out the current system time that includes one basic unit test. The code for this tutorial is available on

Github

.

为了本教程的目的,我们需要一个简单的Node应用程序进行测试。 我们将编写一个简单的应用程序,打印出包括一个基本单元测试的当前系统时间。

Github

上提供了本教程的代码。

Let’s start by creating a folder on your machine:

让我们从在计算机上创建一个文件夹开始:

/test-app

Next, let’s initialize a

package.json

file from within the

/test-app

directory. In the terminal enter:

接下来,让我们从

/test-app

目录中初始化

package.json

文件。 在终端中输入:

npm init

Just press enter on all the prompts. No need to specify all this information for our simple application. Next let’s create a file

time.js

such that our application looks like this:

只需在所有提示上按Enter。 无需为我们的简单应用程序指定所有这些信息。 接下来,我们创建一个文件

time.js

,使我们的应用程序如下所示:

/test-app
    time.js

In

time.js

paste the following code:



time.js

粘贴以下代码:

'use strict';

class Time {
    constructor() {
        this.date = new Date();

        this.hour = this.date.getHours();
        this.hour = (this.hour < 10 ? '0' : '') + this.hour;

        this.min  = this.date.getMinutes();
        this.min = (this.min < 10 ? '0' : '') + this.min;

        this.ampm = 'AM';
        if (this.hour > 12) {
            this.ampm = 'PM';
            this.hour -= 12;
        }
    }

    getPretty() {
        return 'The time is ' + this.hour + ':' + this.min + ' ' + this.ampm;  
    }
}

module.exports = Time;

This code creates a basic ES6 class to wrap the transformed JavaScript Date object into usable time information. The wrapper also let’s you print out the current time in an easy to read way.

此代码创建一个基本的ES6类,以将转换后JavaScript Date对象包装到可用的时间信息中。 包装器还让您以一种易于阅读的方式打印出当前时间。

Now let’s create the main file to utilize our time class. Create a file

index.js

like so:

现在,让我们创建主文件以利用我们的时间类。 像这样创建文件

index.js

/test-app
    index.js

In

index.js

paste the following code:



index.js

粘贴以下代码:

'use strict';

var colors = require('colors');
var Time = require('./time');

var time = new Time();

console.log(time.getPretty().green);

This code just instantiates a Time object and prints the current time to the screen.

colors

is a npm package that let’s you give your terminal output some color. We need to install the npm package for this to work. In the terminal run the following command from within the

/test-app

directory:

这段代码只是实例化一个Time对象,并将当前时间打印到屏幕上。

colors

是一个npm软件包,可让您为终端输出一些颜色。 我们需要安装npm软件包才能正常工作。 在终端中,从

/test-app

目录中运行以下命令:

npm install colors --save

Now let’s write a simple unit test with Mocha. First, install Mocha globally:

现在,让我们用Mocha编写一个简单的单元测试。 首先,在全球范围内安装Mocha:

npm install -g mocha

Now create a folder

test

and a file

time.js

inside of it like so:

现在创建一个文件夹

test

并在其中创建文件

time.js

,如下所示:

/test-app
    index.js
    time.js
    /test
        time.js

In

time.js

paste the following code:



time.js

粘贴以下代码:

'use strict';

var assert = require('assert');
var Time = require('../time');

describe('time', function() {

    describe('#constructor', function() {

        it('Object initializes hour, minute, and AM/PM', function() {
            var time = new Time();

            assert(time.hour);
            assert(time.min);
            assert(time.ampm);
        });
    });
});

This code tests up a simple unit test that instantiates a Time object and makes sure the proper instance variables are setup.

这段代码测试了一个简单的单元测试,该单元测试实例化了一个Time对象,并确保设置了正确的实例变量。

Run the following command in your terminal from the root of your project:

从项目的根目录在终端中运行以下命令:

mocha

If you have setup your tests correctly, it should show you one test is passing.

如果您正确设置了测试,则应该表明您正在通过一项测试。

That’s it! You now should have a simple node app with a basic unit test setup. Again, you can find all the code for this tutorial on

Github

.

而已! 您现在应该拥有一个带有基本单元测试设置的简单节点应用程序。 同样,您可以在

Github

上找到本教程的所有代码。

第2部分:设置坞站

(

Part 2: Setup Dockunit

)

We want our application to work across many different versions of Node since we will be distributing it publically. We need to be able to quickly run our tests locally across a number of Node versions. We also want our teammates and collaborators to be able to run the same tests without having to setup complex local environments. We will use

Dockunit

to accomplish this.

我们希望我们的应用程序可以跨许多不同版本的Node工作,因为我们将公开发布它。 我们需要能够跨多个Node版本在本地快速运行测试。 我们还希望我们的队友和协作者能够运行相同的测试,而不必设置复杂的本地环境。 我们将使用

Dockunit

完成此操作。

First, install Dockunit locally. In the terminal run the following command:

首先,在本地安装Dockunit。 在终端中运行以下命令:

npm install -g dockunit

In the root of the

test-app

folder, create the file

Dockunit.json

like so:



test-app

文件夹的根目录中,创建文件

Dockunit.json

如下所示:

/test-app
    index.js
    Dockunit.json
    time.js
    /test
        time.js

In

Dockunit.json

paste the following code:



Dockunit.json

粘贴以下代码:

{
    "containers": [
        {
            "prettyName": "Node 0.10.40",
            "image": "node:0.10.40",
            "beforeScripts": [
                "npm install",
                "npm install -g mocha"
            ],
            "testCommand": "mocha"
        },
        {
            "prettyName": "Node 0.12",
            "image": "node:0.12",
            "beforeScripts": [
                "npm install",
                "npm install -g mocha"
            ],
            "testCommand": "mocha"
        },
        {
            "prettyName": "Node Latest",
            "image": "node:latest",
            "beforeScripts": [
                "npm install",
                "npm install -g mocha"
            ],
            "testCommand": "mocha"
        }
    ]
}


Dockunit.json

files are written in JSON which is JavaScript object notation. All

Dockunit.json

files contain a root level object with a property

containers

which holds an array of objects that each describe a test to be run in a Docker container. The idea is for containers to be different real life simulations of your software so you can see how it performs in different scenarios. Here is an example container object:


Dockunit.json

文件使用JSON编写,这是JavaScript对象表示法。 所有

Dockunit.json

文件都包含带有属性

containers

的根级对象,该属性

containers

包含一个对象数组,每个对象都描述了要在Docker容器中运行的测试。 想法是使容器成为您软件的不同真实生活模拟,以便您可以查看容器在不同情况下的性能。 这是一个示例容器对象:

{
    "prettyName": My container pretty name",
    "image": "docker-image-ref",
    "beforeScripts": [
      "before-command-1",
      "before-command-2"
    ],
    "testCommand": "my-command"
}


prettyName

is just an easy way for you to describe your container which will be useful in build output.

image

refers to a

Docker Hub

image. Dockunit comes with a bunch of

predefined images that you can use

, however you can always create your own.

beforeScripts

allows you to run commands in the Docker container before the test command is run.

testCommand

is the command whose exit code will be evaluated to determine whether your software “passes” or not.


prettyName

是描述容器的简便方法,这对构建输出很有用。

image

是指

Docker Hub

映像。 Dockunit附带了一堆

可以使用



预定义图像

,但是您始终可以创建自己的图像。

beforeScripts

允许您在运行test命令之前在Docker容器中运行命令。

testCommand

是将评估其退出代码以确定您的软件是否“通过”的命令。

This particular

Dockunit.json

file describes three containers, one for Node 0.10.40, Node 0.12, and the latest version of Node. Let’s run Dockunit. In the terminal run the following command from the root of your

test-app

folder:

这个特定的

Dockunit.json

文件描述了三个容器,一个容器用于Node 0.10.40,Node 0.12和最新版本的Node。 让我们运行Dockunit。 在终端中,从

test-app

文件夹的根目录运行以下命令:

dockunit

The first time you run the command it will take a few minutes to download all the relevant Docker images. Subsequent runs will be much faster. You should see your test output for all three containers. If you are using the example application, 1 out of the 3 containers will show as passed.

首次运行该命令时,将花费几分钟时间下载所有相关的Docker映像。 随后的运行将更快。 您应该看到所有三个容器的测试输出。 如果使用示例应用程序,则3个容器中的1个将显示为已通过。

What happened?

发生了什么?

Well, in

test-app/time.js

we are using ES6 class style syntax which is only available in newer versions of Node. Let’s refactor our code to make it more compatible with older versions of Node. Paste the following code into

test-app/time.js

:

好吧,在

test-app/time.js

我们使用的是ES6类样式语法,该语法仅在较新版本的Node中可用。 让我们重构代码,使其与旧版本的Node更加兼容。 将以下代码粘贴到

test-app/time.js

'use strict';

function Time() {
    this.date = new Date();

    this.hour = this.date.getHours();
    this.hour = (this.hour < 10 ? '0' : '') + this.hour;

    this.min  = this.date.getMinutes();
    this.min = (this.min < 10 ? '0' : '') + this.min;

    this.ampm = 'AM';
    if (this.hour > 12) {
        this.ampm = 'PM';
        this.hour -= 12;
    }
}

Time.prototype.getPretty = function() {
    return 'The time is ' + this.hour + ':' + this.min + ' ' + this.ampm;  
}

module.exports = Time;

Rerun Dockunit by running the following command in your terminal from the project root:

通过在终端中从项目根目录运行以下命令来重新运行Dockunit:

dockunit

Now all your containers should be passing. See how easy it is test your code against multiple versions of Node? Since the images are distributable and live on Docker Hub, anyone can run Dockunit on your project without setting up a local environment.

现在您所有的容器都应该通过了。 看到针对多个版本的Node测试代码有多么容易? 由于映像是可分发的,并且可以在Docker Hub上运行,因此任何人都可以在您的项目上运行Dockunit,而无需设置本地环境。

第3部分:使用Dockunit.io设置持续集成

(

Part 3: Setup Continuous Integration with Dockunit.io

)

Now that we’ve setup Dockunit for our project and pushed to Github, we can set up continuous integration on

Dockunit.io

so Dockunit tests are run on each pull request and push to the repository. If a pull request or push fails, a failed status will be shown on Github so we can fix our software.

现在我们已经为项目设置了Dockunit并将其推送到Github,我们可以在

Dockunit.io

上设置持续集成,以便在每个pull请求上运行Dockunit测试并将其推送到存储库。 如果拉取请求或推入失败,则Github上将显示失败状态,以便我们修复软件。

First,

create an account

on Dockunit.io.

首先,在Dockunit.io上

创建一个帐户

Next, go to

projects

and integrate your account with Github:

接下来,转到

项目

并将您的帐户与Github集成:

dockunit-authorized-github

Within Dockunit.io,

create a project

for your Github repository:

在Dockunit.io中,为您的Github存储库

创建一个项目

dockunit-new-project

That’s it! You can now see the build status of your project. It will update automatically when you push to Github:

而已! 现在,您可以查看项目的构建状态。 当您按下Github时,它将自动更新:

dockunit-dash

Within Github, you can see the Dockunit build status within each Pull Request:

在Github中,您可以在每个Pull Request中看到Dockunit的构建状态:

dockunit-test

结论

(

Conclusion

)

In this tutorial we have created a simple Node application, setup Dockunit for local containerized unit testing, and integrated our project’s Github repository with

Dockunit.io

for continuous containerized integration testing. Containerized software testing is the future of assuring code integrity. Give it a try!

在本教程中,我们创建了一个简单的Node应用程序,设置了Dockunit以进行本地容器化单元测试,并将我们项目的Github存储库与

Dockunit.io

集成在一起以进行连续的容器化集成测试。 容器化软件测试是确保代码完整性的未来。 试试看!

翻译自:

https://scotch.io/tutorials/containerized-testing-for-node-applications-with-dockunit

应用节点和容器的关系