Skip to content

Commit

Permalink
Improve Azure provider unit tests (#382)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcAstr0 authored Aug 21, 2020
1 parent 9d4df10 commit 36d2069
Show file tree
Hide file tree
Showing 14 changed files with 2,162 additions and 556 deletions.
2 changes: 2 additions & 0 deletions packages/framework-provider-azure-infrastructure/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
"@azure/cosmos": "^3.7.3",
"@boostercloud/framework-provider-azure": "^0.6.0",
"@boostercloud/framework-types": "^0.6.0",
"@types/archiver": "^3.1.0",
"@types/needle": "^2.0.4",
"archiver": "^4.0.1",
"azure-arm-resource": "^7.3.0",
"azure-arm-website": "^5.7.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import ResourceManagementClient from 'azure-arm-resource/lib/resource/resourceManagementClient'
import { DeploymentExtended } from 'azure-arm-resource/lib/resource/models'

const fs = require('fs')
const archiver = require('archiver')
const os = require('os')
const needle = require('needle')
const uuid = require('uuid')
const path = require('path')
import * as fs from 'fs'
import * as os from 'os'
import * as uuid from 'uuid'
import * as path from 'path'
import * as archiver from 'archiver'
import * as needle from 'needle'

interface FunctionDefinition {
name: string
Expand Down
9 changes: 3 additions & 6 deletions packages/framework-provider-azure/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,10 @@ import { fetchReadModel, storeReadModel } from './library/read-model-adapter'
import { searchReadModel } from './library/searcher-adapter'
import { notifySubscription } from './library/subscription-adapter'

let cosmosClient: CosmosClient | undefined
if (process.env[environmentVarNames.cosmosDbConnectionString]) {
// @ts-ignore
cosmosClient = new CosmosClient(process.env[environmentVarNames.cosmosDbConnectionString])
} else {
cosmosClient = undefined
if (typeof process.env[environmentVarNames.cosmosDbConnectionString] === 'undefined') {
throw new Error('No Cosmos DB connection string has been found')
}
const cosmosClient = new CosmosClient(process.env[environmentVarNames.cosmosDbConnectionString] as string)

export const Provider: ProviderLibrary = {
// ProviderEventsLibrary
Expand Down
14 changes: 9 additions & 5 deletions packages/framework-provider-azure/src/library/events-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function rawEventsToEnvelopes(context: Context): Array<EventEnvelope> {
}

export async function readEntityEventsSince(
cosmosDb: CosmosClient | any,
cosmosDb: CosmosClient,
config: BoosterConfig,
logger: Logger,
entityTypeName: string,
Expand All @@ -22,7 +22,9 @@ export async function readEntityEventsSince(
): Promise<Array<EventEnvelope>> {
const fromTime = since ? since : originOfTime
const querySpec: SqlQuerySpec = {
query: `SELECT * FROM c WHERE c["${eventsStoreAttributes.partitionKey}"] = @partitionKey AND c["${eventsStoreAttributes.sortKey}"] > @fromTime ORDER BY c["${eventsStoreAttributes.sortKey}"] DESC`,
query:
`SELECT * FROM c WHERE c["${eventsStoreAttributes.partitionKey}"] = @partitionKey ` +
`AND c["${eventsStoreAttributes.sortKey}"] > @fromTime ORDER BY c["${eventsStoreAttributes.sortKey}"] DESC`,
parameters: [
{
name: '@partitionKey',
Expand All @@ -43,7 +45,7 @@ export async function readEntityEventsSince(
}

export async function readEntityLatestSnapshot(
cosmosDb: CosmosClient | any,
cosmosDb: CosmosClient,
config: BoosterConfig,
logger: Logger,
entityTypeName: string,
Expand All @@ -53,7 +55,9 @@ export async function readEntityLatestSnapshot(
.database(config.resourceNames.applicationStack)
.container(config.resourceNames.eventsStore)
.items.query({
query: `SELECT * FROM c WHERE c["${eventsStoreAttributes.partitionKey}"] = @partitionKey ORDER BY c["${eventsStoreAttributes.sortKey}"] DESC OFFSET 0 LIMIT 1`,
query:
`SELECT * FROM c WHERE c["${eventsStoreAttributes.partitionKey}"] = @partitionKey ` +
`ORDER BY c["${eventsStoreAttributes.sortKey}"] DESC OFFSET 0 LIMIT 1`,
parameters: [
{
name: '@partitionKey',
Expand All @@ -79,7 +83,7 @@ export async function readEntityLatestSnapshot(
}

export async function storeEvents(
cosmosDb: CosmosClient | any,
cosmosDb: CosmosClient,
eventEnvelopes: Array<EventEnvelope>,
config: BoosterConfig,
logger: Logger
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { CosmosClient } from '@azure/cosmos'
import { BoosterConfig, Logger, ReadModelInterface, UUID } from '@boostercloud/framework-types'

export async function fetchReadModel(
db: CosmosClient | any,
db: CosmosClient,
config: BoosterConfig,
logger: Logger,
readModelName: string,
Expand All @@ -11,7 +11,7 @@ export async function fetchReadModel(
const { resource } = await db
.database(config.resourceNames.applicationStack)
.container(config.resourceNames.forReadModel(readModelName))
.item(readModelID, readModelID)
.item(readModelID as string, readModelID)
.read()

logger.debug(
Expand All @@ -22,7 +22,7 @@ export async function fetchReadModel(
}

export async function storeReadModel(
db: CosmosClient | any,
db: CosmosClient,
config: BoosterConfig,
logger: Logger,
readModelName: string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { CosmosClient, SqlParameter, SqlQuerySpec } from '@azure/cosmos'
import { BoosterConfig, Filter, Logger, InvalidParameterError } from '@boostercloud/framework-types'

export async function searchReadModel(
cosmosDb: CosmosClient | any,
cosmosDb: CosmosClient,
config: BoosterConfig,
logger: Logger,
readModelName: string,
Expand Down
51 changes: 51 additions & 0 deletions packages/framework-provider-azure/test/helpers/event-helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { EventEnvelope } from '@boostercloud/framework-types'
import { random, date } from 'faker'
import { Context, ExecutionContext, Logger as AzureLogger, TraceContext } from '@azure/functions'

export function createMockEventEnvelopes(numOfEvents = 1): Array<EventEnvelope> {
return new Array(numOfEvents).fill(
{
version: random.number(),
entityID: random.uuid(),
kind: 'event',
value: {
id: random.uuid(),
},
typeName: random.word(),
entityTypeName: random.word(),
requestID: random.uuid(),
createdAt: date.past().toISOString(),
},
0,
numOfEvents
)
}

export function addMockSystemGeneratedProperties(eventEnvelopes: Array<EventEnvelope>): Array<EventEnvelope> {
return eventEnvelopes.map((eventEnvelope: EventEnvelope) => {
return {
...eventEnvelope,
id: random.uuid(),
_rid: random.alphaNumeric(24),
_self: `dbs/${random.alphaNumeric(8)}/colls/${random.alphaNumeric(12)}/docs/${random.alphaNumeric(24)}/`,
_etag: `"${random.uuid()}"`,
_attachments: 'attachments/',
_ts: ~~(date.past().getTime() / 1000),
}
})
}

export function wrapEventEnvelopesForCosmosDB(eventEnvelopes: Array<EventEnvelope>): Context {
return {
bindingData: {},
bindingDefinitions: [],
executionContext: {} as ExecutionContext,
invocationId: '',
log: {} as AzureLogger,
traceContext: {} as TraceContext,
done(err?: Error | string | null, result?: any): void {},
bindings: { rawEvent: eventEnvelopes },
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ReadModelInterface } from '@boostercloud/framework-types'
import { random } from 'faker'

export function createMockReadModel(): ReadModelInterface {
return {
id: random.uuid(),
some: 'object',
}
}
27 changes: 14 additions & 13 deletions packages/framework-provider-azure/test/library/api-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ import {
} from '@boostercloud/framework-types'
import { requestFailed } from '../../src/library/api-adapter'

describe('the requestFailed method', () => {
interface TestCase {
input: Error
expectedOutput: {
status: number
title: string
describe('API adapter', () => {
describe('The "requestFailed" method', () => {
interface TestCase {
input: Error
expectedOutput: {
status: number
title: string
}
}
}

it('returns a proper body with several errors', async () => {
const testCases: Array<TestCase> = [
{
input: new InvalidParameterError('error message'),
Expand Down Expand Up @@ -49,11 +49,12 @@ describe('the requestFailed method', () => {
]

for (const testCase of testCases) {
const testDescription = `In test case '${testCase.input.constructor.name}'`
const got = await requestFailed(testCase.input)
expect(got.status).to.be.equal(testCase.expectedOutput.status, testDescription)
const body = JSON.parse(got.body)
expect(body.title).to.be.equal(testCase.expectedOutput.title, testDescription)
it(`returns the proper body for error '${testCase.input.constructor.name}'`, async () => {
const got = await requestFailed(testCase.input)
expect(got.status).to.be.equal(testCase.expectedOutput.status)
const body = JSON.parse(got.body)
expect(body.title).to.be.equal(testCase.expectedOutput.title)
})
}
})
})
Loading

0 comments on commit 36d2069

Please sign in to comment.