Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
OrRosenblatt committed Nov 11, 2019
0 parents commit 254b4d5
Show file tree
Hide file tree
Showing 38 changed files with 7,263 additions and 0 deletions.
22 changes: 22 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: "Test typescript-action"
on:
pull_request:
push:
branches:
- master
- 'releases/*'

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1

- run: npm ci
- run: npm run build
- run: npm test
- uses: ./
with:
schema: ''
jsons: ''

96 changes: 96 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
__tests__/runner/*

# comment out in distribution branches
node_modules/

# Rest pulled from https://github.com/github/gitignore/blob/master/Node.gitignore
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# next.js build output
.next

# nuxt.js build output
.nuxt

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# IDE
.vscode
5 changes: 5 additions & 0 deletions .huskyrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"hooks": {
"pre-commit": "lint-staged"
}
}
6 changes: 6 additions & 0 deletions .lintstagedrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"**/*.{ts,js,json}": [
"prettier --write",
"git add"
]
}
6 changes: 6 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package.json
package-lock.json
tsconfig.json
node_modules
dist
lib
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
trailingComma: es5
singleQuote: true
printWidth: 120
tabWidth: 4
bracketSpacing: true
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

The MIT License (MIT)

Copyright (c) 2018 GitHub, Inc. and contributors

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.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Github Action: Validate JSON
// TODO://
46 changes: 46 additions & 0 deletions __tests__/json-file-reader.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { getJson } from '../src/json-file-reader';
import excepted from './mocks/tested-data/valid.json';
import { InvalidJsonFileError } from '../src/errors';

const mocks_dir = './__tests__/mocks';

describe('Process a JSON file', () => {
test('should return a valid JSON when procesings valid JSON file', async () => {
const validJsonFile = 'tested-data/valid.json';

const result = await getJson(mocks_dir, validJsonFile);
expect(typeof result).toBe('object');

Object.keys(excepted).forEach(key => {
expect(result).toHaveProperty(key);
expect(result[key]).toEqual(excepted[key]);
});
});

test('should throw an error when procesing invalid JSON file', async () => {
const invalidJsonFile = 'tested-data/invalid_by_format.json';

const task = getJson(mocks_dir, invalidJsonFile);

try {
expect(await task).toThrowError(InvalidJsonFileError);
} catch (e) {
const err = e as InvalidJsonFileError;
expect(err.fileName).toEqual('invalid_by_format.json');
}
});

test("should throw an error when file or directory don't exist", async () => {
const notExistingFile = 'no_such_file.json';

const task = getJson(mocks_dir, notExistingFile);
try {
expect(await task).toThrowError(InvalidJsonFileError);
} catch (e) {
const err = e as InvalidJsonFileError;
expect(err.fileName).toEqual('no_such_file.json');
expect(typeof err.innerError).not.toBeUndefined();
expect((<object>err.innerError)['code']).toBe('ENOENT');
}
});
});
54 changes: 54 additions & 0 deletions __tests__/json-validator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { validateJsons } from '../src/json-validator';

const validSchemaFile = `schema/valid.json`;
const invalidSchemaFile = `schema/invalid.json`;

const validDataFile = `tested-data/valid.json`;
const invalidDataFile = `tested-data/invalid_by_schema.json`;

const mocks_dir = './__tests__/mocks';

describe('Json validation results', () => {
test('all successful when all jsons in the list are valid', async () => {
const results = await validateJsons(mocks_dir, validSchemaFile, [validDataFile, validDataFile]);
expect(results.every(r => r.valid)).toBeTruthy();
expect(results.every(r => r.fileName === 'valid.json')).toBeTruthy();
});

test('only one failure when one json in the list is invalid', async () => {
const results = await validateJsons(mocks_dir, validSchemaFile, [validDataFile, invalidDataFile]);

const successes = results.filter(r => r.valid);
expect(successes.length).toEqual(1);
expect(successes.every(r => r.fileName === 'valid.json')).toBeTruthy();

const failures = results.filter(r => !r.valid);
expect(failures.length).toEqual(1);
expect(failures.every(r => r.fileName === 'invalid_by_schema.json')).toBeTruthy();
});

test('all failures when all jsons in the list are invalid', async () => {
const results = await validateJsons(mocks_dir, validSchemaFile, [invalidDataFile, invalidDataFile]);
expect(results.every(r => !r.valid)).toBeTruthy();
expect(results.every(r => r.fileName === 'invalid_by_schema.json')).toBeTruthy();
});

test('one failures when schema file are invalid', async () => {
const results = await validateJsons(mocks_dir, invalidSchemaFile, [validDataFile, validDataFile]);
expect(results).toHaveLength(1);
expect(results.every(r => !r.valid)).toBeTruthy();
expect(results.every(r => r.fileName === 'invalid.json')).toBeTruthy();
});

test('one failure when no schema file', async () => {
const results = await validateJsons(mocks_dir, '', [validDataFile, validDataFile]);
expect(results).toHaveLength(1);
expect(results.every(r => !r.valid)).toBeTruthy();
expect(results.every(r => r.fileName === 'schema')).toBeTruthy();
});

test('empty when when no jsons in the list', async () => {
const results = await validateJsons(mocks_dir, validSchemaFile, []);
expect(results).toHaveLength(0);
});
});
43 changes: 43 additions & 0 deletions __tests__/main.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import * as os from 'os';
import * as process from 'process';
import * as path from 'path';
import * as cp from 'child_process';
import { MockedConfig } from './mocks/mocked-config';

let mockedConfig: MockedConfig;
let ip: string;

describe('Run tests', () => {
beforeEach(() => {
ip = path.join(__dirname, '..', 'lib', 'main.js');
mockedConfig = new MockedConfig();
});

afterEach(() => {
ip = '';
mockedConfig.resetAll();
jest.resetAllMocks();
});

test('All inputs are set and valid', () => {
// Arrange
mockedConfig.mockValue('SCHEMA', './mocks/schema/valid.json');
mockedConfig.mockValue('JSONS', './mocks/tested-data/valid.json');

mockedConfig.set();

const options: cp.ExecOptions = {
env: process.env,
};

try {
// Act
const result = cp.execSync(`node ${ip}`, options);

// Assert
expect(result.toString()).toContain(`::set-output name=INVALID,::${os.EOL}`);
} catch (ex) {
expect(ex).toBeUndefined();
}
});
});
33 changes: 33 additions & 0 deletions __tests__/mocks/mocked-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as path from 'path';
import { ConfigKeys, ConfigKey, configMapping } from '../../src/configuration';

export class MockedConfig {
private mockedConfig: {};

constructor() {
this.mockedConfig = {
GITHUB_WORKSPACE: path.join(__dirname, '..'),
INPUT_SCHEMA: '',
INPUT_JSONS: '',
};
}

public mockValue(key: ConfigKeys, value: string) {
const keyMapping = configMapping.find(x => ConfigKey[x.key] === key);
if (keyMapping) {
this.mockedConfig[keyMapping.setup === 'INPUT' ? `${keyMapping.setup}_${key}` : key] = value;
}
}

public set(): void {
for (const key in this.mockedConfig) {
process.env[key] = this.mockedConfig[key];
}
}

public resetAll(): void {
for (const key in this.mockedConfig) {
Reflect.deleteProperty(this.mockedConfig, key);
}
}
}
6 changes: 6 additions & 0 deletions __tests__/mocks/schema/invalid.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"properties": {
"foo": { "type": "no_such_type" },
"bar": { "type": "number" }
}
}
6 changes: 6 additions & 0 deletions __tests__/mocks/schema/valid.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"properties": {
"foo": { "type": "string" },
"bar": { "type": "number" }
}
}
Empty file.
1 change: 1 addition & 0 deletions __tests__/mocks/tested-data/invalid_by_schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "foo": 2, "bar": 4 }
1 change: 1 addition & 0 deletions __tests__/mocks/tested-data/valid.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "foo": "abc", "bar": 2 }
Loading

0 comments on commit 254b4d5

Please sign in to comment.