Skip to content

Commit

Permalink
tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Fabio Nappi committed Mar 15, 2024
1 parent 216bc5f commit 19060e7
Show file tree
Hide file tree
Showing 6 changed files with 138 additions and 29 deletions.
12 changes: 5 additions & 7 deletions src/lib/configurations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ import * as yaml from 'js-yaml'
import type { RuntimeConfig } from '../config'
import { evaluateAcl, resolveReferences } from '../sdk'
import type { Json } from '../sdk'
import { evaluateLanguage } from '../sdk/resolve-translations'
import { evaluateLanguage } from '../sdk/evaluate-language'

import type { AclContext } from './extract-acl-context'
import { extractAclContext } from './extract-acl-context'
import type { LanguageContext } from './language'
import { extractLanguageContext } from './language'
import type { LanguageContext } from './extract-language-context'
import { extractLanguageContext } from './extract-language-context'

type ExtensionOutput = '' | `.${string}`

Expand Down Expand Up @@ -90,18 +90,16 @@ const shouldManipulate = (extension: ExtensionOutput): extension is Extension =>
['.json', '.yaml', '.yml'].includes(extension)

async function configurationsHandler(request: FastifyRequest, filename: string, config: RuntimeConfig): Promise<ConfigurationResponse> {
const fileExtension = path.extname(filename) as ExtensionOutput
const aclContext = extractAclContext(config, request)

const bufferPromise = fsCache.get(filename) ?? fileLoader(filename)
fsCache.set(filename, bufferPromise)

const buffer = await bufferPromise

const fileExtension = path.extname(filename) as ExtensionOutput
if (!shouldManipulate(fileExtension)) {
return { fileBuffer: buffer }
}

const aclContext = extractAclContext(config, request)
const languageContext = extractLanguageContext(config, request.languages())
const dump = getDumper(fileExtension)
const json = await loadAs(fileExtension)(buffer, aclContext, languageContext)
Expand Down
16 changes: 16 additions & 0 deletions src/lib/language.ts → src/lib/extract-language-context.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Copyright 2022 Mia srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { LanguageConfig, RuntimeConfig } from '../config'

export interface LanguageContext {
Expand Down
36 changes: 14 additions & 22 deletions src/lib/test/serve-files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@ import { createSandbox } from 'sinon'

import type { EnvironmentVariables } from '../../schemas/environmentVariablesSchema'
import * as evaluateAcl from '../../sdk/evaluate-acl'
import * as evaluateLanguage from '../../sdk/evaluate-language'
import * as resolveReferences from '../../sdk/resolve-references'
import { baseVariables, createConfigFile, createTmpDir, setupFastify } from '../../utils/test-utils'

describe('Serve files', () => {
const sandbox = createSandbox()

let evaluateAclStub: SinonStub
let evaluateLanguageStub: SinonStub
let resolveReferencesStub: SinonStub
let random: string

Expand All @@ -40,6 +42,7 @@ describe('Serve files', () => {

before(async () => {
evaluateAclStub = sandbox.stub(evaluateAcl, 'evaluateAcl').returns({ evaluate: 'acl' })
evaluateLanguageStub = sandbox.stub(evaluateLanguage, 'evaluateLanguage').returns({ evaluate: 'language' })
resolveReferencesStub = sandbox.stub(resolveReferences, 'resolveReferences').resolves({ resolve: 'references' })
random = randomUUID()
const { name: configurations, cleanup: confCleanup } = await createTmpDir({
Expand Down Expand Up @@ -114,28 +117,11 @@ describe('Serve files', () => {
expect(evaluateAclStub.calledOnce).to.be.true
expect(evaluateAclStub.args[0]).to.deep.equal([{ foo: 'bar' }, ['admin', 'user'], ['users.post.write']])

expect(resolveReferencesStub.calledOnce).to.be.true
expect(resolveReferencesStub.args[0]).to.deep.equal([{ evaluate: 'acl' }])
})

it('should serve manipulated .yaml file', async () => {
const { payload, headers } = await fastify.inject({
headers: {
[baseVariables.GROUPS_HEADER_KEY]: 'admin,user',
[baseVariables.USER_PROPERTIES_HEADER_KEY]: JSON.stringify({ permissions: ['users.post.write'] }),
},
method: 'GET',
url: '/configurations/config.yaml',
})

expect(payload).to.deep.equal(yaml.dump({ resolve: 'references' }))
expect(headers['content-type']).to.equal('text/yaml')

expect(evaluateAclStub.calledOnce).to.be.true
expect(evaluateAclStub.args[0]).to.deep.equal([{ foo: 'bar' }, ['admin', 'user'], ['users.post.write']])
expect(evaluateLanguageStub.calledOnce).to.be.true
expect(evaluateLanguageStub.args[0]).to.deep.equal([{ evaluate: 'acl' }, undefined])

expect(resolveReferencesStub.calledOnce).to.be.true
expect(resolveReferencesStub.args[0]).to.deep.equal([{ evaluate: 'acl' }])
expect(resolveReferencesStub.args[0]).to.deep.equal([{ evaluate: 'language' }])
})

it('should serve manipulated .yaml file', async () => {
Expand All @@ -154,8 +140,11 @@ describe('Serve files', () => {
expect(evaluateAclStub.calledOnce).to.be.true
expect(evaluateAclStub.args[0]).to.deep.equal([{ foo: 'bar' }, ['admin', 'user'], ['users.post.write']])

expect(evaluateLanguageStub.calledOnce).to.be.true
expect(evaluateLanguageStub.args[0]).to.deep.equal([{ evaluate: 'acl' }, undefined])

expect(resolveReferencesStub.calledOnce).to.be.true
expect(resolveReferencesStub.args[0]).to.deep.equal([{ evaluate: 'acl' }])
expect(resolveReferencesStub.args[0]).to.deep.equal([{ evaluate: 'language' }])
})

it('should remove "definitions" key from manipulated file', async () => {
Expand All @@ -179,8 +168,11 @@ describe('Serve files', () => {
expect(evaluateAclStub.calledOnce).to.be.true
expect(evaluateAclStub.args[0]).to.deep.equal([{ foo: 'bar' }, ['admin', 'user'], ['users.post.write']])

expect(evaluateLanguageStub.calledOnce).to.be.true
expect(evaluateLanguageStub.args[0]).to.deep.equal([{ evaluate: 'acl' }, undefined])

expect(resolveReferencesStub.calledOnce).to.be.true
expect(resolveReferencesStub.args[0]).to.deep.equal([{ evaluate: 'acl' }])
expect(resolveReferencesStub.args[0]).to.deep.equal([{ evaluate: 'language' }])
})

it('should serve non-JSON file with proper `Content-Type` headers', async () => {
Expand Down
16 changes: 16 additions & 0 deletions src/sdk/resolve-translations.ts → src/sdk/evaluate-language.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Copyright 2022 Mia srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import cloneDeepWith from 'lodash.clonedeepwith'

import type { Json } from './types'
Expand Down
84 changes: 84 additions & 0 deletions src/sdk/test/evaluate-language.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright 2022 Mia srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { expect } from 'chai'

import { evaluateLanguage } from '../evaluate-language'
import type { Json } from '../types'

describe('Evaluate Language', () => {
interface Test {
expected: Json
json: Json
labelsMap?: Record<string, string>
message: string
}

const tests: Test[] = [
{
expected: { foo: 'bar' },
json: { foo: 'bar' },
message: 'should return input when no labels map',
},
{
expected: {
array: [0, false, 'translated array value'],
foo: 'bar',
parent: {
key: 'value',
nestedArray: ['first', 'translated nested array value'],
nestedParent: {
anotherNestedText: 'translated nested text',
nestedProp: true,
nestedText: 'translated nested text',
},
text: 'translated text',
},
title: 'translated title',
},
json: {
array: [0, false, 'main.array.value'],
foo: 'bar',
parent: {
key: 'value',
nestedArray: ['first', 'main.parent.array.value'],
nestedParent: {
anotherNestedText: 'main.parent.nested-parent.text',
nestedProp: true,
nestedText: 'main.parent.nested-parent.text',
},
text: 'main.parent.text',
},
title: 'main.title',
},
labelsMap: {
'main.array.value': 'translated array value',
'main.parent.array.value': 'translated nested array value',
'main.parent.nested-parent.text': 'translated nested text',
'main.parent.text': 'translated text',
'main.title': 'translated title',
},
message: 'should replace label values',
},
]

tests.forEach(({ expected, json, labelsMap, message }, index) => {
it(`#${index} - ${message}`, () => {
const result = evaluateLanguage(json, labelsMap)
expect(result).to.deep.equal(expected)
})
})
})
3 changes: 3 additions & 0 deletions src/test/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ const createEnvVars = (configPath: string): EnvironmentVariables => ({

const defaults = {
CONTENT_TYPE_MAP: defaultConfigs.CONTENT_TYPE_MAP,
DEFAULT_CONTENT_LANGUAGE: 'en',
LANGUAGES_CONFIG: [],
LANGUAGES_DIRECTORY_PATH: '/usr/static/languages',
PUBLIC_DIRECTORY_PATH: '/usr/static/public',
RESOURCES_DIRECTORY_PATH: '/usr/static/configurations',
USER_PROPERTIES_HEADER_KEY: 'miauserproperties',
Expand Down

0 comments on commit 19060e7

Please sign in to comment.