Skip to content

Commit

Permalink
test(pkg): add missing tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed May 11, 2024
1 parent a4e3896 commit 9571c72
Show file tree
Hide file tree
Showing 11 changed files with 564 additions and 10 deletions.
2 changes: 2 additions & 0 deletions bin/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
*/

import { Runner } from '@athenna/test'
import { command } from '@athenna/artisan/testing/plugins'

await Runner.setTsEnv()
.addAssertPlugin()
.addPlugin(command())
.addPath('tests/unit/**/*.ts')
.setCliArgs(process.argv.slice(2))
.setGlobalTimeout(5000)
Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,10 @@
],
"namedValidators": {
"hello": "#tests/fixtures/validators/HelloValidator"
},
"templates": {
"validator-http": "./templates/validator-http.edge",
"validator-console": "./templates/validator-console.edge"
}
}
}
2 changes: 1 addition & 1 deletion src/validator/BaseValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export abstract class BaseValidator {
public abstract schema: SchemaTypes
public abstract handle(data: any): Promise<void>

public validate(data: any) {
public async validate(data: any) {
return this.validator.validate({ schema: this.schema, data })
}
}
10 changes: 5 additions & 5 deletions src/validator/ValidatorImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ export class ValidatorImpl {
* build your validation schemas:
*
* ```ts
* const schema = Validator.schema.object({
* name: Validator.schema.string(),
* email: Validator.schema.string().email(),
* password: Validator.schema.string().minLength(8).maxLength(32).confirmed()
* const schema = Validate.schema.object({
* name: Validate.schema.string(),
* email: Validate.schema.string().email(),
* password: Validate.schema.string().minLength(8).maxLength(32).confirmed()
* })
* ```
*/
Expand All @@ -47,7 +47,7 @@ export class ValidatorImpl {
* validation rules:
*
* ```ts
* Validator.extend().string('unique', (value, options, field) => {
* Validate.extend().string('unique', (value, options, field) => {
* if (!options.column) {
* options.column = field.name as string
* }
Expand Down
35 changes: 35 additions & 0 deletions tests/fixtures/consoles/base-console.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* @athenna/validator
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

import { sep } from 'node:path'
import { Path } from '@athenna/common'
import { Config, Rc } from '@athenna/config'
import { ViewProvider } from '@athenna/view'
import { LoggerProvider } from '@athenna/logger'
import { Artisan, ArtisanProvider, ConsoleKernel } from '@athenna/artisan'

process.env.IS_TS = 'true'

await Config.loadAll(Path.fixtures('config'))

Config.set('rc.parentURL', Path.toHref(Path.pwd() + sep))

Config.set('rc.commands', {
'make:validator': '#src/commands/MakeValidatorCommand'
})

await Rc.setFile(Path.pwd('package.json'))

new ViewProvider().register()
new ArtisanProvider().register()
new LoggerProvider().register()

await new ConsoleKernel().registerCommands(process.argv)

await Artisan.parse(process.argv, 'Artisan')
38 changes: 38 additions & 0 deletions tests/fixtures/consoles/console-mock-dest-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* @athenna/validator
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

import { sep } from 'node:path'
import { Path } from '@athenna/common'
import { Config, Rc } from '@athenna/config'
import { ViewProvider } from '@athenna/view'
import { LoggerProvider } from '@athenna/logger'
import { Artisan, ArtisanProvider, ConsoleKernel } from '@athenna/artisan'

process.env.IS_TS = 'true'

await Config.loadAll(Path.fixtures('config'))

Config.set('rc.parentURL', Path.toHref(Path.pwd() + sep))

Config.set('rc.commands', {
'make:validator': {
path: '#src/commands/MakeValidatorCommand',
destination: './tests/fixtures/storage/validators'
}
})

await Rc.setFile(Path.pwd('package.json'))

new ViewProvider().register()
new ArtisanProvider().register()
new LoggerProvider().register()

await new ConsoleKernel().registerCommands(process.argv)

await Artisan.parse(process.argv, 'Artisan')
32 changes: 32 additions & 0 deletions tests/helpers/BaseCommandTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* @athenna/validator
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

import { ArtisanProvider } from '@athenna/artisan'
import { Path, File, Folder } from '@athenna/common'
import { AfterEach, BeforeEach } from '@athenna/test'
import { TestCommand } from '@athenna/artisan/testing/plugins'

export class BaseCommandTest {
public originalPackageJson = new File(Path.pwd('package.json')).getContentAsStringSync()

@BeforeEach()
public async beforeEach() {
new ArtisanProvider().register()

TestCommand.setArtisanPath(Path.fixtures('consoles/base-console.ts'))
}

@AfterEach()
public async afterEach() {
await Folder.safeRemove(Path.app())
await Folder.safeRemove(Path.fixtures('storage'))

await new File(Path.pwd('package.json')).setContent(this.originalPackageJson)
}
}
14 changes: 13 additions & 1 deletion tests/unit/annotations/ValidatorAnnotationTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,23 @@ export default class ValidatorAnnotationTest extends BaseTest {

@Test()
@Cleanup(() => ioc.reconstruct())
public async shouldNotReRegisterTheValidatorIfItIsAlreadyRegisteredInTheServiceContainer({ assert }: Context) {
public async shouldNotReRegisterTheValidatorAliasIfItIsAlreadyRegisteredInTheServiceContainer({ assert }: Context) {
ioc.singleton('App/Validators/ProductValidator', () => {})

const ProductValidator = await this.import('#tests/fixtures/validators/ProductValidator')

assert.isFalse(Annotation.isAnnotated(ProductValidator))
}

@Test()
@Cleanup(() => ioc.reconstruct())
public async shouldNotReRegisterTheValidatorNamedAliasIfItIsAlreadyRegisteredInTheServiceContainer({
assert
}: Context) {
ioc.singleton('App/Validators/Names/productValidator', () => {})

const ProductValidator = await this.import('#tests/fixtures/validators/ProductValidator')

assert.isFalse(Annotation.isAnnotated(ProductValidator))
}
}
52 changes: 51 additions & 1 deletion tests/unit/commands/MakeValidatorCommandTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,54 @@
* file that was distributed with this source code.
*/

export class MakeValidatorCommandTest {}
import { Path, File } from '@athenna/common'
import { Test, type Context } from '@athenna/test'
import { BaseCommandTest } from '#tests/helpers/BaseCommandTest'

export default class MakeValidatorCommandTest extends BaseCommandTest {
@Test()
public async shouldBeAbleToCreateAValidatorFile({ assert, command }: Context) {
const output = await command.run('make:validator TestValidator')

output.assertSucceeded()
output.assertLogged('[ MAKING VALIDATOR ]')
output.assertLogged('[ success ] Validator "TestValidator" successfully created.')
output.assertLogged('[ success ] Athenna RC updated: [ validators += "#app/validators/TestValidator" ]')

const { athenna } = await new File(Path.pwd('package.json')).getContentAsJson()

assert.isTrue(await File.exists(Path.validators('TestValidator.ts')))
assert.containsSubset(athenna.validators, ['#app/validators/TestValidator'])
}

@Test()
public async shouldBeAbleToCreateAValidatorFileWithADifferentDestPathAndImportPath({ assert, command }: Context) {
const output = await command.run('make:validator TestValidator', {
path: Path.fixtures('consoles/console-mock-dest-import.ts')
})

output.assertSucceeded()
output.assertLogged('[ MAKING VALIDATOR ]')
output.assertLogged('[ success ] Validator "TestValidator" successfully created.')
output.assertLogged(
'[ success ] Athenna RC updated: [ validators += "#tests/fixtures/storage/validators/TestValidator" ]'
)

const { athenna } = await new File(Path.pwd('package.json')).getContentAsJson()

assert.isTrue(await File.exists(Path.fixtures('storage/validators/TestValidator.ts')))
assert.containsSubset(athenna.validators, ['#tests/fixtures/storage/validators/TestValidator'])
}

@Test()
public async shouldThrowAnExceptionWhenTheFileAlreadyExists({ command }: Context) {
await command.run('make:validator TestValidator')
const output = await command.run('make:validator TestValidator')

output.assertFailed()
output.assertLogged('[ MAKING VALIDATOR ]')
output.assertLogged('The file')
output.assertLogged('TestValidator.ts')
output.assertLogged('already exists')
}
}
90 changes: 89 additions & 1 deletion tests/unit/validator/BaseValidatorTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,92 @@
* file that was distributed with this source code.
*/

export class BaseValidatorTest {}
import { AfterEach, BeforeEach, Test, type Context } from '@athenna/test'
import { BaseValidator, ValidationException, ValidatorProvider } from '#src'

export class BaseValidatorTest {
@BeforeEach()
public async beforeEach() {
await new ValidatorProvider().register()
}

@AfterEach()
public async afterEach() {
ioc.reconstruct()
}

@Test()
public async shouldBeAbleToDefineTheValidationSchema({ assert }: Context) {
class UserValidator extends BaseValidator {
public schema = this.validator.object({
name: this.validator.string()
})

public async handle() {}
}

const properties = new UserValidator().schema.getProperties()

assert.isDefined(properties.name)
}

@Test()
public async shouldBeAbleToDefineTheValidationHandlerMethod({ assert }: Context) {
class UserValidator extends BaseValidator {
public schema = this.validator.object({
name: this.validator.string()
})

public async handle(data: any) {
await this.validator.validate({ schema: this.schema, data })
}
}

assert.doesNotReject(() => new UserValidator().handle({ name: 'lenon' }))
}

@Test()
public async shouldThrowValidationExceptionWhenValidationFails({ assert }: Context) {
class UserValidator extends BaseValidator {
public schema = this.validator.object({
name: this.validator.string()
})

public async handle(data: any) {
await this.validator.validate({ schema: this.schema, data })
}
}

assert.rejects(() => new UserValidator().handle({ name: 10 }), ValidationException)
}

@Test()
public async shouldBeAbleToUseValidateMethodToValidateData({ assert }: Context) {
class UserValidator extends BaseValidator {
public schema = this.validator.object({
name: this.validator.string()
})

public async handle(data: any) {
await this.validate(data)
}
}

assert.doesNotReject(() => new UserValidator().handle({ name: 'lenon' }))
}

@Test()
public async shouldThrowValidationExceptionWhenValidationFailsWhenUsingValidateMethod({ assert }: Context) {
class UserValidator extends BaseValidator {
public schema = this.validator.object({
name: this.validator.string()
})

public async handle(data: any) {
await this.validate(data)
}
}

assert.rejects(() => new UserValidator().handle({ name: 10 }), ValidationException)
}
}
Loading

0 comments on commit 9571c72

Please sign in to comment.