Showing posts with label akka-http. Show all posts
Showing posts with label akka-http. Show all posts

Tuesday, July 7, 2020

Conclusion - CI/CD Series

In this series, we have covered how to implement CI/CD (continuous integration, continuous deployment) using DevOps (development and operations). We have shown how to go from a simple change in the code, to adding tests, building an assembly, planning the deployment, and eventually apply the changes to our live environment:
  1. Introduction
  2. Base Application
  3. Unit Tests
  4. Assembly
  5. PATs
  6. Plan
  7. Apply
Future enhancements to this pipeline could include:
  • Separate DEV and PROD environments
    • DEV deploy on pushes to master
    • PROD deploy on specific tag/release cycles
  • Performance tests for the REST service
  • Ability to destroy the resources using the Terraform destroy command
  • Run PATs against service deployed in the DEV environment
    • Currently, PATs are only run against the service running in-memory

Tuesday, June 16, 2020

PATs - CI/CD Series

Since we now have a fully runnable assembly (jar), we can add Product Acceptance Tests (PATs) to our automated build. PATs are a type of test which tests the product as a black-box - meaning that we work directly with the contracts defined on the exposed API without internal knowledge of the system. This allows us to test the system with more real-world style tests whereas unit tests usually go for a lot more edge-case tests for all possible input scenarios.

In our use-case, we will run our PATs against the defined REST endpoints and ensure the proper response codes and content are returned for each call. We will also simulate scenarios for our guestbook application.

Design

To help build these PATs, we are going to utilize Behavior Driven Development (BDD) Testing - specifically the Cucumber library:
Cucumber and its language Gherkin are a framework which have multiple implementations. For our use-case, we will be using the python implementation called "behave":
The reason for choosing python is just to use something different than the implementation language of our REST service. Also, it helps show that these PATs are completely separate from the actual service.

Test Setup

To run our tests, we will start our REST service as an in-memory process. This is facilitated via Cucumber with before-all and after-all setup stages:

from behave import *
import requests
import subprocess
import time

def before_all(context):
print('Starting server')
process = subprocess.Popen(['java', '-jar', 'cicd-series-assembly.jar'])
time.sleep(2)
print('Saving process to context')
context.proc = process

def after_all(context):
print('Terminating server')
context.proc.terminate()
print('Server terminated')

Running our service as an in-memory process ensures that we are running our tests against the fully built artifact from our "assemble" CI stage. Thus, these tests are running against the jar that we would push to a DEV or PROD environment instead of an one-off build.

Test Implementation

To build our tests, we write the actual test in the Gherkin language. This is a more natural language than most programming languages and can be understood without having much knowledge of its structure. Also, it uses the "Given/When/Then" style which is familiar to BDD Testing:
  • Given = setting up the service to be in a given state
  • When = the action to perform against the service
  • Then = the assertions to perform after the action
For the actual tests, we are building more real-world style use-cases - some of which are very similar to the unit tests we built previously. For example, we can build a test to ensure we cannot add a duplicate guest to our guestbook:

Scenario: conflict if a guest is added twice
Given a guestbook with one guest
When we add a guest
Then the response should be 409
And a single guest should be found with /guests

And with Cucumber, each "Given/When/Then" line maps to actual code. For the above test, our python code looks like:

from behave import *
import requests

@given('a guestbook with one guest')
def step_impl(context):
url = 'http://localhost:8080/guests'
guest = {'name': 'Dan', 'age': 31}
post_response = requests.post(url, json=guest)
assert post_response.status_code == 201
list_response = requests.get(url)
assert list_response.status_code == 200
assert 'guests' in list_response.json()
guests = list_response.json()['guests']
assert len(guests) == 1
assert guests[0] == guest

@when('we add a guest')
def step_impl(context):
url = 'http://localhost:8080/guests'
json = {'name': 'Dan', 'age': 31}
post_response = requests.post(url, json=json)
context.response = post_response

@then('the response should be 409')
def step_impl(context):
assert context.response.status_code == 409

@then('a single guest should be found with /guests')
def step_impl(context):
url = 'http://localhost:8080/guests'
guest = {'name': 'Dan', 'age': 31}
list_response = requests.get(url)
assert list_response.status_code == 200
assert 'guests' in list_response.json()
guests = list_response.json()['guests']
assert len(guests) == 1
assert guests[0] == guest

CI/CD

Now that we have our tests setup, we can plug them into our automated builds. Again, this will ensure that our system adheres to its contracts on every build and should something fail we will get automated build failure notifications.

The first step in plugging these tests into our build is to pass the built artifact from our "assemble" stage to our "pats" stage. We want to pass the built artifact between stages since we already have a dedicated stage to ensuring the build works as expected, hence, there is no reason to do the build twice. This artifact passing can be done using GitHub Actions:
Next, we want to define our PAT stage within our build. Since we are running both a Java application and Python tests, we need to choose a docker image which has all of our prerequisites installed by default (or build a custom image). Luckily, there is a docker image available which has Java 8 and Python 3 installed:
After that, we just need to install the required python dependencies and run our tests with "behave":

pats:
runs-on: ubuntu-latest
container: openkbs/jre-mvn-py3:v1.0.6
needs: assemble

steps:
- name: Checkout Repo
uses: actions/checkout@v2

# Download artifact
- name: Download Artifact
uses: actions/download-artifact@v2
with:
name: cicd-series-assembly.jar

# Verify artifact
- name: List Files
run: ls -al

# This is needed because the artifact is downloaded with the original file name (includes version)
- name: Rename Artifact
run: mv cicd-series-assembly-*.jar cicd-series-assembly.jar

# This is needed because download artifacts are not runnable
- name: Change Permissions
run: chmod a+rx cicd-series-assembly.jar

# Verify artifact
- name: List Files
run: ls -al

# Install python dependencies
- name: Install Dependencies
run: pip install -r requirements.txt

# Run behave tests
- name: Run PATs
run: behave

Conclusion

We now have added automated PATs to run on every Pull Request to the master branch of our repo. They were built using python and the Cucumber library to perform BDD Tests. Also, should anything fail, we will get automated build failure notifications.

All of the code above and more can be found on this pull request.

Sunday, June 7, 2020

Unit Tests - CI/CD Series

In the previous post we created a simple REST service built on top of akka-http. However, as practiced with professional software development, we want to add unit tests to our service to ensure everything is working as planned. These unit tests provide several things for our service:
  1. Automated testing
  2. Reproducible tests
  3. Software assurance
Unit Tests

To build the unit tests for our service, we will leverage:
  • ScalaTest
    • The base testing framework (similar to JUnit for Java)
  • akka-http
    • akka-http provides test harnesses that integrate directly with ScalaTest
With these testing libraries, we can perform tests directly against the endpoints of our service instead of using objects. Also, both the requests and responses are full payloads so we can assert things such as:
  • Response code
  • Application type
  • Response body
This will help provide a full end-to-end unit test instead of directly calling an object and ignoring the serialization aspect of the test.

The simplest endpoint in our service is the health check - it only returns 200. A unit test for this endpoint is as simple as:

it should "return OK for /health" in {
Get("/health") ~> healthCheck.route ~> check {
status shouldBe StatusCodes.OK
}
}

In this test, the actions performed are:
  1. Send a GET request with the path "/health"
  2. The request goes to the route defined in the object "healthCheck"
  3. Assert that the returned status is OK (200)
We can use this same kind of test setup for a more complex case (such as adding a guest to our guestbook):

it should "add a guest" in {
val guestBook = new GuestBook

Post("/guests").withEntity(guestEntity) ~> guestBook.route ~> check {
status shouldBe StatusCodes.Created
}

Get("/guests") ~> guestBook.route ~> check {
status shouldBe StatusCodes.OK
contentType shouldBe ContentTypes.`application/json`
entityAs[Guests] shouldBe Guests(List(guest))
}
}

This test has a similar setup as the one above, just with a few more steps:
  1. Send a POST request with the guest data (defined outside of snippet)
  2. The request goes to the route defined in the object "guestBook"
  3. Assert that the returned status is Created (201)
  4. Send a GET request with the path "/guests"
  5. The request goes to the route defined in the object "guestBook"
  6. Assert that the returned status is OK (200)
  7. Assert that the returned content type is "application/json"
  8. Assert that the returned entity is our guest we added previously (wrapped in a list)
Continuous Integration

Now that we have unit tests available, we can hook up our continuous integration using:
For this simple REST service, the actions we want to perform are:
  • Run unit tests on all pull requests to the "master" branch
  • Run unit tests on all pushes to the "master" branch
  • Running unit tests consists of
    • Using a docker image which has sbt installed
    • Running "sbt test"
The entirety of the above can be expressed with just a few lines of a YAML definition:

name: SBT CI

# Run SBT tests on pushes and pull requests to master branch
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
# https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idruns-on
runs-on: ubuntu-latest
# The specific container to use
# https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idcontainer
# https://hub.docker.com/r/hseeberger/scala-sbt/
container: hseeberger/scala-sbt:8u222_1.3.5_2.13.1

# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2

# Runs a set of commands using the runners shell
- name: Run Unit Tests
run: sbt test

Conclusion

Given the above unit tests and GitHub Actions definition, we now have a system which will run all unit tests on every build. This will not only ensure our system performs as expected, but also alert us when a build breaks for any reason.

All of the changes mentioned above (and more) can be found on this pull request.

Monday, June 1, 2020

Base Application - CI/CD Series

As discussed in the introduction, we are working on a basic REST service with the goal of implementing full end-to-end CI/CD. To help build this REST service, we are leveraging:
All of the changes have been completed and the full changeset can be found on this pull request.

The service currently has the following endpoints:
  • GET /health
    • Basic health check for the service
    • Returns 200
  • GET /guests
    • Returns all guests in the guestbook
    • Returns 200
    • Returns JSON list of guests
  • POST /guests
    • Adds a guest to the guestbook
    • Request is JSON guest {"name":"Dan", "age":31}
    • Returns 201 on creation
    • Returns 409 if the guest already exists
  • DELETE /guests/<name>
    • Deletes a guest by name
    • Returns 204 if the guest was deleted
    • Returns 404 if the guest to delete was not found
Overall, this is an extremely basic REST service, however it will serve our purposes for the rest of this CI/CD series.

In the following posts, we will start to:
  1. Add automated unit tests
  2. Run the service via a Docker image
  3. Add automated product acceptance tests (PATs)
  4. Add automated deployments to a cloud service

Wednesday, May 27, 2020

Introduction - CI/CD Series

Over the last several years, the terms CI/CD (continuous integration, continuous deployment) and DevOps (development and operations) have grown to be known throughout most of the software industry. The implication of these practices is that no longer must software wait for a "release ritual" to push a new version to production. Nor must software be developed by one team and then "handed over" to a production support team. 

Instead, now a development team manages the software from end-to-end:
  • Requirements
  • Code changes
  • Testing
  • Build and package artifacts
  • Deploy to production
  • Support
Also, software has seen a much quicker release cycles. It is even possible to have pipelines that perform releases and deployments upon every committed code change.

Throughout the next few posts, we will build a fully automated CI/CD pipeline for a simple REST service. The series will be broken down into individual posts:
  1. Introduction (this post)
  2. Base application
  3. CI for testing
  4. Dockerizing the application
  5. Product acceptance testing (PATs)
  6. CD for deployment
The tools we will be working with throughout this project will be: