Skip to content

Commit

Permalink
testes no back-end dos monitor-apps
Browse files Browse the repository at this point in the history
  • Loading branch information
luizchaves committed Mar 5, 2024
1 parent 50c5ec6 commit 152124f
Show file tree
Hide file tree
Showing 41 changed files with 30,884 additions and 5,209 deletions.
8,013 changes: 7,113 additions & 900 deletions public/codes/expressjs/monitor-app-api/back/package-lock.json

Large diffs are not rendered by default.

16 changes: 15 additions & 1 deletion public/codes/expressjs/monitor-app-api/back/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,27 @@
"type": "module",
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js"
"dev": "node --watch src/index.js",
"test": "node --experimental-vm-modules ./node_modules/.bin/jest src",
"test:coverage": "node --experimental-vm-modules ./node_modules/.bin/jest src --coverage"
},
"jest": {
"collectCoverage": true,
"testTimeout": 20000,
"coverageReporters": [
"json",
"html"
]
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"express-async-errors": "^3.1.1",
"morgan": "^1.10.0",
"uuid": "^9.0.0"
},
"devDependencies": {
"jest": "^29.7.0",
"supertest": "^6.3.4"
}
}
13 changes: 7 additions & 6 deletions public/codes/expressjs/monitor-app-api/back/requests.http
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ Content-Type: application/json
"address": "1.1.1.1"
}

### Create a host (bad params)
# @name createHost
### Create a host without name or address
POST {{server}}/hosts
Content-Type: application/json

Expand All @@ -25,11 +24,13 @@ GET {{server}}/hosts

### Read a host by name
GET {{server}}/hosts?name=Google%20DNS
# GET {{server}}/hosts?name=DNS
# GET {{server}}/hosts?name=dns

### Read a host by id
GET {{server}}/hosts/{{createdHostId}}

### Read a host by id (bad params)
### Read a host by id with invalid id
GET {{server}}/hosts/x

### Update a host
Expand All @@ -41,15 +42,15 @@ Content-Type: application/json
"address": "1.1.1.1"
}

### Update a host (bad params)
### Update a host without name or address
PUT {{server}}/hosts/{{createdHostId}}
Content-Type: application/json

{
"name": "Cloudflare DNS"
}

### Update a host (bad params)
### Update a host with invalid id
PUT {{server}}/hosts/x
Content-Type: application/json

Expand All @@ -61,5 +62,5 @@ Content-Type: application/json
### Delete a host
DELETE {{server}}/hosts/{{createdHostId}}

### Delete a host (bad params)
### Delete a host with invalid id
DELETE {{server}}/hosts/x
2 changes: 2 additions & 0 deletions public/codes/expressjs/monitor-app-api/back/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ server.use(router);
server.listen(3000, () => {
console.log('Server is running on port 3000');
});

export default server;
62 changes: 36 additions & 26 deletions public/codes/expressjs/monitor-app-api/back/src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import express from 'express';
import { v4 as uuidv4 } from 'uuid';
import { hosts } from './data/hosts.js';

class HTTPError extends Error {
constructor(message, code) {
class HttpError extends Error {
constructor(message, code = 400) {
super(message);
this.code = code;
}
Expand All @@ -12,26 +12,34 @@ class HTTPError extends Error {
const router = express.Router();

router.post('/hosts', (req, res) => {
const host = req.body;
const { name, address } = req.body;

const id = uuidv4();
if (!name || !address) {
throw new HttpError('Error when passing parameters');
}

const newHost = { ...host, id };
const id = uuidv4();

if (!host.name || !host.address) {
throw new HTTPError('Error when passing parameters', 400);
}
const newHost = { id, name, address };

hosts.push(newHost);

res.json(newHost);
res.status(201).json(newHost);
});

router.get('/hosts', (req, res) => {
const { name } = req.query;
const where = req.query;

if (name) {
const filteredHosts = hosts.filter((host) => host.name.includes(name));
if (where) {
const field = Object.keys(where)[0];

const value = where[field];

const filteredHosts = hosts.filter((host) =>
host[field] instanceof String
? host[field].toLowerCase().includes(value.toLowerCase())
: host[field] === value
);

return res.json(filteredHosts);
}
Expand All @@ -40,32 +48,32 @@ router.get('/hosts', (req, res) => {
});

router.get('/hosts/:id', (req, res) => {
const id = req.params.id;
const { id } = req.params;

const index = hosts.findIndex((host) => host.id === id);

if (!hosts[index]) {
throw new HTTPError('Host not found', 400);
throw new HttpError('Unable to read a host');
}

return res.json(hosts[index]);
});

router.put('/hosts/:id', (req, res) => {
const host = req.body;
const { name, address } = req.body;

const id = req.params.id;
const { id } = req.params;

if (!host.name || !host.address || !id) {
throw new HTTPError('Error when passing parameters', 400);
if (!name || !address) {
throw new HttpError('Error when passing parameters');
}

const newHost = { ...host, id };
const newHost = { id, name, address };

const index = hosts.findIndex((host) => host.id === id);

if (!hosts[index]) {
throw new HTTPError('Host not found', 400);
throw new HttpError('Unable to update a host');
}

hosts[index] = newHost;
Expand All @@ -74,12 +82,12 @@ router.put('/hosts/:id', (req, res) => {
});

router.delete('/hosts/:id', (req, res) => {
const id = req.params.id;
const { id } = req.params;

const index = hosts.findIndex((host) => host.id === id);

if (!hosts[index]) {
throw new HTTPError('Host not found', 400);
throw new HttpError('Unable to delete a host');
}

hosts.splice(index, 1);
Expand All @@ -89,17 +97,19 @@ router.delete('/hosts/:id', (req, res) => {

// 404 handler
router.use((req, res, next) => {
res.status(404).json({ message: 'Content not found!' });
return res.status(404).json({ message: 'Content not found!' });
});

// Error handler
router.use((err, req, res, next) => {
if (err instanceof HTTPError) {
// console.error(err.message);
console.error(err.stack);

if (err instanceof HttpError) {
return res.status(err.code).json({ message: err.message });
}

// console.error(err.stack);
// next(err)
// next(err);
return res.status(500).json({ message: 'Something broke!' });
});

Expand Down
132 changes: 132 additions & 0 deletions public/codes/expressjs/monitor-app-api/back/src/routes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import request from 'supertest';
import app from './index.js';

let createdHost;

const newHost = {
name: 'DNS Server',
address: '1.1.1.1',
};

const updatedHost = {
name: 'Cloudflare DNS',
address: '1.1.1.1',
};

describe('Moniotr App', () => {
describe('Hosts Endpoints', () => {
describe('POST /hosts', () => {
it('should create a new host', async () => {
const response = await request(app).post('/hosts').send(newHost);

createdHost = response.body;

expect(response.statusCode).toBe(201);
});

it('should not create a new host without name or address', async () => {
const response = await request(app).post('/hosts').send({
name: 'DNS Server',
});

expect(response.statusCode).toBe(400);
});
});

describe('GET /hosts', () => {
it('should show all hosts', async () => {
const response = await request(app).get('/hosts');

expect(response.statusCode).toBe(200);
});

it('should list the valid host', async () => {
const response = await request(app).get('/hosts');

const hasValidHost = response.body.some(
(host) => host.address === createdHost.address
);

expect(hasValidHost).toBeTruthy();
});

it('should show all hosts by name', async () => {
const response = await request(app).get('/hosts?name=DNS');

expect(response.statusCode).toBe(200);
});
});

describe('GET /hosts/:hostId', () => {
it('should show a host by id', async () => {
const response = await request(app).get(`/hosts/${createdHost.id}`);

expect(response.statusCode).toBe(200);

expect(response.body.name).toBe(createdHost.name);
});

it('should not show a host with invalid id', async () => {
const response = await request(app).get(`/hosts/x`);

expect(response.statusCode).toBe(400);

expect(response.body.message).toBe('Unable to read a host');
});
});

describe('PUT /hosts/:hostId', () => {
it('should update a host', async () => {
const response = await request(app)
.put(`/hosts/${createdHost.id}`)
.send(updatedHost);

expect(response.statusCode).toBe(200);
});

it('should list an updated host', async () => {
const response = await request(app).get('/hosts');

const hasValidHost = response.body.some(
(host) => host.address === updatedHost.address
);

expect(hasValidHost).toBeTruthy();
});

it('should not update a host without name or address', async () => {
const response = await request(app)
.put(`/hosts/${createdHost.id}`)
.send({
name: 'Cloudflare DNS',
});

expect(response.statusCode).toBe(400);
});

it('should not update a host with invalid id', async () => {
const response = await request(app).put(`/hosts/x`).send(updatedHost);

expect(response.statusCode).toBe(400);

expect(response.body.message).toBe('Unable to update a host');
});
});

describe('DELETE /hosts/:hostId', () => {
it('should remove a host', async () => {
const response = await request(app).delete(`/hosts/${createdHost.id}`);

expect(response.statusCode).toBe(204);
});

it('should not delete a host with invalid id', async () => {
const response = await request(app).delete(`/hosts/x`);

expect(response.statusCode).toBe(400);

expect(response.body.message).toBe('Unable to delete a host');
});
});
});
});
Loading

0 comments on commit 152124f

Please sign in to comment.