text:
//
// DateTimeExtensions.cs
//
// Author:
//       Ehouarn Perret <ehouarn.perret@outlook.com>
//
// Copyright (c) Ehouarn Perret
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace EhouarnPerret.CSharp.Utilities.Core
{
    public static class DateTimeExtensions
    {
        private const string DateTimeIsoStringFormat = @"yyyy-MM-dd HH:mm:ss.fff";
        private const string DateIsoStringFormat = @"yyyy-MM-dd";
        private const string TimeIsoStringFormat = @"HH:mm:ss.fff";

        public static IEnumerable<DateTime> OnWeekends(this IEnumerable<DateTime> source)
        {
            return source.Where (item => item.IsWeekend ());
        }
        public static IEnumerable<DateTime> OnNonWeekends (this IEnumerable<DateTime> source)
        {
            return source.Where (item => item.IsNotWeekend ());
        }

        public static DateTime NextDay(this DateTime dateTime)
        {
            return dateTime.AddDays(1);
        }
        public static DateTime PreviousDay(this DateTime dateTime)
        {
            return dateTime.AddDays(-1);
        }

        public static DateTime NextMonth(this DateTime dateTime)
        {
            return dateTime.AddMonths(1);
        }
        public static DateTime PreviousMonth(this DateTime dateTime)
        {
            return dateTime.AddMonths(-1);
        }

        public static DateTime NextYear(this DateTime dateTime)
        {
            return dateTime.AddYears(1);
        }
        public static DateTime PreviousYear(this DateTime dateTime)
        {
            return dateTime.AddYears(-1);
        }

        public static bool IsWeekend(this DateTime dateTime)
        {
            return dateTime.DayOfWeek.IsIn(DayOfWeek.Saturday, DayOfWeek.Sunday);
        }
        public static bool IsNotWeekend(this DateTime dateTime)
        {
            return !dateTime.IsWeekend();
        }

        public static string ToInvariantIsoString(this DateTime dateTime)
        {
            return dateTime.ToIsoString(CultureInfo.InvariantCulture);
        }
        public static string ToIsoString(this DateTime dateTime, IFormatProvider formatProvider)
        {
            return dateTime.ToString(DateTimeIsoStringFormat, formatProvider);
        }

        public static string ToInvariantIsoDateString(this DateTime dateTime)
        {
            return dateTime.ToIsoDatetring(CultureInfo.InvariantCulture);
        }
        public static string ToIsoDatetring(this DateTime dateTime, IFormatProvider formatProvider)
        {
            return dateTime.ToString(DateIsoStringFormat, formatProvider);
        }

        public static string ToInvariantIsoTimeString(this DateTime dateTime)
        {
            return dateTime.ToIsoTimeString(CultureInfo.InvariantCulture);
        }
        public static string ToIsoTimeString(this DateTime dateTime, IFormatProvider formatProvider)
        {
            return dateTime.ToString(TimeIsoStringFormat, formatProvider);
        }

        public static IEnumerable<DateTime> AsEnumerable(this DateTime start, DateTime stop, TimeSpan interval)
        {
            interval.ThrowIfStrictlyLesserThan(TimeSpan.Zero);

            var current = start.ThrowIfGreaterThan(stop);

            while (current <= stop)
            {
                yield return current;
                current = current.Add(interval);
            }
        }

        public static IEnumerable<DateTime> AsEnumerableDays(this DateTime start, DateTime stop, double interval = 1)
        {
            return start.AsEnumerable(stop, TimeSpan.FromDays(interval));
        }

        public static IEnumerable<DateTime> AsEnumerableHours(this DateTime start, DateTime stop, double interval = 1)
        {
            return start.AsEnumerable(stop, TimeSpan.FromHours(interval));
        }

        public static IEnumerable<DateTime> AsEnumerableMinutes(this DateTime start, DateTime stop, double interval = 1)
        {
            return start.AsEnumerable(stop, TimeSpan.FromMinutes(interval));
        }

        public static IEnumerable<DateTime> AsEnumerableSeconds(this DateTime start, DateTime stop, double interval = 1)
        {
            return start.AsEnumerable(stop, TimeSpan.FromSeconds(interval));
        }

        public static IEnumerable<DateTime> AsEnumerableMilliseconds(this DateTime start, DateTime stop, double interval = 1)
        {
            return start.AsEnumerable(stop, TimeSpan.FromMilliseconds(interval));
        }
    }
}


text:
import gluon.contrib.simplejson

# main overview of snippets
def index():
    response.flash = T('Navigate on the right to see the snippets on the left.')
    response.title = T('Code Snippets')
    files = db(db.snippet).select().as_list()
    return dict(files=gluon.contrib.simplejson.dumps(files))

# function to return code files
def snippets():
    files = ""
    if request.vars.values():
        files = request.vars.values()
    return dict(files=files)

def preview():
    snippet_id = request.args[0]
    filePreview = db(db.snippet.id==snippet_id).select().as_list()
    return dict(filePreview=filePreview)

redpajama_set_name: RedPajamaGithub


text:
package com.radaee.reader;

import java.io.File;
import java.io.FileOutputStream;

import com.radaee.pdf.Document;
import com.radaee.pdf.Global;
import com.radaee.pdf.Matrix;
import com.radaee.pdf.Page;
import com.radaee.util.PDFAESEnc;
import com.radaee.util.PDFAESStream;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Bitmap.Config;
import android.os.Bundle;

public class PDFEncAct extends Activity
{
	private PDFAESStream m_stream;
	private Document m_doc;
    private ReaderController m_vPDF = null;
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Global.Init( this );

        //encrypt PDF file first
        //the key must 16 bytes long.
        byte[] key = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16};
        PDFAESEnc.encrypt("/sdcard/src.pdf", "/sdcard/dst.pdf", key);

        //using PDFAESStream to decrypt PDF file.
        m_stream = new PDFAESStream();
        if( !m_stream.open("/sdcard/dst.pdf", key) )
        	return;
        m_doc = new Document();
		int ret = m_doc.OpenStream(m_stream, null);
		switch( ret )
		{
		case -1://need input password
			finish();
			break;
		case -2://unknown encryption
			finish();
			break;
		case -3://damaged or invalid format
			finish();
			break;
		case -10://access denied or invalid file path
			finish();
			break;
		case 0://succeeded, and continue
			break;
		default://unknown error
			finish();
			break;
		}
		m_vPDF = new ReaderController(this);
		m_vPDF.open(m_doc);
        setContentView(m_vPDF);
	}
    protected void onDestroy()
    {
    	if( m_doc != null )
    	{
    		m_doc.Close();
    		m_doc = null;
    	}
    	if( m_stream != null )
    	{
    		m_stream.close();
    		m_stream = null;
    	}
    	Global.RemoveTmp();
    	super.onDestroy();
    }
}


text:
You should see a 100x100 green square below enclosed by an olive border.  If you see any red, the test has failed. If the border does not fully enclose the green square, then the test has failed.

This test is checking to make sure blocks with auto height that are children of boxes will expand to encompass overhanging floats.


text:
""" ./examples/display_name/display_name.rst"""

from hamcrest import assert_that
from allure_commons_test.report import has_test_case
from allure_commons_test.result import has_title
from allure_commons_test.label import has_label

def test_display_name(executed_docstring_path):
    assert_that(executed_docstring_path.allure_report,
                has_test_case("test_display_name",
                              has_title("A some test title")
                              )
                )

def test_display_name_template(executed_docstring_path):
    assert_that(executed_docstring_path.allure_report,
                has_test_case("test_display_name_template",
                              has_title("A some test title with param False")
                              )
                )

def test_unicode_display_name(executed_docstring_source):
    """
    >>> import allure

    >>> @allure.title(u"Лунтик")
    >>> def test_unicode_display_name_example():
    ...     pass
    """

    assert_that(executed_docstring_source.allure_report,
                has_test_case("test_unicode_display_name_example", has_title(u"Лунтик"))
                )

def test_unicode_display_name_template(executed_docstring_source):
    """
    >>> import allure
    >>> import pytest

    >>> @allure.title(u"Тест с шаблоном и параметром: {param}")
    ... @pytest.mark.parametrize("param", [False])
    ... def test_unicode_display_name_template_example(param):
    ...     assert param
    """

    assert_that(executed_docstring_source.allure_report,
                has_test_case("test_unicode_display_name_template_example",
                              has_title(u"Тест с шаблоном и параметром: False")
                              )
                )

def test_fixture_value_in_display_name(executed_docstring_source):
    """
    >>> import allure
    >>> import pytest

    >>> @pytest.fixture
    ... def fix():
    ...     return 'fixture value'

    >>> @allure.title('title with {fix}')
    ... def test_fixture_value_name(fix):
    ...     pass
    """

    assert_that(executed_docstring_source.allure_report,
                has_test_case("test_fixture_value_name",
                              has_title("title with fixture value")
                              )
                )

def test_display_name_with_features(allured_testdir):
    allured_testdir.testdir.makepyfile("""
        import allure
        import pytest

        @allure.feature('Feature 1')
        @allure.title('Titled test with features')
        @allure.feature('Feature 2')
        def test_feature_label_for_titled_test():
            pass
        """)

    allured_testdir.run_with_allure()

    assert_that(allured_testdir.allure_report,
                has_test_case("test_feature_label_for_titled_test",
                              has_label("feature", "Feature 1"),
                              has_label("feature", "Feature 2"),
                              has_title("Titled test with features")
                              )
                )

def test_failed_fixture_value_in_display_name(executed_docstring_source):
    """
    >>> import allure
    >>> import pytest

    >>> @pytest.fixture
    ... def fix():
    ...     raise AssertionError("Fixture failed for some reason")

    >>> @allure.title('title with {fix}')
    ... def test_fixture_value_name(fix):
    ...     pass
    """

    assert_that(executed_docstring_source.allure_report,
                has_test_case("test_fixture_value_name",
                              has_title("title with {fix}")
                              )
                )


text:
package com.adverserealms.astar.basic2d

import scala.collection.immutable.List
import scala.collection.mutable.ListBuffer
import com.adverserealms.astar.core._
import com.adverserealms.astar.basic2d._
import org.slf4j.{ Logger, LoggerFactory }

class MockSquareGridMap extends AstarMap {

  protected lazy val log = LoggerFactory.getLogger(getClass())

  private val MAP_WIDTH = 4

  private val MAP_HEIGHT: Int = 4

  private val tiles: List[MockSquareTile] = populateMockTiles()

  private val diagonalMultiplier = 1.4d

  private val normalMultiplier = 1.0d

  private val defaultCost = 1.0d

  /**
   * Map: x's are not walkable
   *
   * 0000
   * 0xx0
   * 0xx0
   * 0000
   */
  def populateMockTiles(): List[MockSquareTile] = {
    val tiles = new ListBuffer[MockSquareTile]

    for (y <- 0 until MAP_HEIGHT) {
      for (x <- 0 until MAP_WIDTH) {
        val tile = new MockSquareTile(new Point(x, y))

        if (x == 1 && y == 1) {
          tile.setWalkable(false)
        }
        if (x == 2 && y == 1) {
          tile.setWalkable(false)
        }
        if (x == 1 && y == 2) {
          tile.setWalkable(false)
        }
        if (x == 2 && y == 2) {
          tile.setWalkable(false)
        }

        tiles += tile
      }
    }

    tiles.toList
  }

  def getNeighbors(tile: AstarTile): List[AstarTile] = {
    val neighbors = new ListBuffer[AstarTile]

    val position = tile.asInstanceOf[PositionTile].getPosition()

    val x = position.getX
    val y = position.getY

    //up, left
    if (getTile(x - 1, y - 1) != null) {
      neighbors += getTile(x - 1, y - 1)
    }
    //up
    if (getTile(x, y - 1) != null) {
      neighbors += getTile(x, y - 1)
    }
    //up, right
    if (getTile(x + 1, y - 1) != null) {
      neighbors += getTile(x + 1, y - 1)
    }
    //left
    if (getTile(x - 1, y) != null) {
      neighbors += getTile(x - 1, y)
    }
    //right
    if (getTile(x + 1, y) != null) {
      neighbors += getTile(x + 1, y)
    }
    //down, left
    if (getTile(x - 1, y + 1) != null) {
      neighbors += getTile(x - 1, y + 1)
    }
    //down
    if (getTile(x, y + 1) != null) {
      neighbors += getTile(x, y + 1)
    }
    //down, right
    if (getTile(x + 1, y + 1) != null) {
      neighbors += getTile(x + 1, y + 1)
    }

    neighbors.toList
  }

  def getTile(x: Int, y: Int): MockSquareTile = {
    if (x < 0 || x >= MAP_WIDTH) {
      null
    }
    else if (y < 0 || y >= MAP_HEIGHT) {
      null
    }
    else {
      tiles(x + (y * MAP_WIDTH))
    }
  }

  def getHeuristic(tile: AstarTile, req: AstarPathRequest): Float = {
    val start = tile.asInstanceOf[PositionTile].getPosition()
    val end = req.end.asInstanceOf[PositionTile].getPosition()

    //using a diagonal distance heuristic
    val distance: Point = getXYDistanceBetweenPoints(start, end);

    var h = scala.math.max(distance.getX, distance.getY)

    h
  }

  def getXYDistanceBetweenPoints(start: Point, end: Point): Point = {
    new Point(getAxisDistance(start.getX, end.getX), getAxisDistance(start.getY, end.getY))
  }

  private def getAxisDistance(start: Int, end: Int): Int = {
    scala.math.abs(start - end)
  }

  def getDistance(start: AstarTile, end: AstarTile): Float = {
    val startP = start.asInstanceOf[PositionTile].getPosition()
    val endP = end.asInstanceOf[PositionTile].getPosition()

    if (startP.getX != endP.getX && startP.getY != endP.getY) {
      //diagonal move
      1.4f
    }
    else {
      1.0f
    }
  }

}


text:
<?php

namespace Reach\Mongo;

use Reach\PaginatorInterface;
use stdClass;

class Paginator implements PaginatorInterface
{

    protected $_limit;

    protected $_resultSet;

    protected $_current_page;

    /**
     * @param ResultSet $resultSet
     * @param int       $limit
     * @param int       $current_page
     */
    public function __construct(ResultSet $resultSet, $limit = 10, $current_page = 1)
    {
        $this->_resultSet = $resultSet;
        $this->_current_page = max((int)$current_page, 0);
        $this->_limit = max((int)$limit, 0);
    }

    /**
     * Set the current page number
     * @param int $number
     * @return Paginator
     */
    public function setCurrentPage($number)
    {
        $this->_current_page = max((int)$number, 0);
        return $this;
    }

    /**
     * Returns a slice of the ResultSet for the pagination
     * @return stdClass with properties: first, current, next, prev, last, pages, items
     */
    public function getPaginate()
    {
        $page = new stdClass();
        $number_of_items = $this->_resultSet->count();
        $total_pages = ceil($number_of_items / $this->_limit);

        $page->first = 1;
        $page->current = $this->_current_page;
        $page->next = $this->_current_page < $total_pages ? $this->_current_page + 1 : $total_pages;
        $page->prev = $this->_current_page > 1 ? $this->_current_page - 1 : 1;
        $page->last = $total_pages;
        $page->pages = $total_pages;
        $page->total_items = $number_of_items;
        $page->items = $this->_resultSet
            ->skip($this->_limit * ($this->_current_page - 1))
            ->limit($this->_limit);

        return $page;
    }

    /**
     * Set rows limit
     * @param int $limit
     * @return Paginator
     */
    public function setLimit($limit)
    {
        $this->_limit = max((int)$limit, 0);
        return $this;
    }

    /**
     * Get current rows limit
     * @return int $limit
     */
    public function getLimit()
    {
        return $this->_limit;
    }

    /**
     * Get current page number
     */
    public function getCurrentPage()
    {
        return $this->_current_page;
    }

    /**
     * @param ResultSet $resultSet
     * @return Paginator
     */
    public function setResultSet(ResultSet $resultSet)
    {
        $this->_resultSet = $resultSet;
        return $this;
    }

    /**
     * @return Paginator
     */
    public function getResultSet()
    {
        return $this->_resultSet;
    }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**dataAmount** | **Long** | Amount of data allowed to be transfered |  [optional]
**dataUnit** | **String** | Unit of data allowed to be transfered. Allowed values are \"KB\", \"MB\" and \"GB\" |  [optional]


text:
android-toolbox
===============


text:
set -eE -u -o pipefail # Fail on error, call ERR trap

automated_build=${AUTOMATED_BUILD:-}
gopath=${GOPATH:-}
kbfs_dir="$gopath/src/github.com/keybase/client/go/kbfs"
client_dir="$gopath/src/github.com/keybase/client"
shared_dir="$gopath/src/github.com/keybase/client/shared"
ios_dir="$gopath/src/github.com/keybase/client/shared/ios"
clean=${CLEAN:-}
cache_npm=${CACHE_NPM:-}
cache_go_lib=${CACHE_GO_LIB:-}
client_commit=${CLIENT_COMMIT:-}
kbfs_commit=${KBFS_COMMIT:-}
check_ci=${CHECK_CI:-1}

# Notify Slack on failure
function notify_slack {
  if [ -n "$automated_build" ]; then
    "$client_dir/packaging/slack/send.sh" "<@channel> Automated iOS build failed, please check out the log."
  fi
}
trap notify_slack ERR

# Reset on exit
kbfs_branch=`cd "$kbfs_dir" && git rev-parse --abbrev-ref HEAD`
client_branch=`cd "$client_dir" && git rev-parse --abbrev-ref HEAD`
rn_packager_pid=""
function reset {
  (cd "$kbfs_dir" && git checkout $kbfs_branch)
  (cd "$client_dir" && git checkout $client_branch)
  (cd "$client_dir" && git checkout shared/ios/)

  if [ ! "$rn_packager_pid" = "" ]; then
    echo "Killing packager $rn_packager_pid"
    pkill -P $rn_packager_pid || true
  fi
}
trap reset EXIT

if [ -n "$kbfs_commit" ]; then
  cd "$kbfs_dir"
  echo "Checking out $kbfs_commit on kbfs (will reset to $kbfs_branch)"
  git fetch
  git reset --hard
  git clean -f
  git checkout "$kbfs_commit"
  # tell gobuild.sh (called via "yarn run rn-gobuild-ios" below) to use our local commit
  export LOCAL_KBFS=1
fi

cd "$kbfs_dir"
echo "Recent KBFS commit log"
git log -n 3

if [ -n "$client_commit" ]; then
  cd "$client_dir"
  echo "Checking out $client_commit on client (will reset to $client_branch)"
  git fetch
  git reset --hard
  git clean -f
  git checkout "$client_commit"
else
  "$client_dir/packaging/check_status_and_pull.sh" "$client_dir"
fi

cd "$client_dir"
echo "Recent client commit log"
git log -n 3

cd "$shared_dir"

echo "Cleaning up main node_modules from previous runs"
rm -rf node_modules
yarn modules
echo "Ensuring correct"
yarn --check-files

echo "Cocoapods"
cd ios
pod install --repo-update
cd ..

if [ ! "$cache_go_lib" = "1" ]; then
  echo "Building Go library"
  CHECK_CI="$check_ci" yarn run rn-gobuild-ios
fi

"$client_dir/packaging/manage_react_native_packager.sh" &
rn_packager_pid=$!
echo "Packager running with PID $rn_packager_pid"

# Build and publish the apk
cd "$ios_dir"
if [ -n "$clean" ]; then
    xcodebuild clean -workspace "Keybase.xcworkspace" -scheme "Keybase"
fi

# fastlane wants these set
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
fastlane ios beta

"$client_dir/packaging/slack/send.sh" "Finished releasing ios"


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Web.UI
{
  sealed public partial class PageAsyncTask
  {
    #region Methods and constructors
    public PageAsyncTask (System.Web.BeginEventHandler beginHandler, System.Web.EndEventHandler endHandler, System.Web.EndEventHandler timeoutHandler, Object state)
    {
    }

    public PageAsyncTask (System.Web.BeginEventHandler beginHandler, System.Web.EndEventHandler endHandler, System.Web.EndEventHandler timeoutHandler, Object state, bool executeInParallel)
    {
    }
    #endregion

    #region Properties and indexers
    public System.Web.BeginEventHandler BeginHandler
    {
      get
      {
        return default(System.Web.BeginEventHandler);
      }
    }

    public System.Web.EndEventHandler EndHandler
    {
      get
      {
        return default(System.Web.EndEventHandler);
      }
    }

    public bool ExecuteInParallel
    {
      get
      {
        return default(bool);
      }
    }

    public Object State
    {
      get
      {
        return default(Object);
      }
    }

    public System.Web.EndEventHandler TimeoutHandler
    {
      get
      {
        return default(System.Web.EndEventHandler);
      }
    }
    #endregion
  }
}


text:
package simulation

import (
	"errors"
	"io/ioutil"
	"testing"
	"time"

	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strconv"

	"github.com/3dsim/auth0/auth0fakes"
	"github.com/3dsim/simulation-goclient/models"
	"github.com/go-openapi/swag"
	"github.com/gorilla/mux"
	"github.com/stretchr/testify/assert"
)

const (
	audience = "test audience"
)

func TestMachineWhenFetcherErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	machineID := int32(2)
	expectedError := errors.New("Some auth0 error")

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("", expectedError)

	client := NewClient(fakeTokenFetcher, "apiGatewayURL", "", audience)

	// act
	_, err := client.Machine(machineID)

	// assert

	assert.Equal(t, expectedError, err, "Expected an error returned")
}

func TestMachineWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	machineID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Machine
	machineHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	machineEndpoint := "/" + SimulationAPIBasePath + "/machines/{machineID}"
	r.HandleFunc(machineEndpoint, machineHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.Machine(machineID)

	// assert

	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestMachineWhenSuccessfulExpectsMachineReturned(t *testing.T) {
	// arrange
	machineID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Machine
	machineToReturn := &models.Machine{
		ID:   swag.Int32(machineID),
		Name: swag.String("Machine name"),
	}
	machineHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedMachineID, err := strconv.Atoi(mux.Vars(r)["machineID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(machineID), receivedMachineID, "Expected machine id received to match what was passed in")
		bytes, err := json.Marshal(machineToReturn)
		if err != nil {
			t.Error("Failed to marshal machine")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	machineEndpoint := "/" + SimulationAPIBasePath + "/machines/{machineID}"
	r.HandleFunc(machineEndpoint, machineHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	machine, err := client.Machine(machineID)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *machineToReturn.Name, *machine.Name, "Expected names to match")
	assert.Equal(t, *machineToReturn.ID, *machine.ID, "Expected IDs to match")
}

// Materials
func TestMaterialWhenFetcherErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	materialID := int32(2)
	expectedError := errors.New("Some auth0 error")

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("", expectedError)

	client := NewClient(fakeTokenFetcher, "", "", audience)

	// act
	_, err := client.Material(materialID)

	// assert

	assert.Equal(t, expectedError, err, "Expected an error returned")
}

func TestMaterialWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	materialID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Material
	materialHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	materialEndpoint := "/" + SimulationAPIBasePath + "/materials/{materialID}"
	r.HandleFunc(materialEndpoint, materialHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.Material(materialID)

	// assert

	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestMaterialWhenSuccessfulExpectsMaterialReturned(t *testing.T) {
	// arrange
	materialID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Material
	materialToReturn := &models.Material{
		ID:   swag.Int32(materialID),
		Name: swag.String("Material name"),
	}
	materialHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedMaterialID, err := strconv.Atoi(mux.Vars(r)["materialID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(materialID), receivedMaterialID, "Expected material id received to match what was passed in")
		bytes, err := json.Marshal(materialToReturn)
		if err != nil {
			t.Error("Failed to marshal material")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	materialEndpoint := "/" + SimulationAPIBasePath + "/materials/{materialID}"
	r.HandleFunc(materialEndpoint, materialHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	material, err := client.Material(materialID)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *materialToReturn.Name, *material.Name, "Expected names to match")
	assert.Equal(t, *materialToReturn.ID, *material.ID, "Expected IDs to match")
}

// Simulations
func TestSimulationWhenFetcherErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	simulationID := int32(2)
	expectedError := errors.New("Some auth0 error")

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("", expectedError)

	client := NewClient(fakeTokenFetcher, "", "", audience)

	// act
	_, err := client.Simulation(simulationID)

	// assert

	assert.Equal(t, expectedError, err, "Expected an error returned")
}

func TestSimulationWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	simulationID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Simulation
	simulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	simulationEndpoint := "/" + SimulationAPIBasePath + "/simulations/{simulationID}"
	r.HandleFunc(simulationEndpoint, simulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.Simulation(simulationID)

	// assert

	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestSimulationWhenSuccessfulExpectsSimulationReturned(t *testing.T) {
	// arrange
	simulationID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Simulation
	simulationToReturn := &models.Simulation{
		ID:    simulationID,
		Title: swag.String("Simulation name"),
	}
	simulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedSimulationID, err := strconv.Atoi(mux.Vars(r)["simulationID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(simulationID), receivedSimulationID, "Expected simulation id received to match what was passed in")
		bytes, err := json.Marshal(simulationToReturn)
		if err != nil {
			t.Error("Failed to marshal simulation")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	simulationEndpoint := "/" + SimulationAPIBasePath + "/simulations/{simulationID}"
	r.HandleFunc(simulationEndpoint, simulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	simulation, err := client.Simulation(simulationID)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *simulationToReturn.Title, *simulation.Title, "Expected names to match")
	assert.Equal(t, simulationToReturn.ID, simulation.ID, "Expected IDs to match")
}

// ThermalSimulations
func TestThermalSimulationWhenFetcherErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	thermalSimulationID := int32(2)
	expectedError := errors.New("Some auth0 error")

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("", expectedError)

	thermalSimulationService := NewClient(fakeTokenFetcher, "", "", audience)

	// act
	_, err := thermalSimulationService.ThermalSimulation(thermalSimulationID)

	// assert

	assert.Equal(t, expectedError, err, "Expected an error returned")
}

func TestThermalSimulationWhenThermalSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	thermalSimulationID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// ThermalSimulation
	thermalSimulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	thermalSimulationEndpoint := "/" + SimulationAPIBasePath + "/thermalsimulations/{thermalSimulationID}"
	r.HandleFunc(thermalSimulationEndpoint, thermalSimulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	thermalSimulationService := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := thermalSimulationService.ThermalSimulation(thermalSimulationID)

	// assert

	assert.NotNil(t, err, "Expected an error returned because thermalSimulation api send a 500 error")
}

func TestThermalSimulationWhenSuccessfulExpectsThermalSimulationReturned(t *testing.T) {
	// arrange
	thermalSimulationID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// ThermalSimulation
	thermalSimulationToReturn := &models.ThermalSimulation{
		Simulation: models.Simulation{
			ID:    thermalSimulationID,
			Title: swag.String("ThermalSimulation name"),
		},
		PartBasedSimulationParameters: models.PartBasedSimulationParameters{
			ElasticModulus: swag.Float64(10),
		},
		ThermalSimulationParameters: models.ThermalSimulationParameters{
			AnisotropicStrainCoefficientsParallel:      swag.Float64(21),
			AnisotropicStrainCoefficientsPerpendicular: swag.Float64(22),
			AnisotropicStrainCoefficientsZ:             swag.Float64(23),
		},
	}
	thermalSimulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedThermalSimulationID, err := strconv.Atoi(mux.Vars(r)["thermalSimulationID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(thermalSimulationID), receivedThermalSimulationID, "Expected thermalSimulation id received to match what was passed in")
		bytes, err := json.Marshal(thermalSimulationToReturn)
		if err != nil {
			t.Error("Failed to marshal thermalSimulation")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	thermalSimulationEndpoint := "/" + SimulationAPIBasePath + "/thermalsimulations/{thermalSimulationID}"
	r.HandleFunc(thermalSimulationEndpoint, thermalSimulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	thermalSimulationService := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	thermalSimulation, err := thermalSimulationService.ThermalSimulation(thermalSimulationID)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *thermalSimulationToReturn.Title, *thermalSimulation.Title, "Expected names to match")
	assert.Equal(t, thermalSimulationToReturn.ID, thermalSimulation.ID, "Expected IDs to match")
	assert.EqualValues(t, *thermalSimulationToReturn.ElasticModulus, *thermalSimulation.ElasticModulus, "Expected ElasticModulus values to match")
	assert.EqualValues(t,
		*thermalSimulationToReturn.AnisotropicStrainCoefficientsParallel,
		*thermalSimulation.AnisotropicStrainCoefficientsParallel,
		"Expected AnisotropicStrainCoefficientsParallel values to match")
}

// ScanPatternSimulations
func TestScanPatternSimulationWhenFetcherErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	scanPatternSimulationID := int32(2)
	expectedError := errors.New("Some auth0 error")

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("", expectedError)

	scanPatternSimulationService := NewClient(fakeTokenFetcher, "", "", audience)

	// act
	_, err := scanPatternSimulationService.ScanPatternSimulation(scanPatternSimulationID)

	// assert

	assert.Equal(t, expectedError, err, "Expected an error returned")
}

func TestScanPatternSimulationWhenScanPatternSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	scanPatternSimulationID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// ScanPatternSimulation
	scanPatternSimulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	scanPatternSimulationEndpoint := "/" + SimulationAPIBasePath + "/scanpatternsimulations/{scanPatternSimulationID}"
	r.HandleFunc(scanPatternSimulationEndpoint, scanPatternSimulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	scanPatternSimulationService := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := scanPatternSimulationService.ScanPatternSimulation(scanPatternSimulationID)

	// assert

	assert.NotNil(t, err, "Expected an error returned because scanPatternSimulation api send a 500 error")
}

func TestScanPatternSimulationWhenSuccessfulExpectsScanPatternSimulationReturned(t *testing.T) {
	// arrange
	scanPatternSimulationID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// ScanPatternSimulation
	scanPatternSimulationToReturn := &models.ScanPatternSimulation{
		Simulation: models.Simulation{
			ID:    scanPatternSimulationID,
			Title: swag.String("ScanPatternSimulation name"),
		},
		PartBasedSimulationParameters: models.PartBasedSimulationParameters{
			ElasticModulus: swag.Float64(10),
		},
		ScanPatternSimulationParameters: models.ScanPatternSimulationParameters{
			LayerThickness: swag.Float64(21),
		},
	}
	scanPatternSimulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedScanPatternSimulationID, err := strconv.Atoi(mux.Vars(r)["scanPatternSimulationID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(scanPatternSimulationID), receivedScanPatternSimulationID, "Expected scanPatternSimulation id received to match what was passed in")
		bytes, err := json.Marshal(scanPatternSimulationToReturn)
		if err != nil {
			t.Error("Failed to marshal scanPatternSimulation")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	scanPatternSimulationEndpoint := "/" + SimulationAPIBasePath + "/scanpatternsimulations/{scanPatternSimulationID}"
	r.HandleFunc(scanPatternSimulationEndpoint, scanPatternSimulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	scanPatternSimulationService := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	scanPatternSimulation, err := scanPatternSimulationService.ScanPatternSimulation(scanPatternSimulationID)

	// assert
	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *scanPatternSimulationToReturn.Title, *scanPatternSimulation.Title, "Expected names to match")
	assert.Equal(t, scanPatternSimulationToReturn.ID, scanPatternSimulation.ID, "Expected IDs to match")
	assert.EqualValues(t, *scanPatternSimulationToReturn.ElasticModulus, *scanPatternSimulation.ElasticModulus, "Expected ElasticModulus values to match")
	assert.EqualValues(t, *scanPatternSimulationToReturn.LayerThickness, *scanPatternSimulation.LayerThickness, "Expected LayerThickness values to match")

}

// AssumedStrainSimulations
func TestAssumedStrainSimulationWhenFetcherErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	assumedStrainSimulationID := int32(2)
	expectedError := errors.New("Some auth0 error")

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("", expectedError)

	assumedStrainSimulationService := NewClient(fakeTokenFetcher, "", "", audience)

	// act
	_, err := assumedStrainSimulationService.AssumedStrainSimulation(assumedStrainSimulationID)

	// assert

	assert.Equal(t, expectedError, err, "Expected an error returned")
}

func TestAssumedStrainSimulationWhenAssumedStrainSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	assumedStrainSimulationID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// AssumedStrainSimulation
	assumedStrainSimulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	assumedStrainSimulationEndpoint := "/" + SimulationAPIBasePath + "/assumedstrainsimulations/{assumedStrainSimulationID}"
	r.HandleFunc(assumedStrainSimulationEndpoint, assumedStrainSimulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	assumedStrainSimulationService := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := assumedStrainSimulationService.AssumedStrainSimulation(assumedStrainSimulationID)

	// assert

	assert.NotNil(t, err, "Expected an error returned because assumedStrainSimulation api send a 500 error")
}

func TestAssumedStrainSimulationWhenSuccessfulExpectsAssumedStrainSimulationReturned(t *testing.T) {
	// arrange
	assumedStrainSimulationID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// AssumedStrainSimulation
	assumedStrainSimulationToReturn := &models.AssumedStrainSimulation{
		Simulation: models.Simulation{
			ID:    assumedStrainSimulationID,
			Title: swag.String("AssumedStrainSimulation name"),
		},
		PartBasedSimulationParameters: models.PartBasedSimulationParameters{
			ElasticModulus: swag.Float64(10),
		},
		AssumedStrainSimulationParameters: models.AssumedStrainSimulationParameters{
			LayerThickness: 50e-6,
		},
	}
	assumedStrainSimulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedAssumedStrainSimulationID, err := strconv.Atoi(mux.Vars(r)["assumedStrainSimulationID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(assumedStrainSimulationID), receivedAssumedStrainSimulationID, "Expected assumedStrainSimulation id received to match what was passed in")
		bytes, err := json.Marshal(assumedStrainSimulationToReturn)
		if err != nil {
			t.Error("Failed to marshal assumedStrainSimulation")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	assumedStrainSimulationEndpoint := "/" + SimulationAPIBasePath + "/assumedstrainsimulations/{assumedStrainSimulationID}"
	r.HandleFunc(assumedStrainSimulationEndpoint, assumedStrainSimulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	assumedStrainSimulationService := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	assumedStrainSimulation, err := assumedStrainSimulationService.AssumedStrainSimulation(assumedStrainSimulationID)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *assumedStrainSimulationToReturn.Title, *assumedStrainSimulation.Title, "Expected names to match")
	assert.Equal(t, assumedStrainSimulationToReturn.ID, assumedStrainSimulation.ID, "Expected IDs to match")
	assert.EqualValues(t, *assumedStrainSimulationToReturn.ElasticModulus, *assumedStrainSimulation.ElasticModulus, "Expected ElasticModulus values to match")
	assert.EqualValues(t, assumedStrainSimulationToReturn.LayerThickness, assumedStrainSimulation.LayerThickness, "Expected LayerThickness values to match")
}

func TestSimulationsWhenNilValuesExpectsSuccess(t *testing.T) {
	// arrange
	var organizationID int32 = 10
	offset := 2
	limit := 10

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Simulation
	simulationsToReturn := []models.Simulation{
		models.Simulation{
			ID: 1,
		},
		models.Simulation{
			ID: 2,
		},
	}

	simulationsHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		assert.Equal(t, strconv.Itoa(offset), r.URL.Query().Get("offset"), "Expected offset to be passed as query param")
		assert.Equal(t, strconv.Itoa(limit), r.URL.Query().Get("limit"), "Expected limit to be passed as query param")
		bytes, err := json.Marshal(simulationsToReturn)
		if err != nil {
			t.Error("Failed to marshal simulations")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	simulationEndpoint := "/" + SimulationAPIBasePath + "/simulations"
	r.HandleFunc(simulationEndpoint, simulationsHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	simulations, err := client.Simulations(organizationID, nil, nil, int32(offset), int32(limit), nil, nil, nil)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Len(t, simulations, 2, "Expected 2 simulations returned.")
}

func TestSimulationsWhenNonNilValuesExpectsSuccess(t *testing.T) {
	// arrange
	var organizationID int32 = 10
	offset := 2
	limit := 10
	sort := "field1:asc"
	status := models.SimulationStatusInProgress
	archived := true

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Simulation
	simulationsToReturn := []models.Simulation{
		models.Simulation{
			ID: 1,
		},
		models.Simulation{
			ID: 2,
		},
	}

	simulationsHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		assert.Equal(t, strconv.Itoa(offset), r.URL.Query().Get("offset"), "Expected offset to be passed as query param")
		assert.Equal(t, strconv.Itoa(limit), r.URL.Query().Get("limit"), "Expected limit to be passed as query param")
		assert.Equal(t, status, r.URL.Query().Get("status"), "Expected status to be passed as query param")
		assert.Equal(t, sort, r.URL.Query().Get("sort"), "Expected sort to be passed as query param")
		bytes, err := json.Marshal(simulationsToReturn)
		if err != nil {
			t.Error("Failed to marshal simulations")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	simulationEndpoint := "/" + SimulationAPIBasePath + "/simulations"
	r.HandleFunc(simulationEndpoint, simulationsHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	simulations, err := client.Simulations(organizationID, []string{status}, []string{sort},
		int32(offset), int32(limit), &archived, nil, nil)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Len(t, simulations, 2, "Expected 2 simulations returned.")
}

func TestRawSimulationWhenSuccessfulExpectsSimulationMapReturned(t *testing.T) {
	// arrange
	simulationID := int32(2)
	layerThickness := float64(50e-6)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Simulation
	simulationToReturn := &models.Simulation{
		ID:    simulationID,
		Title: swag.String("Simulation name"),
		Type:  models.SimulationTypeAssumedStrainSimulation,
	}
	simulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedSimulationID, err := strconv.Atoi(mux.Vars(r)["simulationID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(simulationID), receivedSimulationID, "Expected simulation id received to match what was passed in")
		bytes, err := json.Marshal(simulationToReturn)
		if err != nil {
			t.Error("Failed to marshal simulation")
		}
		w.Write(bytes)
	})

	assumedStrainSimulationToReturn := &models.AssumedStrainSimulation{
		Simulation: models.Simulation{
			ID:    simulationID,
			Title: swag.String("Simulation name"),
			Type:  models.SimulationTypeAssumedStrainSimulation,
		},
		PartBasedSimulationParameters: models.PartBasedSimulationParameters{
			ElasticModulus: swag.Float64(10),
		},
		AssumedStrainSimulationParameters: models.AssumedStrainSimulationParameters{
			LayerThickness: layerThickness,
		},
	}
	assumedStrainSimulationHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedSimulationID, err := strconv.Atoi(mux.Vars(r)["simulationID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(simulationID), receivedSimulationID, "Expected simulation id received to match what was passed in")
		bytes, err := json.Marshal(assumedStrainSimulationToReturn)
		if err != nil {
			t.Error("Failed to marshal simulation")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	simulationEndpoint := "/" + SimulationAPIBasePath + "/simulations/{simulationID}"
	assumedStrainSimulationEndpoint := "/" + SimulationAPIBasePath + "/assumedstrainsimulations/{simulationID}"
	r.HandleFunc(simulationEndpoint, simulationHandler)
	r.HandleFunc(assumedStrainSimulationEndpoint, assumedStrainSimulationHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	simulation, err := client.RawSimulation(simulationID)

	// assert
	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *simulationToReturn.Title, simulation["title"], "Expected names to match")
	assert.EqualValues(t, simulationToReturn.ID, simulation["id"], "Expected IDs to match")
	assert.EqualValues(t, *assumedStrainSimulationToReturn.ElasticModulus, simulation["elasticModulus"].(float64), "Expected elastic modulus to match")
	assert.EqualValues(t, layerThickness, simulation["layerThickness"], "Expected layer thickness to match")
}

func TestBuildFilesWithNonNilValuesExpectsSuccess(t *testing.T) {
	// arrange
	var organizationID int32 = 10
	offset := 2
	limit := 10
	sort := "field1:asc"
	availability := models.BuildFileAvailabilityAvailable

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Build Files
	buildFilesToReturn := []models.BuildFile{
		models.BuildFile{
			ID: swag.Int32(1),
		},
		models.BuildFile{
			ID: swag.Int32(2),
		},
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		assert.Equal(t, strconv.Itoa(offset), r.URL.Query().Get("offset"), "Expected offset to be passed as query param")
		assert.Equal(t, strconv.Itoa(limit), r.URL.Query().Get("limit"), "Expected limit to be passed as query param")
		assert.Equal(t, availability, r.URL.Query().Get("availability"), "Expected availability to be passed as query param")
		assert.Equal(t, sort, r.URL.Query().Get("sort"), "Expected sort to be passed as query param")
		bytes, err := json.Marshal(buildFilesToReturn)
		if err != nil {
			t.Error("Failed to marshal simulations")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	buildFiles, err := client.BuildFiles(organizationID, []string{availability}, []string{sort},
		int32(offset), int32(limit))

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Len(t, buildFiles, 2, "Expected 2 build files returned.")
}

func TestBuildFilesWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	organizationID := int32(2)
	offset := int32(0)
	limit := int32(10)
	var availability []string
	var sort []string

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.BuildFiles(organizationID, availability, sort, offset, limit)

	// assert
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestBuildFileWithNonNilValuesExpectsSuccess(t *testing.T) {
	// arrange
	buildFileID := int32(10)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	buildFileToReturn := models.BuildFile{
		ID:           swag.Int32(buildFileID),
		Name:         swag.String("MyBuildFile"),
		Availability: swag.String("Available"),
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedBuildFileID, err := strconv.Atoi(mux.Vars(r)["id"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(buildFileID), receivedBuildFileID, "Expected build file id received to match what was passed in")
		bytes, err := json.Marshal(buildFileToReturn)
		if err != nil {
			t.Error("Failed to marshal build file")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	buildFile, err := client.BuildFile(int32(buildFileID))

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, buildFile)
	assert.Equal(t, *buildFileToReturn.ID, *buildFile.ID, "Expected ID values to match")
	assert.Equal(t, *buildFileToReturn.Name, *buildFile.Name, "Expected Name values to match")
	assert.Equal(t, *buildFileToReturn.Availability, *buildFile.Availability, "Expected Availability values to match")
}

func TestBuildFileWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	buidFileID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Machine
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.BuildFile(buidFileID)

	// assert
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestPostBuildFileWithNonNilValuesExpectsSuccess(t *testing.T) {

	// arrange
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Build Files
	buildFileToPost := models.BuildFilePost{
		OrganizationID:     swag.Int32(10),
		FileUploadLocation: swag.String("s3bucket/mybuildfile.zip"),
		MachineType:        swag.String(models.BuildFileMachineTypeAdditiveIndustries),
		Name:               swag.String("myBuildFile"),
		Description:        "My lucky build file",
		Tags:               []string{"tag1", "tag2"},
	}

	buildFileToReturn := models.BuildFile{
		ID:             swag.Int32(99),
		OrganizationID: *buildFileToPost.OrganizationID,
		Name:           buildFileToPost.Name,
		Tags:           buildFileToPost.Tags,
		Description:    buildFileToPost.Description,
		MachineType:    buildFileToPost.MachineType,
		Availability:   swag.String("Available"),
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		bytes, err := json.Marshal(buildFileToReturn)
		if err != nil {
			t.Error("Failed to marshal build file")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	buildFile, err := client.PostBuildFile(&buildFileToPost)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, buildFile)
	assert.Equal(t, *buildFileToReturn.ID, *buildFile.ID, "Expected ID values to match")
	assert.Equal(t, *buildFileToReturn.Name, *buildFile.Name, "Expected Name values to match")
	assert.Equal(t, *buildFileToReturn.Availability, *buildFile.Availability, "Expected Availability values to match")
	assert.Equal(t, buildFileToReturn.Description, buildFile.Description, "Expected Description values to match")
	assert.Equal(t, *buildFileToReturn.MachineType, *buildFile.MachineType, "Expected MachineType values to match")
}

func TestPostBuildFileWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	buildFileToPost := models.BuildFilePost{
		OrganizationID:     swag.Int32(10),
		FileUploadLocation: swag.String("s3bucket/mybuildfile.zip"),
		MachineType:        swag.String(models.BuildFileMachineTypeAdditiveIndustries),
		Name:               swag.String("myBuildFile"),
		Description:        "My lucky build file",
		Tags:               []string{"tag1", "tag2"},
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.PostBuildFile(&buildFileToPost)

	// assert
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestPatchBuildFileWithNonNilValuesExpectsSuccess(t *testing.T) {

	// arrange
	availability := "Available"
	buildFileID := int32(101)
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: availability,
	}

	buildFileToReturn := models.BuildFile{
		ID: swag.Int32(buildFileID),
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedBuildFileID, err := strconv.Atoi(mux.Vars(r)["id"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(buildFileID), receivedBuildFileID, "Expected build file id received to match what was passed in")
		bodyBytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		var actualPatchDocuments []models.PatchDocument
		err = json.Unmarshal(bodyBytes, &actualPatchDocuments)
		if err != nil {
			t.Error("Failed to unmarshal build file")
		}
		actualPatch := actualPatchDocuments[0]
		assert.EqualValues(t, *patch, actualPatch, "Expected patch document to be passed in body of PATCH request")
		bytes, err := json.Marshal(buildFileToReturn)
		if err != nil {
			t.Error("Failed to marshal build file")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	buildFile, err := client.PatchBuildFile(int32(buildFileID), []*models.PatchDocument{patch})

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, buildFile)
	assert.Equal(t, buildFileID, *buildFile.ID, "Expected ID values to match")
}

func TestPatchBuildFileWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	buildFileID := int32(22)
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Build Files
	patch := models.PatchDocument{
		From:  "from",
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: "Available",
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.PatchBuildFile(buildFileID, []*models.PatchDocument{&patch})

	// assert
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}
func TestUpdateBuildFileAvailabilityWithNonNilValuesExpectsSuccess(t *testing.T) {

	// arrange
	buildFileID := int32(97)
	availability := "Processing"

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	expectedPatch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: availability,
	}

	// Build Files
	buildFileToReturn := models.BuildFile{
		ID: swag.Int32(buildFileID),
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedBuildFileID, err := strconv.Atoi(mux.Vars(r)["id"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(buildFileID), receivedBuildFileID, "Expected build file id received to match what was passed in")
		bodyBytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		var actualPatchDocuments []models.PatchDocument
		err = json.Unmarshal(bodyBytes, &actualPatchDocuments)
		if err != nil {
			t.Error("Failed to unmarshal build file")
		}
		actualPatch := actualPatchDocuments[0]
		assert.EqualValues(t, *expectedPatch, actualPatch, "Expected patch document to be passed in body of PATCH request")
		bytes, err := json.Marshal(buildFileToReturn)
		if err != nil {
			t.Error("Failed to marshal build file")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	buildFile, err := client.UpdateBuildFileAvailability(int32(buildFileID), availability)

	// assert
	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, buildFile, "Expected buildFile to not be nil")
	assert.Equal(t, buildFileID, *buildFile.ID, "Expected build file IDs to match")
}

func TestUpdateBuildFileAvailabilityWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.UpdateBuildFileAvailability(27, "Available")

	// assert
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestRawBUildFileWhenSuccessfulExpectsBuildFileMapReturned(t *testing.T) {
	// arrange
	buildFileID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Simulation
	buildFileToReturn := &models.BuildFile{
		ID:          swag.Int32(buildFileID),
		Name:        swag.String("Build File Name"),
		MachineType: swag.String(models.BuildFileMachineTypeAdditiveIndustries),
	}
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedSimulationID, err := strconv.Atoi(mux.Vars(r)["id"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(buildFileID), receivedSimulationID, "Expected build file id received to match what was passed in")
		bytes, err := json.Marshal(buildFileToReturn)
		if err != nil {
			t.Error("Failed to marshal simulation")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/buildfiles/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	buildFileMap, err := client.RawBuildFile(int32(buildFileID))

	// assert
	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *buildFileToReturn.Name, buildFileMap["name"], "Expected names to match")
	assert.EqualValues(t, *buildFileToReturn.ID, buildFileMap["id"], "Expected IDs to match")
}

func TestPatchPartWithNonNilValuesExpectsSuccess(t *testing.T) {
	// arrange
	availability := "Available"
	partID := int32(101)
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: availability,
	}

	partToReturn := models.Part{
		ID: &partID,
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedPartID, err := strconv.Atoi(mux.Vars(r)["id"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(partID), receivedPartID, "Expected part id received to match what was passed in")
		bodyBytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		var actualPatchDocuments []models.PatchDocument
		err = json.Unmarshal(bodyBytes, &actualPatchDocuments)
		if err != nil {
			t.Error("Failed to unmarshal part")
		}
		actualPatch := actualPatchDocuments[0]
		assert.EqualValues(t, *patch, actualPatch, "Expected patch document to be passed in body of PATCH request")
		bytes, err := json.Marshal(partToReturn)
		if err != nil {
			t.Error("Failed to marshal part")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/parts/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	part, err := client.PatchPart(int32(partID), []*models.PatchDocument{patch})

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, part)
	assert.Equal(t, partID, *part.ID, "Expected ID values to match")
}

func TestPatchPartWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	partID := int32(22)
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Parts
	patch := models.PatchDocument{
		From:  "from",
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: "Available",
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/parts/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.PatchPart(partID, []*models.PatchDocument{&patch})

	// assert
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestPartWithNonNilValuesExpectsSuccess(t *testing.T) {
	// arrange
	partID := int32(10)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	partToReturn := models.Part{
		ID:           &partID,
		Name:         swag.String("MyPart"),
		Availability: "Available",
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedPartID, err := strconv.Atoi(mux.Vars(r)["id"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(partID), receivedPartID, "Expected part id received to match what was passed in")
		bytes, err := json.Marshal(partToReturn)
		if err != nil {
			t.Error("Failed to marshal part")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/parts/{id}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	part, err := client.Part(partID)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, part)
	assert.Equal(t, partToReturn.ID, part.ID, "Expected ID values to match")
	assert.Equal(t, *partToReturn.Name, *part.Name, "Expected Name values to match")
	assert.Equal(t, partToReturn.Availability, part.Availability, "Expected Availability values to match")
}

func TestPartWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	buidFileID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Machine
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/parts"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.Part(buidFileID)

	// assert
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestNewClientWithRetryWhen500ExpectsRetry(t *testing.T) {
	// arrange
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	callCounter := 0
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		callCounter++
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	r.HandleFunc("/"+SimulationAPIBasePath+"/parts/1", handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClientWithRetry(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience, 3*time.Second)

	// act
	_, err := client.Part(1)

	// assert
	assert.True(t, callCounter > 1, "Expected to retry the failed call at least once")
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 500 error")
}

func TestPatchSimulationActivityWithNonNilValuesExpectsSuccess(t *testing.T) {

	// arrange
	simulationID := int32(10)
	activityID := "activity id"
	simulationActivityID := int32(11)
	percentComplete := int32(98)
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/percentComplete"),
		Value: percentComplete,
	}

	activityToReturn := &models.SimulationActivity{
		ID:              simulationActivityID,
		ActivityID:      swag.String(activityID),
		SimulationID:    swag.Int32(simulationID),
		PercentComplete: percentComplete,
	}

	activitiesHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		activitiesBytes, err := json.Marshal([]models.SimulationActivity{*activityToReturn})
		if err != nil {
			t.Fatal(err)
		}
		w.Write(activitiesBytes)
	})

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedID, err := strconv.Atoi(mux.Vars(r)["id"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(simulationID), receivedID, "Expected simulation id received to match what was passed in")
		receivedActivityID, err := strconv.Atoi(mux.Vars(r)["activityId"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(simulationActivityID), receivedActivityID, "Expected activity id received to match what was passed in")
		bodyBytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		var actualPatchDocuments []models.PatchDocument
		err = json.Unmarshal(bodyBytes, &actualPatchDocuments)
		if err != nil {
			t.Error("Failed to unmarshal patch documents")
		}
		actualPatch := actualPatchDocuments[0]
		assert.Equal(t, *patch.Path, *actualPatch.Path, "Expected patch document path to be passed in body of PATCH request")
		assert.Equal(t, *patch.Op, *actualPatch.Op, "Expected patch document op to be passed in body of PATCH request")
		assert.EqualValues(t, patch.Value, actualPatch.Value, "Expected patch document value to be passed in body of PATCH request")
		bytes, err := json.Marshal(activityToReturn)
		if err != nil {
			t.Error("Failed to marshal patch")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/simulations/{id}/activities/{activityId}"
	r.HandleFunc(endpoint, handler)
	r.HandleFunc("/"+SimulationAPIBasePath+"/simulations/{id}/activities", activitiesHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	activity, err := client.PatchSimulationActivity(simulationID, activityID, []*models.PatchDocument{patch})

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, activity)
	assert.Equal(t, simulationActivityID, activity.ID, "Expected ID values to match")
	assert.Equal(t, simulationID, *activity.SimulationID, "Expected simulation ID values to match")
	assert.Equal(t, percentComplete, activity.PercentComplete, "Expected percent complete values to match")
}

func TestPutSimulationActivityWithNonNilValuesExpectsSuccess(t *testing.T) {
	// arrange
	simulationID := int32(10)
	activityID := "activity id"
	simulationActivityID := int32(11)
	percentComplete := int32(98)
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	simulationActivity := &models.SimulationActivity{
		ID:              simulationActivityID,
		ActivityID:      swag.String(activityID),
		SimulationID:    swag.Int32(simulationID),
		PercentComplete: percentComplete,
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedID, err := strconv.Atoi(mux.Vars(r)["id"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(simulationID), receivedID, "Expected simulation id received to match what was passed in")
		receivedActivityID, err := strconv.Atoi(mux.Vars(r)["activityId"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(simulationActivityID), receivedActivityID, "Expected activity id received to match what was passed in")
		bodyBytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		var actualSimulationActivity models.SimulationActivity
		err = json.Unmarshal(bodyBytes, &actualSimulationActivity)
		if err != nil {
			t.Error("Failed to unmarshal activity documents")
		}
		assert.Equal(t, simulationActivity.ID, actualSimulationActivity.ID, "Expected simulation activity id to be passed in body")
		w.WriteHeader(http.StatusOK)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/simulations/{id}/activities/{activityId}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	err := client.PutSimulationActivity(simulationID, simulationActivity)

	// assert

	assert.Nil(t, err, "Expected no error returned")
}

func TestPatchSimulationActivityWhenSimulationAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	simulationID := int32(10)
	activityID := "activity id"
	percentComplete := int32(98)
	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/percentComplete"),
		Value: percentComplete,
	}

	// Setup routes
	r := mux.NewRouter()
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	activity, err := client.PatchSimulationActivity(simulationID, activityID, []*models.PatchDocument{patch})

	// assert
	assert.NotNil(t, err, "Expected an error returned because simulation api sent a 404 error")
	assert.Nil(t, activity, "Expected activity to be nil due to error from api")
}

func TestPatchPartSupportWithNonNilValuesExpectsSuccess(t *testing.T) {

	// arrange
	availability := "Available"
	partSupportID := int32(101)
	partID := int32(102)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: availability,
	}

	partSupportFileToReturn := models.PartSupport{
		ID:     swag.Int32(partSupportID),
		PartID: swag.Int32(partID),
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedPartSupportID, err := strconv.Atoi(mux.Vars(r)["supportID"])
		if err != nil {
			t.Fatal(err)
		}
		receivedPartID, err := strconv.Atoi(mux.Vars(r)["partID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(partSupportID), receivedPartSupportID, "Expected part support id received to match what was passed in")
		assert.EqualValues(t, int(partID), receivedPartID, "Expected part id received to match what was passed in")
		bodyBytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		var actualPatchDocuments []models.PatchDocument
		err = json.Unmarshal(bodyBytes, &actualPatchDocuments)
		if err != nil {
			t.Error("Failed to unmarshal build file")
		}
		actualPatch := actualPatchDocuments[0]
		assert.EqualValues(t, *patch, actualPatch, "Expected patch document to be passed in body of PATCH request")
		bytes, err := json.Marshal(partSupportFileToReturn)
		if err != nil {
			t.Error("Failed to marshal build file")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/parts/{partID}/supports/{supportID}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	partSupport, err := client.PatchPartSupport(int32(partID), int32(partSupportID), []*models.PatchDocument{patch})

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, partSupport)
	assert.Equal(t, partSupportID, *partSupport.ID, "Expected ID values to match")
}

func TestPatchPartSupportWhenPatchErrorsExpectsErrorReturned(t *testing.T) {

	// arrange
	availability := "Available"
	partSupportID := int32(101)
	partID := int32(102)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: availability,
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/parts/{partID}/supports/{supportID}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.PatchPartSupport(int32(partID), int32(partSupportID), []*models.PatchDocument{patch})

	// assert

	assert.Error(t, err, "Expected an error returned because patch returned a 500")
}

func TestPatchPartSupportWhenTokenFetcherErrorsExpectsErrorReturned(t *testing.T) {

	// arrange
	partSupportID := int32(101)
	partID := int32(102)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	expectedError := errors.New("some token error")
	fakeTokenFetcher.TokenReturns("Token", expectedError)

	client := NewClient(fakeTokenFetcher, "some url", SimulationAPIBasePath, audience)

	// act
	_, err := client.PatchPartSupport(int32(partID), int32(partSupportID), []*models.PatchDocument{})

	// assert
	assert.Error(t, err, "Expected an error returned because token fetcher errored")
}

func TestPartSupportByIDWhenSuccessfulExpectsPartSupportReturned(t *testing.T) {
	// arrange
	partSupportID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	// Material
	partSupportToReturn := &models.PartSupport{
		ID:   swag.Int32(partSupportID),
		Name: swag.String("Part support name"),
	}
	partSupportHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedPartSupportID, err := strconv.Atoi(mux.Vars(r)["partSupportID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(partSupportID), receivedPartSupportID, "Expected partSupport id received to match what was passed in")
		bytes, err := json.Marshal(partSupportToReturn)
		if err != nil {
			t.Error("Failed to marshal returned object")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	materialEndpoint := "/" + SimulationAPIBasePath + "/supports/{partSupportID}"
	r.HandleFunc(materialEndpoint, partSupportHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	partSupport, err := client.PartSupportByID(partSupportID)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.Equal(t, *partSupportToReturn.Name, *partSupport.Name, "Expected names to match")
	assert.Equal(t, *partSupportToReturn.ID, *partSupport.ID, "Expected IDs to match")
}

func TestPartSupportByIDWhenAPIErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	partSupportID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	partSupportHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	materialEndpoint := "/" + SimulationAPIBasePath + "/supports/{partSupportID}"
	r.HandleFunc(materialEndpoint, partSupportHandler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.PartSupportByID(partSupportID)

	// assert
	assert.Error(t, err, "Expected an error returned because API returned a 500")
}

func TestPartSupportByIDWhenTokenFetcherErrorsExpectsErrorReturned(t *testing.T) {
	// arrange
	partSupportID := int32(2)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	expectedError := errors.New("some error")
	fakeTokenFetcher.TokenReturns("Token", expectedError)

	client := NewClient(fakeTokenFetcher, "some url", SimulationAPIBasePath, audience)

	// act
	_, err := client.PartSupportByID(partSupportID)

	// assert

	assert.Error(t, err, "Expected error returned because token fetcher errored")
}

func TestPatchPartSupportByIDWithNonNilValuesExpectsSuccess(t *testing.T) {

	// arrange
	availability := "Available"
	partSupportID := int32(101)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: availability,
	}

	partSupportFileToReturn := models.PartSupport{
		ID:     swag.Int32(partSupportID),
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedPartSupportID, err := strconv.Atoi(mux.Vars(r)["supportID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(partSupportID), receivedPartSupportID, "Expected part support id received to match what was passed in")
		bodyBytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		var actualPatchDocuments []models.PatchDocument
		err = json.Unmarshal(bodyBytes, &actualPatchDocuments)
		if err != nil {
			t.Error("Failed to unmarshal build file")
		}
		actualPatch := actualPatchDocuments[0]
		assert.EqualValues(t, *patch, actualPatch, "Expected patch document to be passed in body of PATCH request")
		bytes, err := json.Marshal(partSupportFileToReturn)
		if err != nil {
			t.Error("Failed to marshal build file")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/supports/{supportID}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	partSupport, err := client.PatchPartSupportByID(int32(partSupportID), []*models.PatchDocument{patch})

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, partSupport)
	assert.Equal(t, partSupportID, *partSupport.ID, "Expected ID values to match")
}

func TestPatchPartSupportByIDWhenPatchErrorsExpectsErrorReturned(t *testing.T) {

	// arrange
	availability := "Available"
	partSupportID := int32(101)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: availability,
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(500)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/supports/{supportID}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	_, err := client.PatchPartSupportByID(int32(partSupportID), []*models.PatchDocument{patch})

	// assert
	assert.Error(t, err, "Expected an error returned because patch returned a 500")
}

func TestPatchPartSupportByIDWhenTokenFetcherErrorsExpectsErrorReturned(t *testing.T) {

	// arrange
	partSupportID := int32(101)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	expectedError := errors.New("some token error")
	fakeTokenFetcher.TokenReturns("Token", expectedError)

	client := NewClient(fakeTokenFetcher, "some url", SimulationAPIBasePath, audience)

	// act
	_, err := client.PatchPartSupportByID(int32(partSupportID), []*models.PatchDocument{})

	// assert
	assert.Error(t, err, "Expected an error returned because token fetcher errored")
}

func TestUpdatePartSupportAvailabilityWithNonNilValuesExpectsSuccess(t *testing.T) {

	// arrange
	availability := "Available"
	partSupportID := int32(101)

	// Token
	fakeTokenFetcher := &auth0fakes.FakeTokenFetcher{}
	fakeTokenFetcher.TokenReturns("Token", nil)

	patch := &models.PatchDocument{
		Op:    swag.String(models.PatchDocumentOpReplace),
		Path:  swag.String("/availability"),
		Value: availability,
	}

	partSupportFileToReturn := models.PartSupport{
		ID:     swag.Int32(partSupportID),
	}

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		assert.NotEmpty(t, r.Header.Get("Authorization"), "Authorization header should not be empty")
		receivedPartSupportID, err := strconv.Atoi(mux.Vars(r)["supportID"])
		if err != nil {
			t.Fatal(err)
		}
		assert.EqualValues(t, int(partSupportID), receivedPartSupportID, "Expected part support id received to match what was passed in")
		bodyBytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		var actualPatchDocuments []models.PatchDocument
		err = json.Unmarshal(bodyBytes, &actualPatchDocuments)
		if err != nil {
			t.Error("Failed to unmarshal build file")
		}
		actualPatch := actualPatchDocuments[0]
		assert.EqualValues(t, *patch, actualPatch, "Expected patch document to be passed in body of PATCH request")
		bytes, err := json.Marshal(partSupportFileToReturn)
		if err != nil {
			t.Error("Failed to marshal build file")
		}
		w.Write(bytes)
	})

	// Setup routes
	r := mux.NewRouter()
	endpoint := "/" + SimulationAPIBasePath + "/supports/{supportID}"
	r.HandleFunc(endpoint, handler)
	testServer := httptest.NewServer(r)
	defer testServer.Close()
	client := NewClient(fakeTokenFetcher, testServer.URL, SimulationAPIBasePath, audience)

	// act
	partSupport, err := client.UpdatePartSupportAvailability(int32(partSupportID), availability)

	// assert

	assert.Nil(t, err, "Expected no error returned")
	assert.NotNil(t, partSupport)
	assert.Equal(t, partSupportID, *partSupport.ID, "Expected ID values to match")
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using System.ComponentModel.Composition;

namespace Hermit.Plugin
{
    /// <summary>
    /// Interface for a Shell
    /// </summary>
    [InheritedExport]
    public interface IShell : IHaveDisplayName
    {
        /// <summary>
        /// Startup task for all shells
        /// </summary>
        /// <param name="args"></param>
        void Startup(string[] args);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using TribalWars.Villages.Units;

namespace TribalWars.WorldTemplate
{
    /// <summary>
    /// Reading fixed world Unit information from WorldTemplate\Units.xml
    /// for all unit info that is not in official TW API.
    /// </summary>
    public class TacticsUnit
    {
        public UnitTypes Type { get; private set; }
        public string Name { get; private set; }
        public string ShortName { get; private set; }
        public bool Farmer { get; private set; }
        public bool HideAttacher { get; private set; }
        public bool Offense { get; private set; }

        private TacticsUnit()
        {

        }

        public static List<TacticsUnit> GetUnitsFromXml(string xmlPath)
        {
            var units = new List<TacticsUnit>();

            var xml = XDocument.Load(xmlPath);
            foreach (var xmlUnit in xml.Root.Elements())
            {
                var unit = new TacticsUnit
                    {
                        Type = (UnitTypes)Enum.Parse(typeof(UnitTypes), xmlUnit.Element("Type").Value, true),
                        Name = xmlUnit.Element("Name").Value,
                        ShortName = xmlUnit.Element("Short").Value,

                        Farmer = Convert.ToBoolean(xmlUnit.Element("Farmer").Value),
                        HideAttacher = Convert.ToBoolean(xmlUnit.Element("HideAttacker").Value),
                        Offense = Convert.ToBoolean(xmlUnit.Element("Offense").Value)
                    };

                units.Add(unit);
            }

            return units;
        }

        public override string ToString()
        {
            return string.Format("Type={0}, Name={1}", Type, Name);
        }
    }
}


text:
/*!
 Frog Framework JS, Keypad Component
 Created by Ahmet Emin Yuce for the Frog Framework, http://www.frogframework.com/
 MIT License: http://en.wikipedia.org/wiki/MIT_License
*/

/*globals $, jQuery, alert, console, ffc, easeTime, mobile */
if (typeof ffc.frogFramework === 'undefined') { throw new Error('Keypad component requires Frog Framework! Please visit: frogframework.com'); }

var
    keypadClasses = typeof keypadClasses !== 'undefined' ? keypadClasses : 'keypad bordered rounded shadow ease-opacity',
    keypadBtnClasses = typeof keypadBtnClasses !== 'undefined' ? keypadBtnClasses : 'btn no-padding-h rounded bordered light-bordered ease-bg',
    keypadClearBtnClasses = typeof keypadClearBtnClasses !== 'undefined' ? keypadClearBtnClasses : 'theme-red ui-dark',
    keypadDelBtnClasses = typeof keypadDelBtnClasses !== 'undefined' ? keypadDelBtnClasses : 'theme-yellow ui-dark';

(function ($) {

    'use strict';

    // data- attributes settings
    ffc.Attr.keypad = function (t) {

        ffc.keypadClasses = t.is('[data-classes]') ? t.data('classes') : keypadClasses;
        ffc.keypadBtnClasses = t.is('[data-btn-classes]') ? t.data('btn-classes') : keypadBtnClasses;
        ffc.keypadClearBtnClasses = t.is('[data-clear-btnclasses]') ? t.data('clear-btnclasses') : keypadClearBtnClasses;
        ffc.keypadDelBtnClasses = t.is('[data-del-btnclasses]') ? t.data('del-btnclasses') : keypadDelBtnClasses;

    };

    $(function () {

        $(document).on('ffc.keypad'); // set callback

        function keypadClose() {

            var keypad = $('.keypad');
            keypad.removeClass('open-ease');
            setTimeout(function () { keypad.removeClass('open'); }, easeTime);

        }

        $(document).on('focus', '.ffc-keypad [type="text"]', function (e) {

            var i, buttons = '', keypad = $('.keypad'), v = $(this).val(), offset = $(this).offset();

            if (keypad.length < 1 && !mobile && $(window).width() > 767) {

                ffc.Attr.keypad($(this).parents('.ffc-keypad'));

                for (i = 1; i <= 10; i += 1) {

                    if (i === 10) { i = 0; }
                    buttons += '<button class="' + ffc.keypadBtnClasses + '" type="button">' + i + '</button>';

                    if (i === 0) {
                        buttons += '<button class="clear ' + ffc.keypadBtnClasses + ' ' + ffc.keypadClearBtnClasses + '" type="button"></button>' +
                            '<button class="del ' + ffc.keypadBtnClasses + ' ' + ffc.keypadDelBtnClasses + '" type="button"></button>';
                        break;
                    }
                }

                $('body').prepend('
' + buttons + '
');
                buttons = '';
                keypad = $('.keypad');

            }

            $('.keypad-active').removeClass('keypad-active');
            $(this).addClass('keypad-active');

            $(this).val('').val(v);
            keypad.css({'top' : (offset.top + 32) + 'px', 'left' : (offset.left - 1) + 'px'});

            keypad.addClass('open');
            setTimeout(function () { keypad.addClass('open-ease'); }, easeTime);

            $(document).one('click', keypadClose);

            $(document).trigger('ffc.keypad'); // setting callback event

        });

        $(document).on('click', '.keypad button:not(.clear):not(.del)', function () {

            var f, t = $('.keypad-active'), forms = $('[type="text"]', t.parents('.ffc-keypad')), v = t.val(), n = t.val() + $(this).text();
            if (v.length >= (t.attr('maxlength') - 1)) {

                if (v.length < t.attr('maxlength')) { t.focus().val(n); }

                f = forms.index(t) + 1;
                if (forms.eq(f).length > 0) { forms.eq(f).trigger('focus'); } else { keypadClose(); }

            } else { t.focus().val(n).trigger('keyup'); }

        });

        $(document).on('click', '.keypad .del', function () {

            var t = $('.keypad-active'), v = t.val(), n = v.substr(0, v.length - 1);
            t.focus().val(n);

        });

        $(window).on('resize', keypadClose);

        $(document).on('click', '.keypad, .ffc-keypad', function (e) { e.stopPropagation(); });
        $(document).on('click', '.keypad .clear', function () { $('.keypad-active').focus().val(''); });

    });

}(jQuery));


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.antony.service.mail.db.MailMapper" >
	<select id="getEmailTestUser"  resultType="java.util.Map">
		select ID, NAME, EMAIL from cm_email_test
	</select>
</mapper>


text:
@interface UIColor (TLCommon)

+ (UIColor *)colorWithCSSRed:(NSUInteger)red255 green:(NSUInteger)green255 blue:(NSUInteger)blue255;
+ (UIColor *)colorWithCSSString:(NSString *)cssColorString;

@end