Skip to content

Commit

Permalink
Merge pull request #77 from Renato66/feat/tests
Browse files Browse the repository at this point in the history
test: fix test for mock
  • Loading branch information
Renato66 authored May 3, 2024
2 parents 1f61425 + 1c89d24 commit 30beb16
Show file tree
Hide file tree
Showing 23 changed files with 357 additions and 204 deletions.
1 change: 1 addition & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ jobs:
${{ runner.os }}-bun-${{ github.ref }}
- run: bun install
- run: bun tslint
- run: bun lint
- run: bun test
5 changes: 2 additions & 3 deletions .github/workflows/codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ on:
- main

jobs:

build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v1
Expand All @@ -21,7 +20,7 @@ jobs:
${{ runner.os }}-bun-${{ github.ref }}
- run: bun install
- run: bun test --coverage
#
#
# - name: Upload coverage to Codecov
# uses: codecov/codecov-action@v3
# with:
Expand Down
3 changes: 1 addition & 2 deletions .prettierrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": false,
"arrowParens": "avoid"
"arrowParens": "always"
}
2 changes: 1 addition & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
"streetsidesoftware.code-spell-checker",
"esbenp.prettier-vscode"
]
}
}
3 changes: 1 addition & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ This project was created using `bun init` in bun v1.1.0. [Bun](https://bun.sh) i
> [!NOTE]
> You will need to have [docker](https://www.docker.com/products/docker-desktop/) installed

To create a docker image:

```
docker build --pull -t auto-label .
docker build --pull -t auto-label .
```
4 changes: 2 additions & 2 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ author: 'Renato66'
branding:
icon: 'check-square'
color: 'blue'
inputs:
inputs:
repo-token:
description: 'github token for the repository'
required: true
Expand All @@ -22,4 +22,4 @@ inputs:
default: ''
runs:
using: 'docker'
image: 'Dockerfile'
image: 'Dockerfile'
Binary file modified bun.lockb
Binary file not shown.
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@
"scripts": {
"test": "bun test",
"coverage": "bun test --coverage",
"tslint": "bun run node_modules/typescript/lib/tsc.js --noEmit"
"tslint": "bun run node_modules/typescript/lib/tsc.js --noEmit",
"lint": "bun prettier . --check",
"lint:fix": "bun prettier . --write"
},
"devDependencies": {
"@types/bun": "latest",
"nock": "^13.5.4",
"prettier": "3.2.5",
"typescript": "^5.4.4"
},
"peerDependencies": {
Expand All @@ -20,4 +23,4 @@
"@actions/core": "1.10.1",
"@actions/github": "6.0.0"
}
}
}
38 changes: 38 additions & 0 deletions src/domain/getConfigFile.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { expect, describe, test, mock, afterEach, jest } from 'bun:test'
import * as core from '@actions/core'
import { getConfigFile } from './getConfigFile'

describe('getConfigFile', () => {
afterEach(() => {
mock.module('@actions/core', () => core)
})
test('returns empty array when labels-not-allowed input is empty', () => {
mock.module('@actions/core', () => ({
getInput: jest.fn(() => undefined),
getBooleanInput: jest.fn(() => undefined)
}))
const result1 = getConfigFile()
expect(result1.labelsNotAllowed).toEqual([])
mock.module('@actions/core', () => ({
getInput: jest.fn(() => '')
}))
const result2 = getConfigFile()
expect(result2.labelsNotAllowed).toEqual([])
})

test('returns parsed array from labels-not-allowed input', () => {
const labels = ['label1', 'label2']
mock.module('@actions/core', () => ({
getInput: jest.fn(() => JSON.stringify(labels))
}))
const result = getConfigFile()
expect(result.labelsNotAllowed).toEqual(labels)
})

test('throws error if labels-not-allowed input is not valid JSON', () => {
mock.module('@actions/core', () => ({
getInput: jest.fn(() => 'not-valid-json')
}))
expect(getConfigFile).toThrowError()
})
})
18 changes: 18 additions & 0 deletions src/domain/getConfigFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { getInput } from './getInput'

export const getConfigFile = () => {
const labelsNotAllowed = getInput<string[]>('labels-not-allowed', [])
const defaultLabels = getInput<string[]>('default-labels', [])
const labelsSynonyms = getInput<Record<string, string[]>>(
'labels-synonyms',
{}
)
const ignoreComments = getInput('ignore-comments', true)

return {
labelsNotAllowed,
defaultLabels,
labelsSynonyms,
ignoreComments
}
}
37 changes: 37 additions & 0 deletions src/domain/getInput.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { expect, describe, test, mock, afterEach, jest } from 'bun:test'
import * as core from '@actions/core'
import { getInput } from './getInput'

describe('getInput', () => {
afterEach(() => {
mock.module('@actions/core', () => core)
})
test('returns default value when input is empty/undefined', () => {
mock.module('@actions/core', () => ({
getInput: jest.fn(() => undefined)
}))
const result1 = getInput<string[]>('input', [])
expect(result1).toEqual([])
mock.module('@actions/core', () => ({
getInput: jest.fn(() => '')
}))
const result2 = getInput<string[]>('input', [])
expect(result2).toEqual([])
})

test('returns parsed array from input', () => {
const labels = ['label1', 'label2']
mock.module('@actions/core', () => ({
getInput: jest.fn(() => JSON.stringify(labels))
}))
const result = getInput<string[]>('input', [])
expect(result).toEqual(labels)
})

test('throws error if input is not valid JSON', () => {
mock.module('@actions/core', () => ({
getInput: jest.fn(() => 'not-valid-json')
}))
expect(() => getInput<string[]>('input', [])).toThrowError()
})
})
27 changes: 27 additions & 0 deletions src/domain/getInput.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as core from '@actions/core'

const getObjectInput = <T>(field: string, fallback: T): T => {
const inputString = core.getInput(field)
if (!inputString) return fallback
try {
return JSON.parse(inputString) as T
} catch (error: any) {
throw new Error(`"${field}": ${error.message}`)
}
}
const getBooleanInput = (field: string, fallback: boolean): boolean => {
if ([undefined, ''].includes(core.getInput(field, { trimWhitespace: true })))
return fallback
return core.getBooleanInput(field)
}

export const getInput = <T>(field: string, fallback: T): T => {
switch (typeof fallback) {
case 'object':
return getObjectInput(field, fallback)
case 'boolean':
return getBooleanInput(field, fallback) as T
default:
return core.getInput(field) as T
}
}
15 changes: 0 additions & 15 deletions src/domain/labelsNotAllowed.ts

This file was deleted.

22 changes: 22 additions & 0 deletions src/domain/removeLabelsNotAllowed.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { expect, describe, test } from 'bun:test'
import { removeLabelsNotAllowed } from './removeLabelsNotAllowed'

describe('removeLabelsNotAllowed function', () => {
test('should return the same labels if labels-not-allowed is not set', () => {
const labels = ['Label1', 'Label2', 'Label3']
const result = removeLabelsNotAllowed(labels, [])
expect(result).toEqual(labels)
})

test('should remove labels that are not allowed', () => {
const labels = ['Label1', 'Label2', 'Label3']
const result = removeLabelsNotAllowed(labels, ['Label2'])
expect(result).toEqual(['Label1', 'Label3'])
})

test('should handle case-insensitive labels', () => {
const labels = ['label1', 'Label2', 'label3']
const result = removeLabelsNotAllowed(labels, ['LABEL1'])
expect(result).toEqual(['Label2', 'label3'])
})
})
13 changes: 13 additions & 0 deletions src/domain/removeLabelsNotAllowed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const removeLabelsNotAllowed = (
labels: string[],
labelsNotAllowed: string[]
): string[] => {
if (!labelsNotAllowed || !labelsNotAllowed.length) {
return labels
}
const labelsLC = labels.map((elem) => elem.toLocaleLowerCase())
const labelsNotAllowedLC = new Set(
labelsNotAllowed.map((elem) => elem.toLocaleLowerCase())
)
return labels.filter((_, index) => !labelsNotAllowedLC.has(labelsLC[index]))
}
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
import { run } from './runner';
run()
import { run } from './runner'
run()
76 changes: 35 additions & 41 deletions src/runner.spec.ts
Original file line number Diff line number Diff line change
@@ -1,58 +1,52 @@
import { expect, describe, test, mock, jest } from 'bun:test';
import * as core from '@actions/core';
import '@actions/github';
import { run } from './runner';
import { expect, describe, test, mock, jest } from 'bun:test'
import * as core from '@actions/core'
import '@actions/github'
import { run } from './runner'

// Mock core functions
// // Mock core functions
mock.module('@actions/core', () => ({
getInput: jest.fn(() => 'mocked-token'),
getInput: jest.fn((input) => {
return input === 'repo-token' ? 'mockedToken' : undefined
}),
info: jest.fn(),
startGroup: jest.fn(),
endGroup: jest.fn(),
setFailed: jest.fn(),
}));
setFailed: jest.fn()
}))

// Mock github context
const mockIssue = { number: 123, body: 'Mocked issue body' };
const mockIssue = { number: 123, body: 'Mocked issue body label1' }
const mockContext = {
payload: {
issue: mockIssue,
},
};
issue: mockIssue
}
}
mock.module('@actions/github', () => ({
getOctokit: jest.fn(),
context: mockContext,
}));
context: mockContext
}))

// Mock service functions
// // Mock service functions
const addLabelsSpy = jest.fn()
mock.module('./service/github', () => ({
getRepoLabels: jest.fn(() => []),
addLabels: addLabelsSpy,
}));
mock.module('./domain/labelsNotAllowed', () => ({
removeLabelsNotAllowed: jest.fn((labels: string[]) => labels),
}));
mock.module('./scraper/text', () => ({
getIssueLabels: jest.fn(() => []),
}));
getRepoLabels: jest.fn(() => ['label1']),
addLabels: addLabelsSpy
}))

describe('run function', () => {
test('should run successfully without throwing errors', async () => {
await run();
expect(core.setFailed).not.toHaveBeenCalled();
});
test('should add if any found label', async () => {
const issueLabels = ['label', 'label2']
mock.module('./scraper/text', () => ({
getIssueLabels: jest.fn(() => issueLabels),
}));
await run();
// TODO: fix this test
// expect(addLabelsSpy).toHaveBeenCalledWith(
// expect.any(Object), // octokit
// 123, // issue number
// issueLabels // issue labels
// );
});
});
await run()
expect(core.setFailed).not.toHaveBeenCalled()
expect(addLabelsSpy).toHaveBeenCalled()
})
test('should add if any found label', async () => {
mock.module('@actions/core', () => ({
getInput: jest.fn(() => undefined),
info: jest.fn(),
startGroup: jest.fn(),
endGroup: jest.fn(),
setFailed: jest.fn()
}))
expect(async () => await run()).toThrowError()
})
})
Loading

0 comments on commit 30beb16

Please sign in to comment.