Commit 1e78c500 authored by Alex Quispe's avatar Alex Quispe
Browse files

Se adicionó el scaffold para los tests

parent d516651d
/public
/node_modules
/temp
/package-lock.json
......@@ -4,10 +4,11 @@ Genera la documentación de un servicio web RESTFull con soporte para ApidocJS y
La documentación se genera a partir de las respuestas que devuelve el servicio.
## Requisitos:
## Caracteristicas:
- Es posible documentar las rutas a partir de una instancia de `express`, sin necesidad de levantar el servicio.
- Si el servicio está activo en modo `development` o `test`, es posible ejecutar funciones adicionales realizando peticiones sobre el servicio, permitiendo de esa forma documentar las respuestas automaticamente.
- Es posible generar un escaffold para los tests.
### Archivo `src/auth.js`
......@@ -112,7 +113,7 @@ await ApiGen.get('/api/v1/users').generate('Auth')
const body = await ApiGen.get('/api/v1/users').generate()
```
## Configuración del proyecto para generar la documentación
## Configuración del proyecto para generar la documentación y los tests
### Estructura
......@@ -122,13 +123,15 @@ app
├─ documentation
| ├─ build
| ├─ src
| │ ├─ api.js
| │ └─ auth.js
| │ └─ api-v1-users.js
| ├─ scaffold.js
| ├─ scaffold-test.js
| ├─ generate.js
| └─ server.js
├─ src
│ └─ app.js
├─ test
│ └─ api-v1-users.test.js
├─ index.js
└─ package.json
```
......@@ -149,11 +152,29 @@ const path = require('path')
ApiGen.SRC_PATH = path.resolve(__dirname, 'src')
ApiGen.HELP_TYPE = 'YAML' // YAML o JSON
const app = require('../src/app')
const app = require('../')
ApiGen.scaffold(app)
```
### Archivo `documentation/scaffold-test.js`
Este fichero se encarga de crear los ficheros necesarios para testear los servicios.
Se requieren los paquetes: `ava` y `supertest` para ejecutar los tests.
- `test/api-v1-users.test.js`
```js
const ApiGen = require('./../../')
const path = require('path')
ApiGen.TEST_PATH = path.resolve(__dirname, '../test')
const app = require('../')
ApiGen.scaffoldTest(app)
```
### Archivo `documentation/generate.js`
Este fichero se encarga de generar la documentación con soporte para ApidocJS y Swagger.
......@@ -197,10 +218,16 @@ ApiGen.server()
"main": "index.js",
"scripts": {
"start": "node index",
"test": "NODE_ENV=test ava test/* --serial --verbose",
"doc:scaffold": "node documentation/scaffold",
"doc:scaffold:test": "node documentation/scaffold-test",
"doc:generate": "node documentation/generate",
"doc:server": "node documentation/server",
"doc:start": "npm run doc:scaffold && npm run doc:generate && npm run doc:server"
},
"dependencies": {
"ava": "^0.25.0",
"supertest": "^3.3.0"
}
}
```
......@@ -57,8 +57,23 @@ class ApidocGenerator {
process.exit(0)
}
static scaffoldTest (app) {
console.log(' Apidoc Scaffolding ...\n')
_crearCarpeta(ApidocGenerator.TEST_PATH)
const ROUTES = _getRoutes(app)
// console.log("ROUTES = ", ROUTES);
const archivosVerificados = []
Object.keys(ROUTES).forEach(groupName => {
ROUTES[groupName].forEach(route => {
_crearContenidoTest(route.groupKey, route)
})
})
console.log('\n \x1b[32minfo:\x1b[0m Scaffold ok :) \n')
process.exit(0)
}
static async create (filesName) {
console.log(' Construyendo apidoc ...')
console.log(' Construyendo apidoc ...\n')
const archivosConError = []
_crearCarpeta(ApidocGenerator.BUILD_PATH)
......@@ -261,6 +276,7 @@ class ApidocGenerator {
}
ApidocGenerator.SRC_PATH = path.resolve(process.cwd(), `src`)
ApidocGenerator.TEST_PATH = path.resolve(process.cwd(), `test`)
ApidocGenerator.BUILD_PATH = path.resolve(process.cwd(), `build`)
ApidocGenerator.API_URL = 'http://localhost:4000'
ApidocGenerator.REDIRECT_PATH = '/apidoc'
......@@ -337,7 +353,7 @@ function _getRoutes (app) {
}
async function _build () {
console.log('\n Uniendo ficheros ...\n')
// console.log('\n Uniendo ficheros ...\n')
// APIDOC JS
const filePath1 = path.resolve(ApidocGenerator.BUILD_PATH, `apidoc.js`)
......@@ -354,7 +370,7 @@ async function _build () {
content += newBlock
})
util.writeFile(filePath1, content)
console.log('', filePath1.replace(process.cwd(), ''), '\u2713')
// console.log('', filePath1.replace(process.cwd(), ''), '\u2713')
// SWAGGER
const filePath2 = path.resolve(ApidocGenerator.BUILD_PATH, `swagger.json`)
......@@ -382,7 +398,7 @@ async function _build () {
})
})
util.writeFile(filePath2, JSON.stringify(content2, null, 2))
console.log('', filePath2.replace(process.cwd(), ''), '\u2713\n')
// console.log('', filePath2.replace(process.cwd(), ''), '\u2713\n')
await _buildApidocJS()
const SWAGGER_JSON_OUTPUT_PATH = path.resolve(ApidocGenerator.BUILD_PATH, `public/swagger.json`)
util.copyFile(path.resolve(ApidocGenerator.BUILD_PATH, `swagger.json`), SWAGGER_JSON_OUTPUT_PATH)
......@@ -527,10 +543,35 @@ function _crearContenido (groupKey, route) {
content.push({ method: route.method, path: route.path })
}
util.removeFile(filePath)
util.writeFile(filePath, YAML.stringify(content, 4) + '\n')
util.writeFile(filePath, YAML.stringify(content, 4))
}
}
function _crearContenidoTest (groupKey, route) {
// Archivo .test.js
let content = util.readFile(path.resolve(__dirname, '../template/test.js'))
let filePath = path.resolve(ApidocGenerator.TEST_PATH,`${groupKey}.test.js`)
if (!util.isFile(filePath)) {
util.writeFile(filePath, content)
console.log(`\n ${filePath.replace(process.cwd(), '')} \u2713`)
}
const ROUTE_FLAG = '// <!-- [TEST DEFINITION] --!> //'
content = util.readFile(filePath)
if (!content.includes(`test.serial.cb('[${route.group}] [${route.method}] ${route.path}', t => {`)) {
const TEST_BLOCK_PATH = path.resolve(__dirname, '../template/test-block.js')
let testBlock = util.readFile(TEST_BLOCK_PATH)
testBlock = _.replace(testBlock, /GROUP/g, route.group)
testBlock = _.replace(testBlock, /METHOD/g, route.method)
testBlock = _.replace(testBlock, /PATH/g, route.path)
content = content.replace(ROUTE_FLAG, testBlock)
console.log(` [${groupKey}] - [${route.method}] ${route.path} \u2713`)
}
content = content.trim() + '\n'
util.removeFile(filePath)
util.writeFile(filePath, content)
}
function _verificarRutasDelArchivo (filePath, ROUTES) {
const existInRoutes = (method, path) => {
for (let i in ROUTES) {
......
/documentation/build
/temp
/node_modules
/package-lock.json
const test = require('ava')
const request = require('supertest')
const app = require('../')
test.serial.cb('[Api V1 Users] [get] /api/v1/users/', t => {
request(app).get('/api/v1/users/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
test.serial.cb('[Api V1 Users] [get] /api/v1/users/:id', t => {
request(app).get('/api/v1/users/:id')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
test.serial.cb('[Api V1 Users] [post] /api/v1/users/', t => {
request(app).post('/api/v1/users/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
const ApiGen = require('./../../')
const path = require('path')
ApiGen.TEST_PATH = path.resolve(__dirname, '../test')
const app = require('../src/app')
ApiGen.scaffoldTest(app)
const ApiGen = require('../../../')
const ApiGen = require('apidoc-generator')
module.exports = async () => {
await ApiGen.get('/api/custom/other/route').generate()
......
-
method: get
path: /api/custom/other/route
const ApiGen = require('../../../')
const ApiGen = require('apidoc-generator')
module.exports = async () => {
await ApiGen.get('/api/v1/users/').generate()
......
......@@ -10,4 +10,3 @@
-
method: post
path: /api/v1/users/bulk
const ApiGen = require('../../../')
const ApiGen = require('apidoc-generator')
module.exports = async () => {
await ApiGen.get('/ruta/sin/grupo').generate()
......
......@@ -5,11 +5,17 @@
"main": "index.js",
"scripts": {
"start": "node index",
"test": "NODE_ENV=test ava test/* --serial --verbose",
"doc:scaffold": "node documentation/scaffold",
"doc:scaffold:test": "node documentation/scaffold-test",
"doc:generate": "node documentation/generate",
"doc:server": "node documentation/server",
"doc:start": "npm run doc:scaffold && npm run doc:generate && npm run doc:server"
},
"author": "",
"license": "ISC"
"license": "ISC",
"dependencies": {
"ava": "^0.25.0",
"supertest": "^3.3.0"
}
}
......@@ -15,7 +15,9 @@ app.use(cors({
app.use(express.static('public'))
app.use((req, res, next) => {
console.log(` [${req.method}] ${req.url}`);
if (process.env.NODE_ENV === 'development') {
console.log(` [${req.method}] ${req.url}`)
}
next()
})
......
const test = require('ava')
const request = require('supertest')
const app = require('../')
test.serial.cb('[Api Custom] [get] /api/custom/other/route', t => {
request(app).get('/api/custom/other/route')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
// <!-- [TEST DEFINITION] --!> //
const test = require('ava')
const request = require('supertest')
const app = require('../')
test.serial.cb('[Api V1 Users] [get] /api/v1/users/', t => {
request(app).get('/api/v1/users/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
test.serial.cb('[Api V1 Users] [get] /api/v1/users/:id', t => {
request(app).get('/api/v1/users/:id')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
test.serial.cb('[Api V1 Users] [post] /api/v1/users/', t => {
request(app).post('/api/v1/users/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
test.serial.cb('[Api V1 Users] [post] /api/v1/users/bulk', t => {
request(app).post('/api/v1/users/bulk')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
// <!-- [TEST DEFINITION] --!> //
const test = require('ava')
const request = require('supertest')
const app = require('../')
test.serial.cb('[Default] [get] /ruta/sin/grupo', t => {
request(app).get('/ruta/sin/grupo')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
// <!-- [TEST DEFINITION] --!> //
This diff is collapsed.
test.serial.cb('[GROUP] [METHOD] PATH', t => {
request(app).METHOD('PATH')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.end((err, res) => {
t.pass()
t.end()
})
})
// <!-- [TEST DEFINITION] --!> //
const test = require('ava')
const request = require('supertest')
const app = require('../')
// <!-- [TEST DEFINITION] --!> //
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment