Before we integrate our new facade with the actual system, we should put it through its paces and thoroughly test it. So let’s develop a set of tests and helper elements for testing all of the operations registered in the facade. We’ll start off by creating a set of helper classes. One will test our dependencies, another will test how well the facade works with users, and the last one will contain a set of test users. All of these files will be placed in the folder /test/fixtures.
The file for testing dependencies will be called TestReferences and will allow us to test how well the facade is able to work with the microservices it depends on. This file’s code is listed below:
/test/fixture/TestReferences.ts
import { ConfigParams } from 'pip-services3-commons-nodex';
import { Descriptor } from 'pip-services3-commons-nodex';
import { ManagedReferences } from 'pip-services3-container-nodex';
import { IAccountsClientV1 } from '../../src/clients/version1/IAccountsClientV1';
import { AccountV1 } from '../../src/clients/version1/AccountV1';
import { IRolesClientV1 } from '../../src/clients/version1/IRolesClientV1';
import { ISessionsClientV1 } from '../../src/clients/version1/ISessionsClientV1';
import { ISitesClientV1 } from '../../src/clients/version1/ISitesClientV1';
import { SiteV1 } from '../../src/clients/version1/SiteV1';
import { TestUsers } from './TestUsers';
import { TestSites } from './TestSites';
import { ClientFacadeFactory } from '../../src/build/ClientFacadeFactory';
import { HttpEndpoint, DefaultRpcFactory } from 'pip-services3-rpc-nodex';
import { FacadeServiceV1 } from '../../src/services/version1/FacadeServiceV1';
import { FacadeServiceV2 } from '../../src/services/version2/FacadeServiceV2';
import { AccountsMemoryClientV1 } from '../../src/clients/version1/AccountsMemoryClientV1';
import { SessionsMemoryClientV1 } from '../../src/clients/version1/SessionsMemoryClientV1';
import { PasswordsNullClientV1 } from '../../src/clients/version1/PasswordsNullClientV1';
import { RolesMemoryClientV1 } from '../../src/clients/version1/RolesMemoryClientV1';
import { EmailSettingsMemoryClientV1 } from '../../src/clients/version1/EmailSettingsMemoryClientV1';
import { SitesMemoryClientV1 } from '../../src/clients/version1/SitesMemoryClientV1';
export class TestReferences extends ManagedReferences {
private _factory = new ClientFacadeFactory();
public constructor() {
super();
this.appendDependencies();
this.configureService();
this.createUsersAndSessions();
}
private appendDependencies() {
// Add factories
this.put(null, new ClientFacadeFactory());
this.put(null, new DefaultRpcFactory());
// Add service
this.put(null, new FacadeServiceV1());
this.put(null, new FacadeServiceV2());
// Add services
this.put(new Descriptor('pip-services-accounts', 'client', 'memory', 'default', '*'), new AccountsMemoryClientV1());
this.put(new Descriptor('pip-services-sessions', 'client', 'memory', 'default', '*'), new SessionsMemoryClientV1());
this.put(new Descriptor('pip-services-passwords', 'client', 'null', 'default', '*'), new PasswordsNullClientV1());
this.put(new Descriptor('pip-services-roles', 'client', 'memory', 'default', '*'), new RolesMemoryClientV1());
this.put(new Descriptor('pip-services-emailsettings', 'client', 'memory', 'default', '*'), new EmailSettingsMemoryClientV1());
this.put(new Descriptor('pip-services-sites', 'client', 'direct', 'memory', '*'), new SitesMemoryClientV1());
}
private configureService(): void {
// Configure Facade service
let service = this.getOneRequired<HttpEndpoint>(
new Descriptor('pip-services', 'endpoint', 'http', 'default', '*')
);
service.configure(ConfigParams.fromTuples(
'root_path', '', //'/api/v1',
'connection.protocol', 'http',
'connection.host', 'localhost',
'connection.port', 3000
));
}
private async createUsersAndSessions(): Promise<void> {
// Create accounts
let accountsClient = this.getOneRequired<IAccountsClientV1>(
new Descriptor('pip-services-accounts', 'client', '*', '*', '*')
);
let adminUserAccount = <AccountV1>{
id: TestUsers.AdminUserId,
login: TestUsers.AdminUserLogin,
name: TestUsers.AdminUserName,
active: true,
create_time: new Date()
};
await accountsClient.createAccount(null, adminUserAccount);
let user1Account = <AccountV1>{
id: TestUsers.User1Id,
login: TestUsers.User1Login,
name: TestUsers.User1Name,
active: true,
create_time: new Date()
};
await accountsClient.createAccount(null, user1Account);
let user2Account = <AccountV1>{
id: TestUsers.User2Id,
login: TestUsers.User2Login,
name: TestUsers.User2Name,
active: true,
create_time: new Date()
};
await accountsClient.createAccount(null, user2Account);
// Create test site(s)
let sitesClient = this.getOneRequired<ISitesClientV1>(
new Descriptor('pip-services-sites', 'client', '*', '*', '*')
);
let site1 = <SiteV1>{
id: TestSites.Site1Id,
name: TestSites.Site1Name
};
await sitesClient.createSite(null, site1);
// Create user roles
let rolesClient = this.getOneRequired<IRolesClientV1>(
new Descriptor('pip-services-roles', 'client', '*', '*', '*')
);
await rolesClient.setRoles(
null, TestUsers.AdminUserId, [ 'admin', TestSites.Site1Id + ':admin' ]);
await rolesClient.setRoles(
null, TestUsers.User1Id, [ TestSites.Site1Id + ':manager' ]);
await rolesClient.setRoles(
null, TestUsers.User2Id, [ TestSites.Site1Id + ':user' ]);
// Create opened sessions
let sessionsClient = this.getOneRequired<ISessionsClientV1>(
new Descriptor('pip-services-sessions', 'client', '*', '*', '*')
);
let adminUserData: any = Object.assign({}, adminUserAccount);
adminUserData.roles = [ 'admin', TestSites.Site1Id + ':admin' ];
let session = await sessionsClient.openSession(
null, TestUsers.AdminUserId, TestUsers.AdminUserName,
null, null, adminUserData, null
);
session.id = TestUsers.AdminUserSessionId
let user1Data: any = Object.assign({}, user1Account);
user1Data.roles = [ TestSites.Site1Id + ':manager' ];
session = await sessionsClient.openSession(
null, TestUsers.User1Id, TestUsers.User1Name,
null, null, user1Data, null
);
session.id = TestUsers.User1SessionId
let user2Data: any = Object.assign({}, user2Account);
user2Data.roles = [ TestSites.Site1Id + ':user' ];
session = await sessionsClient.openSession(
null, TestUsers.User2Id, TestUsers.User2Name,
null, null, user2Data, null
);
session.id = TestUsers.User2SessionId
}
}
using Pip.Services.SampleFacade.Build;
using Pip.Services.SampleFacade.Clients.Version1;
using Pip.Services.SampleFacade.Operations.Version1;
using Pip.Services.SampleFacade.Services.Version1;
using Pip.Services.SampleFacade.Services.Version2;
using PipServices3.Commons.Config;
using PipServices3.Commons.Refer;
using PipServices3.Container.Refer;
using PipServices3.Rpc.Build;
using PipServices3.Rpc.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Pip.Services.SampleFacade.Fixtures
{
public class TestReferences: ManagedReferences
{
private ClientFacadeFactory _factory = new ClientFacadeFactory();
public TestReferences()
{
AppendDependencies();
ConfigureService();
CreateUsersAndSessionsAsync().Wait();
}
private void AppendDependencies()
{
// Add factories
Put(null, new ClientFacadeFactory());
Put(null, new DefaultRpcFactory());
// Add service
Put(null, new FacadeServiceV1());
Put(null, new FacadeServiceV2());
// Add services
Put(new Descriptor("pip-services-accounts", "client", "memory", "default", "*"), new AccountsMemoryClientV1());
Put(new Descriptor("pip-services-sessions", "client", "memory", "default", "*"), new SessionsMemoryClientV1());
Put(new Descriptor("pip-services-passwords", "client", "null", "default", "*"), new PasswordsNullClientV1());
Put(new Descriptor("pip-services-roles", "client", "memory", "default", "*"), new RolesMemoryClientV1());
Put(new Descriptor("pip-services-emailsettings", "client", "memory", "default", "*"), new EmailSettingsMemoryClientV1());
Put(new Descriptor("pip-services-sites", "client", "direct", "memory", "*"), new SitesMemoryClientV1());
}
private void ConfigureService()
{
// Configure Facade service
var service = GetOneRequired<HttpEndpoint>(
new Descriptor("pip-services", "endpoint", "http", "default", "*")
);
service.Configure(ConfigParams.FromTuples(
"root_path", "", //"/api/v1",
"connection.protocol", "http",
"connection.host", "0.0.0.0",
"connection.port", 3000
));
}
private async Task CreateUsersAndSessionsAsync()
{
// Create accounts
var accountsClient = GetOneRequired<IAccountsClientV1>(
new Descriptor("pip-services-accounts", "client", "*", "*", "*")
);
var adminUserAccount = new AccountV1{
Id = TestUsers.AdminUserId,
Login = TestUsers.AdminUserLogin,
Name = TestUsers.AdminUserName,
Active = true,
CreateTime = DateTime.Now
};
await accountsClient.CreateAccountAsync(null, adminUserAccount);
var user1Account = new AccountV1{
Id = TestUsers.User1Id,
Login = TestUsers.User1Login,
Name = TestUsers.User1Name,
Active = true,
CreateTime = DateTime.Now
};
await accountsClient.CreateAccountAsync(null, user1Account);
var user2Account = new AccountV1{
Id = TestUsers.User2Id,
Login = TestUsers.User2Login,
Name = TestUsers.User2Name,
Active = true,
CreateTime = DateTime.Now
};
await accountsClient.CreateAccountAsync(null, user2Account);
// Create test site(s)
var sitesClient = GetOneRequired<ISitesClientV1>(
new Descriptor("pip-services-sites", "client", "*", "*", "*")
);
var site1 = new SiteV1
{
Id = TestSites.Site1Id,
Name = TestSites.Site1Name
};
await sitesClient.CreateSiteAsync(null, site1);
// Create user roles
var rolesClient = GetOneRequired<IRolesClientV1>(
new Descriptor("pip-services-roles", "client", "*", "*", "*")
);
await rolesClient.SetRolesAsync(
null, TestUsers.AdminUserId, new[] {"admin", TestSites.Site1Id + ":admin" });
await rolesClient.SetRolesAsync(
null, TestUsers.User1Id, new[] { TestSites.Site1Id + ":manager" });
await rolesClient.SetRolesAsync(
null, TestUsers.User2Id, new[] { TestSites.Site1Id + ":user" });
// Create opened sessions
var sessionsClient = GetOneRequired<ISessionsClientV1>(
new Descriptor("pip-services-sessions", "client", "*", "*", "*")
);
var adminUserData = CreateUserData(adminUserAccount);
adminUserData.Roles = new List<string>(new[] { "admin", TestSites.Site1Id + ":admin" });
var session = await sessionsClient.OpenSessionAsync(
null, TestUsers.AdminUserId, TestUsers.AdminUserName,
null, null, adminUserData, null);
session.Id = TestUsers.AdminUserSessionId;
var user1Data = CreateUserData(user1Account);
user1Data.Roles = new List<string>(new[] { TestSites.Site1Id + ":manager" });
session = await sessionsClient.OpenSessionAsync(
null, TestUsers.User1Id, TestUsers.User1Name,
null, null, user1Data, null);
session.Id = TestUsers.User1SessionId;
var user2Data = CreateUserData(user2Account);
user2Data.Roles = new List<string>(new[] { TestSites.Site1Id + ":user" });
session = await sessionsClient.OpenSessionAsync(
null, TestUsers.User2Id, TestUsers.User2Name,
null, null, user2Data, null);
session.Id = TestUsers.User2SessionId;
}
private SessionUserV1 CreateUserData(AccountV1 account)
{
return new SessionUserV1
{
Id = account.Id,
Name = account.Name,
Login = account.Login,
CreateTime = account.CreateTime,
TimeZone = account.TimeZone,
Language = account.Language,
Theme = account.Theme,
//Settings: settings,
CustomHdr = account.CustomHdr,
CustomDat = account.CustomDat
};
}
}
}
/test/fixture/TestReferences.go
package test_fixture
import (
"time"
bclients1 "github.com/pip-services-samples/client-beacons-gox/clients/version1"
fbuild "github.com/pip-services-samples/pip-samples-facade-go/build"
operations1 "github.com/pip-services-samples/pip-samples-facade-go/operations/version1"
services1 "github.com/pip-services-samples/pip-samples-facade-go/services/version1"
accclients1 "github.com/pip-services-users/pip-clients-accounts-go/version1"
passclients1 "github.com/pip-services-users/pip-clients-passwords-go/version1"
roleclients1 "github.com/pip-services-users/pip-clients-roles-go/version1"
sessclients1 "github.com/pip-services-users/pip-clients-sessions-go/version1"
cconf "github.com/pip-services3-gox/pip-services3-commons-gox/config"
cref "github.com/pip-services3-gox/pip-services3-commons-gox/refer"
cbuild "github.com/pip-services3-gox/pip-services3-components-gox/build"
bref "github.com/pip-services3-gox/pip-services3-container-gox/refer"
rpcbuild "github.com/pip-services3-gox/pip-services3-rpc-gox/build"
rpcservices "github.com/pip-services3-gox/pip-services3-rpc-gox/services"
)
type TestReferences struct {
*bref.ManagedReferences
factory *cbuild.CompositeFactory
}
func NewTestReferences() *TestReferences {
c := TestReferences{
ManagedReferences: bref.NewManagedReferences(nil),
factory: cbuild.NewCompositeFactory(),
}
c.setupFactories()
c.appendDependencies()
c.configureService()
c.createUsersAndSessions()
return &c
}
func (c *TestReferences) setupFactories() {
c.factory.Add(fbuild.NewClientFacadeFactory())
c.factory.Add(fbuild.NewServiceFacadeFactory())
c.factory.Add(rpcbuild.NewDefaultRpcFactory())
}
func (c *TestReferences) Append(descriptor *cref.Descriptor) {
component, err := c.factory.Create(descriptor)
if err != nil {
return
}
c.Put(descriptor, component)
}
func (c *TestReferences) appendDependencies() {
// Add factories
c.Put(nil, c.factory)
// Add service
c.Put(nil, services1.NewFacadeServiceV1())
// Add user management services
c.Put(cref.NewDescriptor("pip-services-accounts", "client", "memory", "default", "*"), accclients1.NewAccountsMemoryClientV1(nil))
c.Put(cref.NewDescriptor("pip-services-sessions", "client", "memory", "default", "*"), sessclients1.NewSessionsMemoryClientV1())
c.Put(cref.NewDescriptor("pip-services-passwords", "client", "commandable-http", "default", "*"), passclients1.NewPasswordsMemoryClientV1())
c.Put(cref.NewDescriptor("pip-services-roles", "client", "commandable-http", "default", "*"), roleclients1.NewRolesMemoryClientV1())
// Add content management services
// Beacons
c.Put(cref.NewDescriptor("beacons", "client", "memory", "default", "*"), bclients1.NewBeaconsMemoryClientV1(nil))
}
func (c *TestReferences) configureService() {
// Configure Facade service
dependency, _ := c.GetOneRequired(cref.NewDescriptor("pip-services", "endpoint", "http", "default", "*"))
service, ok1 := dependency.(*rpcservices.HttpEndpoint)
if !ok1 {
panic("TestReferences: Cant't resolv dependency 'client' to IAccountsClientV1")
}
service.Configure(cconf.NewConfigParamsFromTuples(
"root_path", "", //"/api/1.0",
"connection.protocol", "http",
"connection.host", "0.0.0.0",
"connection.port", 3000,
))
}
func (c *TestReferences) createUsersAndSessions() {
// Create accounts
dependency, _ := c.GetOneRequired(cref.NewDescriptor("pip-services-accounts", "client", "*", "*", "*"))
accountsClient, ok1 := dependency.(accclients1.IAccountsClientV1)
if !ok1 {
panic("TestReferences: Cant't resolv dependency 'client' to IAccountsClientV1")
}
adminUserAccount := accclients1.AccountV1{
Id: TestUsers.AdminUserId,
Login: TestUsers.AdminUserLogin,
Name: TestUsers.AdminUserName,
Active: true,
CreateTime: time.Time{},
}
accountsClient.CreateAccount("", &adminUserAccount)
user1Account := accclients1.AccountV1{
Id: TestUsers.User1Id,
Login: TestUsers.User1Login,
Name: TestUsers.User1Name,
Active: true,
CreateTime: time.Time{},
}
accountsClient.CreateAccount("", &user1Account)
user2Account := accclients1.AccountV1{
Id: TestUsers.User2Id,
Login: TestUsers.User2Login,
Name: TestUsers.User2Name,
Active: true,
CreateTime: time.Time{},
}
accountsClient.CreateAccount("", &user2Account)
// Create opened sessions
dependency, _ = c.GetOneRequired(cref.NewDescriptor("pip-services-sessions", "client", "*", "*", "*"))
sessionsClient, ok2 := dependency.(sessclients1.ISessionsClientV1)
if !ok2 {
panic("TestReferences: Cant't resolv dependency 'client' to ISessionsClientV1")
}
adminUserData := c.cloneAccountToUserData(&adminUserAccount)
adminUserData.Roles = []string{"admin"}
session, _ := sessionsClient.OpenSession(
"", TestUsers.AdminUserId, TestUsers.AdminUserName,
"", "", adminUserData, nil)
session.Id = TestUsers.AdminUserSessionId
user1Data := c.cloneAccountToUserData(&user1Account)
user1Data.Roles = make([]string, 0)
session, _ = sessionsClient.OpenSession(
"", TestUsers.User1Id, TestUsers.User1Name,
"", "", user1Data, nil)
session.Id = TestUsers.User1SessionId
user2Data := c.cloneAccountToUserData(&user2Account)
user2Data.Roles = make([]string, 0)
session, _ = sessionsClient.OpenSession(
"", TestUsers.User2Id, TestUsers.User2Name,
"", "", user2Data, nil)
session.Id = TestUsers.User2SessionId
}
func (c *TestReferences) cloneAccountToUserData(account *accclients1.AccountV1) *operations1.SessionUserV1 {
if account == nil {
return nil
}
return &operations1.SessionUserV1{
Id: account.Id,
Login: account.Login,
Name: account.Name,
/* Activity tracking */
CreateTime: account.CreateTime,
/* User preferences */
TimeZone: account.TimeZone,
Language: account.Language,
Theme: account.Theme,
/* Custom fields */
CustomHdr: account.CustomHdr,
CustomDat: account.CustomDat,
}
}
/test/fixture/ReferencesTest.py
# -*- coding: utf-8 -*-
import datetime
from copy import deepcopy
from pip_services3_commons.config.ConfigParams import ConfigParams
from pip_services3_commons.refer.Descriptor import Descriptor
from pip_services3_container.refer.ManagedReferences import ManagedReferences
from pip_services3_rpc.build.DefaultRpcFactory import DefaultRpcFactory
from pip_facades_sample_python.build.ClientFacadeFactory import ClientFacadeFactory
from pip_facades_sample_python.clients.version1.AccountV1 import AccountV1
from pip_facades_sample_python.clients.version1.AccountsMemoryClientV1 import AccountsMemoryClientV1
from pip_facades_sample_python.clients.version1.EmailSettingsMemoryClientV1 import EmailSettingsMemoryClientV1
from pip_facades_sample_python.clients.version1.IAccountsClientV1 import IAccountsClientV1
from pip_facades_sample_python.clients.version1.IRolesClientV1 import IRolesClientV1
from pip_facades_sample_python.clients.version1.ISessionsClientV1 import ISessionsClientV1
from pip_facades_sample_python.clients.version1.ISitesClientV1 import ISitesClientV1
from pip_facades_sample_python.clients.version1.PasswordsNullClientV1 import PasswordsNullClientV1
from pip_facades_sample_python.clients.version1.RolesMemoryClientV1 import RolesMemoryClientV1
from pip_facades_sample_python.clients.version1.SessionsMemoryClientV1 import SessionsMemoryClientV1
from pip_facades_sample_python.clients.version1.SiteV1 import SiteV1
from pip_facades_sample_python.clients.version1.SitesMemoryClientV1 import SitesMemoryClientV1
from pip_facades_sample_python.services.version1.FacadeServiceV1 import FacadeServiceV1
from pip_facades_sample_python.services.version2.FacadeServiceV2 import FacadeServiceV2
from test.fixtures.TestSites import TestSites
from test.fixtures.TestUsers import TestUsers
class ReferencesTest(ManagedReferences):
def __init__(self):
super(ReferencesTest, self).__init__()
self._factory = ClientFacadeFactory()
self.__append_dependencies()
self.__configure_service()
self.__create_user_and_sessions()
def __append_dependencies(self):
# Add factories
self.put(None, ClientFacadeFactory())
self.put(None, DefaultRpcFactory())
# Add service
self.put(None, FacadeServiceV1())
self.put(None, FacadeServiceV2())
# Add services
self.put(Descriptor('pip-services-accounts', 'client', 'memory', 'default', '*'), AccountsMemoryClientV1())
self.put(Descriptor('pip-services-sessions', 'client', 'memory', 'default', '*'), SessionsMemoryClientV1())
self.put(Descriptor('pip-services-passwords', 'client', 'null', 'default', '*'), PasswordsNullClientV1())
self.put(Descriptor('pip-services-roles', 'client', 'memory', 'default', '*'), RolesMemoryClientV1())
self.put(Descriptor('pip-services-emailsettings', 'client', 'memory', 'default', '*'),
EmailSettingsMemoryClientV1())
self.put(Descriptor('pip-services-sites', 'client', 'direct', 'memory', '*'), SitesMemoryClientV1())
def __configure_service(self):
# Configure Facade service
service = self.get_one_required(Descriptor('pip-services', 'endpoint', 'http', 'default', '*'))
service.configure(ConfigParams.from_tuples(
'root_path', '', # '/api/v1',
'connection.protocol', 'http',
'connection.host', 'localhost',
'connection.port', 3000
))
def __create_user_and_sessions(self):
# Create accounts
accounts_client: IAccountsClientV1 = self.get_one_required(
Descriptor('pip-services-accounts', 'client', '*', '*', '*'))
admin_user_account = AccountV1(
id=TestUsers.AdminUserId,
login=TestUsers.AdminUserLogin,
name=TestUsers.AdminUserName,
active=True,
create_time=datetime.datetime.now()
)
accounts_client.create_account(None, admin_user_account)
user_1_account = AccountV1(
id=TestUsers.User1Id,
login=TestUsers.User1Login,
name=TestUsers.User1Name,
active=True,
create_time=datetime.datetime.now()
)
accounts_client.create_account(None, user_1_account)
user_2_account = AccountV1(
id=TestUsers.User2Id,
login=TestUsers.User2Login,
name=TestUsers.User2Name,
active=True,
create_time=datetime.datetime.now()
)
accounts_client.create_account(None, user_2_account)
# Create test site(s)
sites_client: ISitesClientV1 = self.get_one_required(Descriptor('pip-services-sites', 'client', '*', '*', '*'))
site1 = SiteV1(
id=TestSites.Site1Id,
name=TestSites.Site1Name
)
sites_client.create_site(None, site1)
# Create user roles
roles_client: IRolesClientV1 = self.get_one_required(Descriptor('pip-services-roles', 'client', '*', '*', '*'))
roles_client.set_roles(None, TestUsers.AdminUserId, ['admin', TestSites.Site1Id + ':admin'])
roles_client.set_roles(None, TestUsers.User1Id, [TestSites.Site1Id + ':manager'])
roles_client.set_roles(None, TestUsers.User2Id, [TestSites.Site1Id + ':user'])
# Create opened sessions
sessions_client: ISessionsClientV1 = self.get_one_required(
Descriptor('pip-services-sessions', 'client', '*', '*', '*'))
admin_user_data = deepcopy(admin_user_account)
admin_user_data.roles = ['admin', TestSites.Site1Id + ':admin']
sessions_client.open_session(None, TestUsers.AdminUserId, TestUsers.AdminUserName,
None, None, admin_user_data, None).id = TestUsers.AdminUserSessionId
user_1_data = deepcopy(user_1_account)
user_1_data.roles = [TestSites.Site1Id + ':manager']
sessions_client.open_session(None, TestUsers.User1Id, TestUsers.User1Name,
None, None, user_1_data, None, ).id = TestUsers.User1SessionId
user_2_data = deepcopy(user_2_account)
user_2_data.roles = [TestSites.Site1Id + ':manager']
sessions_client.open_session(None, TestUsers.User2Id, TestUsers.User2Name,
None, None, user_2_data, None, ).id = TestUsers.User2SessionId
Now, let’s create a file with a test client, which will help us test our user and session related operations. Place the code below into a file named RestClientTest:
import { ApplicationExceptionFactory, UnknownException } from "pip-services3-commons-nodex";
let restify = require('restify-clients');
export class TestRestClient {
private _rest: any;
public constructor() {
let url = 'http://localhost:3000';
this._rest = restify.createJsonClient({ url: url, version: '*', requestTimeout: 1500 });
}
protected async call(method: string, route: string, data?: any): Promise<any> {
method = method.toLowerCase();
return new Promise((resolve, reject) => {
let action = (err, req, res, data) => {
// Handling 204 codes
if (res && res.statusCode == 204)
resolve(null);
else if (err == null)
resolve(data);
else {
// Restore application exception
if (data != null)
err = ApplicationExceptionFactory.create(data).withCause(err);
reject(err);
}
};
if (method == 'get') this._rest.get(route, action);
else if (method == 'head') this._rest.head(route, action);
else if (method == 'post') this._rest.post(route, data, action);
else if (method == 'put') this._rest.put(route, data, action);
else if (method == 'patch') this._rest.patch(route, data, action);
else if (method == 'delete' || method == 'del') this._rest.del(route, action);
else {
let err = new UnknownException('UNSUPPORTED_METHOD', 'Method is not supported by Test REST client'
).withDetails('verb', method);
reject(err);
}
});
}
public async get(path: string): Promise<any> {
delete this._rest.headers['x-session-id'];
return await this.call('get', path);
}
public async head(path: string): Promise<any> {
delete this._rest.headers['x-session-id'];
return await this.call('head', path);
}
public async post(path: string, params: any): Promise<any> {
delete this._rest.headers['x-session-id'];
return await this.call('post', path, params);
}
public async put(path: string, params: any): Promise<any> {
delete this._rest.headers['x-session-id'];
return await this.call('put', path, params);
}
public async del(path: string): Promise<any> {
delete this._rest.headers['x-session-id'];
return await this.call('del', path);
}
public async getAsUser(sessionId: string, path: string): Promise<any> {
this._rest.headers['x-session-id'] = sessionId;
return await this.call('get', path);
}
public async headAsUser(sessionId: string, path: string): Promise<any> {
this._rest.headers['x-session-id'] = sessionId;
return await this.call('head', path);
}
public async postAsUser(sessionId: string, path: string, params: any): Promise<any> {
this._rest.headers['x-session-id'] = sessionId;
return await this.call('post', path, params);
}
public async putAsUser(sessionId: string, path: string, params: any): Promise<any> {
this._rest.headers['x-session-id'] = sessionId;
return await this.call('put', path, params);
}
public async delAsUser(sessionId: string, path: string, params?: any): Promise<any> {
this._rest.headers['x-session-id'] = sessionId;
return await this.call('del', path, params);
}
}
/test/fixtures/TestRestClient.cs
using PipServices3.Commons.Convert;
using PipServices3.Commons.Data.Mapper;
using PipServices3.Commons.Errors;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Pip.Services.SampleFacade.Fixtures
{
public class TestRestClient
{
private HttpClient _httpClient;
public TestRestClient()
{
_httpClient = new HttpClient();
}
public async Task<T> GetAsync<T>(string route, dynamic body = null)
{
return await InvokeAsync<T>(HttpMethod.Get, route, body);
}
public async Task<T> PostAsync<T>(string route, dynamic body = null)
{
return await InvokeAsync<T>(HttpMethod.Post, route, body);
}
public async Task<T> GetAsUserAsync<T>(string sessionId, string route, dynamic body = null)
{
return await InvokeAsUserAsync<T>(sessionId, HttpMethod.Get, route, body);
}
public async Task<T> PostAsUserAsync<T>(string sessionId, string route, dynamic body = null)
{
return await InvokeAsUserAsync<T>(sessionId, HttpMethod.Post, route, body);
}
public async Task<T> PutAsUserAsync<T>(string sessionId, string route, dynamic body = null)
{
return await InvokeAsUserAsync<T>(sessionId, HttpMethod.Put, route, body);
}
public async Task<T> DelAsUserAsync<T>(string sessionId, string route, dynamic body = null)
{
return await InvokeAsUserAsync<T>(sessionId, HttpMethod.Delete, route, body);
}
public async Task<T> InvokeAsync<T>(HttpMethod method, string route, dynamic body = null)
{
var requestUri = $"http://localhost:3000" + route;
var request = new HttpRequestMessage(method, requestUri);
if (body != null)
{
request.Content = new StringContent(JsonConverter.ToJson(body), Encoding.UTF8, "application/json");
}
var response = await _httpClient.SendAsync(request);
var responseValue = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
var errorDescription = JsonConverter.FromJson<ErrorDescription>(responseValue);
throw ApplicationExceptionFactory.Create(errorDescription);
}
return JsonConverter.FromJson<T>(responseValue);
}
public async Task<T> InvokeAsUserAsync<T>(string sessionId, HttpMethod method, string route, dynamic body = null)
{
var requestUri = $"http://localhost:3000" + route;
var request = new HttpRequestMessage(method, requestUri);
request.Headers.Add("x-session-id", sessionId);
if (body != null)
{
request.Content = new StringContent(JsonConverter.ToJson(body), Encoding.UTF8, "application/json");
}
var response = await _httpClient.SendAsync(request);
var responseValue = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
var errorDescription = JsonConverter.FromJson<ErrorDescription>(responseValue);
throw ApplicationExceptionFactory.Create(errorDescription);
}
return JsonConverter.FromJson<T>(responseValue);
}
}
}
package test_fixture
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
cerr "github.com/pip-services3-gox/pip-services3-commons-gox/errors"
)
type TestRestClient struct {
url string
}
func NewTestRestClient() *TestRestClient {
c := TestRestClient{
url: "http://localhost:3000",
}
return &c
}
func (c *TestRestClient) invoke(method string,
route string, headers map[string]string, body interface{}, result interface{}) error {
var url string = c.url + route
method = strings.ToUpper(method)
var bodyReader *bytes.Reader = bytes.NewReader(make([]byte, 0, 0))
if body != nil {
jsonBody, _ := json.Marshal(body)
bodyReader = bytes.NewReader(jsonBody)
}
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
return err
}
// Set headers
req.Header.Set("Accept", "application/json")
if headers != nil && len(headers) > 0 {
for k, v := range headers {
req.Header.Set(k, v)
}
}
client := http.Client{}
response, respErr := client.Do(req)
if respErr != nil {
return respErr
}
if response.StatusCode == 204 {
return nil
}
resBody, bodyErr := ioutil.ReadAll(response.Body)
if bodyErr != nil {
return bodyErr
}
if response.StatusCode >= 400 {
appErr := cerr.ApplicationError{}
json.Unmarshal(resBody, &appErr)
return &appErr
}
if result == nil {
return nil
}
jsonErr := json.Unmarshal(resBody, result)
return jsonErr
}
func (c *TestRestClient) Get(path string, result interface{}) error {
return c.invoke("get", path, nil, nil, result)
}
func (c *TestRestClient) Head(path string, result interface{}) error {
return c.invoke("head", path, nil, nil, result)
}
func (c *TestRestClient) Post(path string, params interface{}, result interface{}) error {
return c.invoke("post", path, nil, params, result)
}
func (c *TestRestClient) Put(path string, params interface{}, result interface{}) error {
return c.invoke("put", path, nil, params, result)
}
func (c *TestRestClient) Del(path string, result interface{}) error {
return c.invoke("delete", path, nil, nil, result)
}
func (c *TestRestClient) GetAsUser(sessionId string, path string, result interface{}) error {
return c.invoke("get", path, map[string]string{"x-session-id": sessionId}, nil, result)
}
func (c *TestRestClient) HeadAsUser(sessionId string, path string, result interface{}) error {
return c.invoke("head", path, map[string]string{"x-session-id": sessionId}, nil, result)
}
func (c *TestRestClient) PostAsUser(sessionId string, path string, params interface{}, result interface{}) error {
return c.invoke("post", path, map[string]string{"x-session-id": sessionId}, params, result)
}
func (c *TestRestClient) PutAsUser(sessionId string, path string, params interface{}, result interface{}) error {
return c.invoke("put", path, map[string]string{"x-session-id": sessionId}, params, result)
}
func (c *TestRestClient) DelAsUser(sessionId string, path string, result interface{}) error {
return c.invoke("delete", path, map[string]string{"x-session-id": sessionId}, nil, result)
}
/test/fixture/RestClientTest.py
# -*- coding: utf-8 -*-
import requests
class RestClientTest:
_rest = None
headers = {'Content-type': 'application/json'}
url = 'http://localhost:3000'
def __init__(self):
self._rest = requests.Session()
def get(self, path):
response = self._rest.request('GET', self.url + path, headers=self.headers)
return response
def head(self, path):
response = self._rest.request('HEAD', self.url + path, headers=self.headers)
return response
def post(self, path, params):
response = self._rest.request('POST', self.url + path, json=params, headers=self.headers)
return response
def put(self, path, params):
response = self._rest.request('PUT', self.url + path, json=params, headers=self.headers)
return response
def delete(self, path, params=None):
response = self._rest.request('DELETE', self.url + path, json=params, headers=self.headers)
return response
def get_as_user(self, session_id, path):
self.headers.update({'x-session-id': session_id})
# self._rest.request('GET', path, headers=self.headers)
return self._rest.get(self.url + path, headers=self.headers)
def head_as_user(self, session_id, path):
self.headers.update({'x-session-id': session_id})
return self._rest.head(self.url + path, headers=self.headers)
def post_as_user(self, session_id, path, params):
self.headers.update({'x-session-id': session_id})
return self._rest.post(self.url + path, json=params, headers=self.headers)
def put_as_user(self, session_id, path, params):
self.headers.update({'x-session-id': session_id})
return self._rest.put(self.url + path, json=params, headers=self.headers)
def delete_as_user(self, session_id, path):
self.headers.update({'x-session-id': session_id})
return self._rest.delete(self.url + path, headers=self.headers)
Lastly, define some test users in a file named TestUsers.py, as shown below:
/test/fixture/TestUsers.ts
export class TestUsers {
public static readonly AdminUserId: string = '1';
public static readonly AdminUserName: string = 'Admin User';
public static readonly AdminUserLogin: string = 'admin';
public static readonly AdminUserPassword: string = 'pwd123';
public static readonly AdminUserSessionId: string = '111';
public static readonly User1Id: string = '2';
public static readonly User1Name: string = 'User #1';
public static readonly User1Login: string = 'user1';
public static readonly User1Password: string = 'pwd123';
public static readonly User1SessionId: string = '222';
public static readonly User2Id: string = '3';
public static readonly User2Name: string = 'User #2';
public static readonly User2Login: string = 'user2';
public static readonly User2Password: string = 'pwd123';
public static readonly User2SessionId: string = '333';
};
/test/fixtures/TestUsers.cs
nnamespace Pip.Services.SampleFacade.Fixtures
{
public static class TestUsers
{
public static readonly string AdminUserId = "1";
public static readonly string AdminUserName = "Admin User";
public static readonly string AdminUserLogin = "admin";
public static readonly string AdminUserPassword = "pwd123";
public static readonly string AdminUserSessionId = "111";
public static readonly string User1Id = "2";
public static readonly string User1Name = "User #1";
public static readonly string User1Login = "user1";
public static readonly string User1Password = "pwd123";
public static readonly string User1SessionId = "222";
public static readonly string User2Id = "3";
public static readonly string User2Name = "User #2";
public static readonly string User2Login = "user2";
public static readonly string User2Password = "pwd123";
public static readonly string User2SessionId = "333";
}
}
/test/fixture/TestUsers.go
package test_fixture
var TestUsers tTestUsers = NewTTestUsers()
type tTestUsers struct {
AdminUserId string
AdminUserName string
AdminUserLogin string
AdminUserPassword string
AdminUserSessionId string
User1Id string
User1Name string
User1Login string
User1Password string
User1SessionId string
User2Id string
User2Name string
User2Login string
User2Password string
User2SessionId string
}
func NewTTestUsers() tTestUsers {
c := tTestUsers{
AdminUserId: "1",
AdminUserName: "Admin User",
AdminUserLogin: "admin",
AdminUserPassword: "pwd123",
AdminUserSessionId: "111",
User1Id: "2",
User1Name: "User #1",
User1Login: "user1",
User1Password: "pwd123",
User1SessionId: "222",
User2Id: "3",
User2Name: "User #2",
User2Login: "user2",
User2Password: "pwd123",
User2SessionId: "333",
}
return c
}
/test/fixture/TestUsers.py
# -*- coding: utf-8 -*-
class TestUsers:
AdminUserId: str = '1'
AdminUserName: str = 'Admin User'
AdminUserLogin: str = 'admin'
AdminUserPassword: str = 'pwd123'
AdminUserSessionId: str = '111'
User1Id: str = '2'
User1Name: str = 'User #1'
User1Login: str = 'user1'
User1Password: str = 'pwd123'
User1SessionId: str = '222'
User2Id: str = '3'
User2Name: str = 'User #2'
User2Login: str = 'user2'
User2Password: str = 'pwd123'
User2SessionId: str = '333'
Now we can move on to the tests themselves. Create the following files in the folder test/operations:
test_BeaconsRoutesV1 - for testing business logic operations of the Beacons microservice:
/test/operations/version1/BeaconsRoutesV1.test.ts
const assert = require('chai').assert;
import { DataPage } from 'pip-services3-commons-nodex';
import { Descriptor } from 'pip-services3-commons-nodex';
import { BeaconV1 } from '../../../src/clients/version1/BeaconV1';
import { BeaconsMemoryClientV1 } from '../../../src/clients/version1/BeaconsMemoryClientV1';
import { TestUsers } from '../../fixtures/TestUsers';
import { TestReferences } from '../../fixtures/TestReferences';
import { TestRestClient } from '../../fixtures/TestRestClient';
let BEACON1: BeaconV1 = {
id: '1',
udi: '000001',
site_id: '1',
label: 'TestBeacon1',
center: { type: 'Point', coordinates: [0, 0] },
radius: 50
};
let BEACON2: BeaconV1 = {
id: '2',
udi: '000002',
site_id: '1',
label: 'TestBeacon2',
center: { type: 'Point', coordinates: [2, 2] },
radius: 70
};
let BEACON3: BeaconV1 = {
id: '3',
udi: '000003',
site_id: '2',
label: 'TestBeacon3',
center: { type: 'Point', coordinates: [10, 10] },
radius: 50
};
suite('BeaconsOperationsV1', () => {
let references: TestReferences;
let rest: TestRestClient;
setup(async () => {
rest = new TestRestClient();
references = new TestReferences();
references.put(new Descriptor('beacons', 'client', 'memory', 'default', '1.0'), new BeaconsMemoryClientV1());
await references.open(null);
});
teardown(async () => {
await references.close(null);
});
test('should perform beacon operations', async () => {
let beacon1, beacon2, beacon3: BeaconV1;
// Create one beacon
let beacon = await rest.postAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON1.site_id + '/beacons',
BEACON1,
);
assert.isObject(beacon);
assert.equal(beacon.site_id, BEACON1.site_id);
assert.equal(beacon.udi, BEACON1.udi);
assert.equal(beacon.label, BEACON1.label);
assert.isNotNull(beacon.center);
beacon1 = beacon;
// Create another beacon
beacon = await rest.postAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON2.site_id + '/beacons',
BEACON2
);
assert.isObject(beacon);
assert.equal(beacon.site_id, BEACON2.site_id);
assert.equal(beacon.udi, BEACON2.udi);
assert.equal(beacon.label, BEACON2.label);
assert.isNotNull(beacon.center);
beacon2 = beacon;
// Create yet another beacon
beacon = await rest.postAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON3.site_id + '/beacons',
BEACON3
);
assert.isObject(beacon);
assert.equal(beacon.site_id, BEACON3.site_id);
assert.equal(beacon.udi, BEACON3.udi);
assert.equal(beacon.label, BEACON3.label);
assert.isNotNull(beacon.center);
beacon3 = beacon;
// Get all beacons
let page: DataPage<BeaconV1> = await rest.getAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON1.site_id + '/beacons'
);
assert.isObject(page);
assert.lengthOf(page.data, 2);
// Calculate positions
let position = await rest.postAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON1.site_id + '/beacons/calculate_position',
{
site_id: BEACON1.site_id,
udis: [BEACON1.udi]
}
);
assert.isObject(position);
assert.equal(position.type, 'Point');
// Validate beacon udi
let result = await rest.postAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + beacon1.site_id + '/beacons/validate_udi?udi=' + beacon1.udi,
{},
);
assert.equal(result, beacon1.id);
// Update the beacon
beacon1.label = 'ABC';
beacon = await rest.putAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + beacon1.site_id + '/beacons/' + beacon1.id,
beacon1
);
assert.isObject(beacon);
assert.equal(beacon.label, 'ABC');
// Delete beacon
beacon = await rest.delAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + beacon1.site_id + '/beacons/' + beacon1.id
);
assert.equal(beacon.id, beacon1.id);
// Try to get delete beacon
result = await rest.getAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sites/' + beacon1.site_id + '/beacons/' + beacon1.id
);
assert.isNull(result);
});
});
/test/operations/version1/BeaconsRoutesV1Test.cs
using Pip.Services.SampleFacade.Clients.Version1;
using Pip.Services.SampleFacade.Fixtures;
using PipServices3.Commons.Data;
using PipServices3.Commons.Refer;
using System;
using System.Threading.Tasks;
using Xunit;
namespace Pip.Services.SampleFacade.Operations.Version1
{
[Collection("Sequential")]
public class BeaconsRoutesV1Test: IDisposable
{
BeaconV1 BEACON1 = new()
{
Id = "1",
Udi = "000001",
SiteId = "1",
Label = "TestBeacon1",
Center = new CenterObjectV1 { Type = "Point", Coordinates = new double[] { 0, 0 } },
Radius = 50
};
BeaconV1 BEACON2 = new()
{
Id = "2",
Udi = "000002",
SiteId = "1",
Label = "TestBeacon2",
Center = new CenterObjectV1 { Type = "Point", Coordinates = new double[] { 2, 2 } },
Radius = 70
};
BeaconV1 BEACON3 = new()
{
Id = "3",
Udi = "000003",
SiteId = "2",
Label = "TestBeacon3",
Center = new CenterObjectV1 { Type = "Point", Coordinates = new double[] { 10, 10 } },
Radius = 50
};
private readonly TestReferences references;
private readonly TestRestClient rest;
public BeaconsRoutesV1Test()
{
rest = new TestRestClient();
references = new TestReferences();
references.Put(new Descriptor("beacons", "client", "memory", "default", "1.0"), new BeaconsMemoryClientV1());
references.OpenAsync(null).Wait();
}
public void Dispose()
{
references.CloseAsync(null).Wait();
}
[Fact]
public async Task It_Should_Perform_Beacon_OperationsAsync()
{
BeaconV1 beacon1, beacon2, beacon3;
// Create one beacon
var beacon = await rest.PostAsUserAsync<BeaconV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + BEACON1.SiteId + "/beacons",
BEACON1);
Assert.NotNull(beacon);
Assert.Equal(beacon.SiteId, BEACON1.SiteId);
Assert.Equal(beacon.Udi, BEACON1.Udi);
Assert.Equal(beacon.Label, BEACON1.Label);
Assert.NotNull(beacon.Center);
beacon1 = beacon;
// Create another beacon
beacon = await rest.PostAsUserAsync<BeaconV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + BEACON2.SiteId + "/beacons",
BEACON2);
Assert.NotNull(beacon);
Assert.Equal(beacon.SiteId, BEACON2.SiteId);
Assert.Equal(beacon.Udi, BEACON2.Udi);
Assert.Equal(beacon.Label, BEACON2.Label);
Assert.NotNull(beacon.Center);
beacon2 = beacon;
// Create yet another beacon
beacon = await rest.PostAsUserAsync<BeaconV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + BEACON3.SiteId + "/beacons",
BEACON3);
Assert.NotNull(beacon);
Assert.Equal(beacon.SiteId, BEACON3.SiteId);
Assert.Equal(beacon.Udi, BEACON3.Udi);
Assert.Equal(beacon.Label, BEACON3.Label);
Assert.NotNull(beacon.Center);
beacon3 = beacon;
// Get all beacons
var page = await rest.GetAsUserAsync<DataPage<BeaconV1>>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + BEACON1.SiteId + "/beacons");
Assert.NotNull(page);
Assert.Equal(2, page.Data.Count);
// Calculate positions
var position = await rest.PostAsUserAsync<CenterObjectV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + BEACON1.SiteId + "/beacons/calculate_position",
new
{
site_id = BEACON1.SiteId,
udis = new string[] { BEACON1.Udi }
});
Assert.NotNull(position);
Assert.Equal("Point", position.Type);
// Validate beacon udi
var result = await rest.PostAsUserAsync<string>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + beacon1.SiteId + "/beacons/validate_udi?udi=" + beacon1.Udi);
Assert.Equal(beacon1.Id, result);
// Update the beacon
beacon1.Label = "ABC";
beacon = await rest.PutAsUserAsync<BeaconV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + beacon1.SiteId + "/beacons/" + beacon1.Id,
beacon1);
Assert.NotNull(beacon);
Assert.Equal("ABC", beacon.Label);
beacon1 = beacon;
// Delete beacon
await rest.DelAsUserAsync<BeaconV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + beacon1.SiteId + "/beacons/" + beacon1.Id);
// Try to get delete beacon
beacon = await rest.GetAsUserAsync<BeaconV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + beacon1.SiteId + "/beacons/" + beacon1.Id);
Assert.Null(beacon);
}
}
}
/test/operations/version1/BeaconsRoutesV1_test.go
package test_operations
import (
"testing"
testfixture "github.com/pip-services-samples/pip-samples-facade-go/test/fixtures"
data1 "github.com/pip-services-samples/service-beacons-gox/data/version1"
cdata "github.com/pip-services3-gox/pip-services3-commons-gox/data"
"github.com/stretchr/testify/assert"
)
type beaconsRestServiceV1Test struct {
BEACON1 *data1.BeaconV1
BEACON2 *data1.BeaconV1
references *testfixture.TestReferences
rest *testfixture.TestRestClient
}
func newBeaconsRestServiceV1Test() *beaconsRestServiceV1Test {
BEACON1 := &data1.BeaconV1{
Id: "1",
Udi: "00001",
Type: data1.AltBeacon,
SiteId: "1",
Label: "TestBeacon1",
Center: data1.GeoPointV1{Type: "Point", Coordinates: [][]float32{{0.0, 0.0}}},
Radius: 50,
}
BEACON2 := &data1.BeaconV1{
Id: "2",
Udi: "00002",
Type: data1.IBeacon,
SiteId: "1",
Label: "TestBeacon2",
Center: data1.GeoPointV1{Type: "Point", Coordinates: [][]float32{{2.0, 2.0}}},
Radius: 70,
}
return &beaconsRestServiceV1Test{
BEACON1: BEACON1,
BEACON2: BEACON2,
}
}
func (c *beaconsRestServiceV1Test) setup(t *testing.T) {
c.rest = testfixture.NewTestRestClient()
c.references = testfixture.NewTestReferences()
err := c.references.Open("")
if err != nil {
t.Error("Failed to open references", err)
}
}
func (c *beaconsRestServiceV1Test) teardown(t *testing.T) {
c.rest = nil
err := c.references.Close("")
if err != nil {
t.Error("Failed to close references", err)
}
}
func (c *beaconsRestServiceV1Test) testCrudOperations(t *testing.T) {
var beacon1 *data1.BeaconV1
var beacon data1.BeaconV1
err := c.rest.PostAsUser(testfixture.TestUsers.AdminUserSessionId, "/api/v1/beacons", c.BEACON1, &beacon)
assert.Nil(t, err)
assert.NotNil(t, beacon)
assert.Equal(t, c.BEACON1.Udi, beacon.Udi)
assert.Equal(t, c.BEACON1.SiteId, beacon.SiteId)
assert.Equal(t, c.BEACON1.Type, beacon.Type)
assert.Equal(t, c.BEACON1.Label, beacon.Label)
assert.NotNil(t, beacon.Center)
err = c.rest.PostAsUser(testfixture.TestUsers.AdminUserSessionId, "/api/v1/beacons", c.BEACON2, &beacon)
assert.Nil(t, err)
assert.NotNil(t, beacon)
assert.Equal(t, c.BEACON2.Udi, beacon.Udi)
assert.Equal(t, c.BEACON2.SiteId, beacon.SiteId)
assert.Equal(t, c.BEACON2.Type, beacon.Type)
assert.Equal(t, c.BEACON2.Label, beacon.Label)
assert.NotNil(t, beacon.Center)
var page data1.BeaconV1DataPage
err = c.rest.GetAsUser(testfixture.TestUsers.AdminUserSessionId, "/api/v1/beacons", &page)
assert.Nil(t, err)
assert.NotNil(t, page)
assert.Len(t, page.Data, 2)
beacon1 = page.Data[0]
// Update the beacon
beacon1.Label = "ABC"
err = c.rest.PutAsUser(testfixture.TestUsers.AdminUserSessionId, "/api/v1/beacons", beacon1, &beacon)
assert.Nil(t, err)
assert.NotNil(t, beacon)
assert.Equal(t, beacon1.Id, beacon.Id)
assert.Equal(t, "ABC", beacon.Label)
err = c.rest.GetAsUser(testfixture.TestUsers.User1SessionId, "/api/v1/beacons/udi/"+beacon1.Udi+"?user_id="+testfixture.TestUsers.User1Id, &beacon)
assert.Nil(t, err)
assert.NotNil(t, beacon)
assert.Equal(t, beacon1.Id, beacon.Id)
//Calculate position for one beacon
body := cdata.NewAnyValueMapFromTuples(
"site_id", "1",
"udis", []string{"00001"},
)
var position data1.GeoPointV1
err = c.rest.PostAsUser(testfixture.TestUsers.User1SessionId, "/api/v1/beacons/position", body.Value(), &position)
assert.Nil(t, err)
assert.NotNil(t, position)
assert.Equal(t, "Point", position.Type)
assert.Equal(t, (float32)(0.0), position.Coordinates[0][0])
assert.Equal(t, (float32)(0.0), position.Coordinates[0][1])
err = c.rest.DelAsUser(testfixture.TestUsers.AdminUserSessionId, "/api/v1/beacons/"+beacon1.Id, &beacon)
assert.Nil(t, err)
assert.NotNil(t, beacon)
assert.Equal(t, beacon1.Id, beacon.Id)
beacon = data1.BeaconV1{}
err = c.rest.GetAsUser(testfixture.TestUsers.User1SessionId, "/api/v1/beacons/"+beacon1.Id+"?user_id="+testfixture.TestUsers.User1Id, &beacon)
assert.Nil(t, err)
assert.NotNil(t, beacon)
assert.Empty(t, beacon)
}
func TestBeaconsRestServiceV1(t *testing.T) {
c := newBeaconsRestServiceV1Test()
c.setup(t)
t.Run("CRUD Operations", c.testCrudOperations)
c.teardown(t)
}
/test/operations/version1/test_BeaconsRoutesV1.py
# -*- coding: utf-8 -*-
from pip_services3_commons.convert import JsonConverter, TypeCode
from pip_services3_commons.refer import Descriptor
from pip_facades_sample_python.clients.version1.BeaconV1 import BeaconV1
from pip_facades_sample_python.clients.version1.BeaconsMemoryClientV1 import BeaconsMemoryClientV1
from test.fixtures.ReferencesTest import ReferencesTest
from test.fixtures.RestClientTest import RestClientTest
from test.fixtures.TestUsers import TestUsers
BEACON1 = BeaconV1(id="1",
site_id="1",
udi="00001",
label="TestBeacon1",
center={"type": 'Point', "coordinates": [0, 0]},
radius=50)
BEACON2 = BeaconV1(id="2",
site_id="1",
udi="00002",
label="TestBeacon2",
center={"type": 'Point', "coordinates": [2, 2]},
radius=70)
BEACON3 = BeaconV1(id="3",
site_id="2",
udi="00003",
label="TestBeacon3",
center={"type": 'Point', "coordinates": [10, 10]},
radius=50)
class TestBeaconsOperationsV1:
references: ReferencesTest = None
rest: RestClientTest = None
@classmethod
def setup_class(cls):
cls.rest = RestClientTest()
cls.references = ReferencesTest()
cls.references.put(Descriptor('beacons', 'client', 'memory', 'default', '1.0'),
BeaconsMemoryClientV1())
cls.references.open(None)
@classmethod
def teardown_class(cls):
cls.references.close(None)
def test_beacons_operations(self):
# Create one beacon
response = self.rest.post_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON1.site_id + '/beacons',
JsonConverter.to_json(BEACON1))
created_beacon = JsonConverter.from_json(TypeCode.Map, response.content)
beacon1 = created_beacon
assert response.status_code < 300
assert BEACON1.udi == created_beacon['udi']
assert BEACON1.id == created_beacon['id']
assert BEACON1.site_id == created_beacon['site_id']
assert created_beacon['center'] is not None
# Create the second beacon
response = self.rest.post_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON2.site_id + '/beacons',
JsonConverter.to_json(BEACON2))
assert response.status_code < 300
created_beacon = JsonConverter.from_json(TypeCode.Map, response.content)
assert BEACON2.udi == created_beacon['udi']
assert BEACON2.id == created_beacon['id']
assert BEACON2.site_id == created_beacon['site_id']
assert created_beacon['center'] is not None
# Create yet another beacon
response = self.rest.post_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON3.site_id + '/beacons',
JsonConverter.to_json(BEACON3))
assert response.status_code < 300
created_beacon = JsonConverter.from_json(TypeCode.Map, response.content)
assert BEACON3.udi == created_beacon['udi']
assert BEACON3.id == created_beacon['id']
assert BEACON3.site_id == created_beacon['site_id']
assert created_beacon['center'] is not None
# Get all beacons
response = self.rest.get_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON1.site_id + '/beacons', )
beacons = JsonConverter.from_json(TypeCode.Map, response.content)
assert len(beacons['data']) == 2
# Calculate position for one beacon
response = self.rest.post_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + BEACON1.site_id + '/beacons/calculate_position', {
'site_id': BEACON1.site_id,
'udis': [BEACON1.udi]
})
calc_position = JsonConverter.from_json(TypeCode.Map, response.content)
assert response.status_code < 300
assert calc_position['type'] == 'Point'
assert len(calc_position['coordinates']) == 2
# Validate beacon udi
response = self.rest.post_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + beacon1['site_id'] + '/beacons/validate_udi?udi=' +
beacon1['udi'],
{}, )
assert JsonConverter.from_json(TypeCode.Map, response.content)['id'] == beacon1['id']
# Update the beacon
BEACON1.label = 'ABC'
response = self.rest.put_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + beacon1['site_id'] + '/beacons/' + beacon1['id'],
JsonConverter.to_json(BEACON1))
updated_beacon = JsonConverter.from_json(TypeCode.Map, response.content)
beacon1 = updated_beacon
assert response.status_code < 300
assert BEACON1.id == updated_beacon['id']
assert updated_beacon['label'] == 'ABC'
# Delete the beacon
response = self.rest.delete_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + beacon1['site_id'] + '/beacons/' + beacon1['id'])
deleted_result = JsonConverter.from_json(TypeCode.Map, response.content)
assert deleted_result['id'] == BEACON1.id
# Try to get deleted beacon
response = self.rest.get_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sites/' + beacon1['site_id'] + '/beacons/' + beacon1['id'], )
assert response.status_code == 204
test_SessionsRoutesV1 - for testing user and session related operations:
/test/operations/version1/SessionsRoutesV1.test.ts
const assert = require('chai').assert;
import { TestReferences } from '../../fixtures/TestReferences';
import { TestUsers } from '../../fixtures/TestUsers';
import { TestRestClient } from '../../fixtures/TestRestClient';
suite('SessionRoutesV1', () => {
let USER = {
login: 'test',
name: 'Test User',
email: 'test@conceptual.vision',
password: 'test123'
};
let references: TestReferences;
let rest: TestRestClient;
setup(async () => {
rest = new TestRestClient();
references = new TestReferences();
await references.open(null);
});
teardown(async () => {
await references.close(null);
});
test('should signup new user', async () => {
let session = await rest.post('/api/v1/signup', USER);
assert.isNotNull(session);
assert.isDefined(session);
assert.isDefined(session.id);
assert.equal(session.user_name, USER.name);
});
test('should check login for signup', async () => {
// Check registered email
let err = null;
try {
await rest.get('/api/v1/signup/validate?login=' + TestUsers.User1Login)
} catch (ex) {
err = ex;
}
assert.isNotNull(err);
// Check not registered email
await rest.get('/api/v1/signup/validate?login=xxx@gmail.com');
});
test('should not signup with the same email', async () => {
// Sign up
await rest.post('/api/v1/signup', USER);
// Try to sign up again
let err = null;
try {
await rest.post('/api/v1/signup', USER);
} catch (ex) {
err = ex;
}
assert.isNotNull(err);
});
test('should signout', async () => {
await rest.post('/api/v1/signout', null);
});
test('should signin with email and password', async () => {
// Sign up
await rest.post('/api/v1/signup', USER);
// Sign in with username
await rest.post('/api/v1/signin',
{
login: USER.login,
password: USER.password
}
);
});
test('should get sessions as admin', async () => {
let page = await rest.getAsUser(
TestUsers.AdminUserSessionId,
'/api/v1/sessions?paging=1&skip=0&take=2',
);
assert.isObject(page);
});
test('should get user sessions as owner', async () => {
let page = await rest.getAsUser(
TestUsers.User1SessionId,
'/api/v1/sessions/' + TestUsers.User1Id + '?paging=1&skip=0&take=2'
);
assert.isObject(page);
});
test('should restore user sessions as owner', async () => {
let session = await rest.postAsUser(
TestUsers.User1SessionId,
'/api/v1/sessions/restore?session_id=' + TestUsers.User1SessionId,
{}
);
assert.isObject(session);
});
});
/test/operations/version1/SessionsRoutesV1Test.cs
using Pip.Services.SampleFacade.Clients.Version1;
using Pip.Services.SampleFacade.Fixtures;
using PipServices3.Commons.Data;
using PipServices3.Commons.Refer;
using System;
using System.Threading.Tasks;
using Xunit;
namespace Pip.Services.SampleFacade.Operations.Version1
{
[Collection("Sequential")]
public class SitesRoutesV1Test: IDisposable
{
SiteV1 SITE1 = new SiteV1
{
Id = "2",
Code = "111",
Name = "Site #1",
Description = "Test site #1",
CreateTime = DateTime.Now,
CreatorId = "123",
Active = true
};
SiteV1 SITE2 = new SiteV1
{
Id = "3",
Code = "222",
Name = "Site #2",
Description = "Test site #2",
CreateTime = DateTime.Now,
CreatorId = "123",
Active = true
};
private readonly TestReferences references;
private readonly TestRestClient rest;
public SitesRoutesV1Test()
{
rest = new TestRestClient();
references = new TestReferences();
references.Put(new Descriptor("iqs-services-facade", "operations", "sites", "default", "1.0"), new SitesOperationsV1());
references.OpenAsync(null).Wait();
}
public void Dispose()
{
references.CloseAsync(null).Wait();
}
[Fact]
public async Task It_Should_Perform_Site_OperationsAsync()
{
SiteV1 site1, site2;
// Create one site
var site = await rest.PostAsUserAsync<SiteV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites",
SITE1);
Assert.NotNull(site);
Assert.Equal(site.Name, SITE1.Name);
Assert.Equal(site.Description, SITE1.Description);
site1 = site;
// Create another site
site = await rest.PostAsUserAsync<SiteV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites",
SITE2);
Assert.NotNull(site);
Assert.Equal(site.Name, SITE2.Name);
Assert.Equal(site.Description, SITE2.Description);
site2 = site;
// Get all sites
var page = await rest.GetAsUserAsync<DataPage<SiteV1>>(
TestUsers.AdminUserSessionId,
"/api/v1/sites");
Assert.NotNull(page);
// Account for 1 test site
Assert.Equal(3, page.Data.Count);
// Find site by code
site = await rest.GetAsync<SiteV1>("/api/v1/sites/find_by_code?code=" + site1.Code);
Assert.NotNull(site);
Assert.Equal(site1.Id, site.Id);
// Validate site code
var result = await rest.PostAsUserAsync<string>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/validate_code?code=" + site1.Code);
Assert.Equal(site1.Id, result);
// Generate code
result = await rest.PostAsUserAsync<string>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + site1.Id + "/generate_code");
Assert.NotNull(result);
// Update the site
site1.Description = "Updated Content 1";
site1.Center = new CenterObjectV1 { Type = "Point", Coordinates = new double[] { 32, -110 } };
site1.Radius = 5;
site = await rest.PutAsUserAsync<SiteV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + site1.Id,
site1);
Assert.NotNull(site);
Assert.Equal("Updated Content 1", site.Description);
Assert.Equal(site1.Name, site.Name);
Assert.NotNull(site.Center);
Assert.NotNull(site.Radius);
site1 = site;
// Delete site
site = await rest.DelAsUserAsync<SiteV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + site1.Id);
Assert.NotNull(site);
// Try to get delete site
site = await rest.GetAsUserAsync<SiteV1>(
TestUsers.AdminUserSessionId,
"/api/v1/sites/" + site1.Id);
Assert.NotNull(site);
Assert.True(site.Deleted);
}
}
}
/test/operations/version1/SessionsRoutesV1_test.go
package test_operations
import (
"testing"
testfixture "github.com/pip-services-samples/pip-samples-facade-go/test/fixtures"
"github.com/stretchr/testify/assert"
)
type sessionRoutesV1Test struct {
references *testfixture.TestReferences
rest *testfixture.TestRestClient
user map[string]string
}
func newSessionRoutesV1Test() *sessionRoutesV1Test {
c := &sessionRoutesV1Test{
user: make(map[string]string, 0),
}
c.user["login"] = "test"
c.user["name"] = "Test User"
c.user["email"] = "test@conceptual.vision"
c.user["password"] = "test123"
return c
}
func (c *sessionRoutesV1Test) setup(t *testing.T) {
c.rest = testfixture.NewTestRestClient()
c.references = testfixture.NewTestReferences()
err := c.references.Open("")
if err != nil {
t.Error("Failed to open references", err)
}
}
func (c *sessionRoutesV1Test) teardown(t *testing.T) {
c.rest = nil
err := c.references.Close("")
if err != nil {
t.Error("Failed to close references", err)
}
}
func (c *sessionRoutesV1Test) testSignupNewUser(t *testing.T) {
session := make(map[string]interface{})
err := c.rest.Post("/api/v1/users/signup", c.user, &session)
assert.Nil(t, err)
assert.NotNil(t, session)
assert.NotNil(t, session["id"])
assert.Equal(t, session["user_name"], c.user["name"])
}
func (c *sessionRoutesV1Test) testNotSignupWithTheSameEmail(t *testing.T) {
// Sign up
session := make(map[string]interface{})
err := c.rest.Post("/api/v1/users/signup", c.user, &session)
assert.Nil(t, err)
// Try to sign up again
err = c.rest.Post("/api/v1/users/signup", c.user, &session)
assert.NotNil(t, err)
}
func (c *sessionRoutesV1Test) testShouldSignout(t *testing.T) {
result := make(map[string]interface{})
err := c.rest.Post("/api/v1/users/signout", nil, &result)
assert.Nil(t, err)
}
func (c *sessionRoutesV1Test) testShouldSigninWithEmailAndPassword(t *testing.T) {
// Sign up
session := make(map[string]interface{})
err := c.rest.Post("/api/v1/users/signup",
c.user, &session)
assert.Nil(t, err)
// Sign in with username
err = c.rest.Post("/api/v1/users/signin",
map[string]string{
"login": c.user["login"],
"password": c.user["password"],
}, &session)
assert.Nil(t, err)
}
func TestSignupNewUser(t *testing.T) {
c := newSessionRoutesV1Test()
c.setup(t)
t.Run("Signup New User", c.testSignupNewUser)
c.teardown(t)
}
func TestNotSignupWithTheSameEmail(t *testing.T) {
c := newSessionRoutesV1Test()
c.setup(t)
t.Run("Not Signup With The Same Email", c.testNotSignupWithTheSameEmail)
c.teardown(t)
}
func TestShouldSignout(t *testing.T) {
c := newSessionRoutesV1Test()
c.setup(t)
t.Run("Should Signout", c.testShouldSignout)
c.teardown(t)
}
func TestShouldSigninWithEmailAndPassword(t *testing.T) {
c := newSessionRoutesV1Test()
c.setup(t)
t.Run("Should Signin With Email And Password", c.testShouldSigninWithEmailAndPassword)
c.teardown(t)
}
/test/operations/version1/test_SessionsRoutesV1.py
# -*- coding: utf-8 -*-
import json
from pip_services3_commons.convert import JsonConverter, TypeCode
from test.fixtures.ReferencesTest import ReferencesTest
from test.fixtures.RestClientTest import RestClientTest
from test.fixtures.TestUsers import TestUsers
USER = {
'login': 'test',
'name': 'Test User',
'email': 'test@conceptual.vision',
'password': 'test123'
}
class TestSessionRoutesV1:
references: ReferencesTest = None
rest: RestClientTest = None
def setup_method(self):
self.rest = RestClientTest()
self.references = ReferencesTest()
self.references.open(None)
def teardown_method(self):
self.references.close(None)
def test_should_signup_new_user(self):
response = self.rest.post('/api/v1/signup', USER)
session = json.loads(response.content)
JsonConverter.from_json(TypeCode.Map, response.content)
assert session is not None
assert session['id'] is not None
assert session['user_name'] == USER['name']
def test_should_check_login_for_signup(self):
# Check registered email
response = self.rest.get('/api/v1/signup/validate?login=' + TestUsers.User1Login)
result = json.loads(response.content)
assert result['status'] == 400
assert result['code'] == "LOGIN_ALREADY_USED"
# Check not registered email
response = self.rest.get('/api/v1/signup/validate?login=xxx@gmail.com')
assert response.status_code == 204
assert response.content == b''
def test_should_not_signup_with_the_same_email(self):
# Sign up
response = self.rest.post('/api/v1/signup', USER)
session = json.loads(response.content)
assert response.status_code == 200
# Try to sign up again
response = self.rest.post('/api/v1/signup', USER)
result = json.loads(response.content)
assert result['status'] == 400
assert result['code'] == 'DUPLICATE_LOGIN'
def test_should_signout(self):
response = self.rest.post('/api/v1/signout', {})
assert response.status_code == 204
assert response.content == b''
def test_should_signin_with_email_and_password(self):
# Sign up
response = self.rest.post('/api/v1/signup', USER)
session = json.loads(response.content)
assert response.status_code == 200
assert isinstance(session, dict)
# Sign in with username
response = self.rest.post('/api/v1/signin', {
'login': USER['login'],
'password': USER['password']
})
session = json.loads(response.content)
assert response.status_code == 200
assert isinstance(session, dict)
def test_should_get_sessions_as_admin(self):
response = self.rest.get_as_user(TestUsers.AdminUserSessionId,
'/api/v1/sessions?paging=1&skip=0&take=2')
page = json.loads(response.content)
assert page is not None and page != {}
def test_should_get_user_sessions_as_owner(self):
response = self.rest.get_as_user(TestUsers.User1SessionId,
'/api/v1/sessions/' + TestUsers.User1Id + '?paging=1&skip=0&take=2', )
page = json.loads(response.content)
assert page is not None and page != {}
Run the tests using the following command:
npm run test
dotnet test
go test ./...
python test.py
Once all the tests pass successfully, you can move on to Step 8 - Running the facade - to learn how to deploy all of these microservices using Docker.