Skip to content

Commit

Permalink
Ajustando leitura do retorno e tratando requisições sem retorno.
Browse files Browse the repository at this point in the history
  • Loading branch information
brunobrandaosbx committed May 22, 2018
1 parent adb69b2 commit bdbb52d
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 67 deletions.
12 changes: 12 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
language: bash
services:
- docker

script: docker run --rm -v $(pwd):/app -w /app/test thrustjs/thrust-docker /bin/sh -c "thrust install && thrust test.httpClient.js"

deploy:
provider: releases
api_key: $githubToken
skip_cleanup: true
on:
tags: true
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
HttpClient
[![Build Status](https://travis-ci.org/thrust-bitcodes/http-client.svg?branch=master)](https://travis-ci.org/thrust-bitcodes/http-client) [![GitHub release](https://img.shields.io/github/release/thrust-bitcodes/http-client.svg)](https://github.com/thrust-bitcodes/http-client/releases)
===============

HttpClient é um *bitcode* de acesso HTTP e HTTPS para [ThrustJS](https://github.com/thrustjs/thrust).
Expand Down Expand Up @@ -43,6 +44,8 @@ delete(url, params)

## What's new

v1.3.3 - Fix: Ajustando leitura do retorno e tratando requisições sem retorno.

v1.3.2 - Fix: Quando uma requisição retorna com erro, o atributo "body" no objeto de retorno fica com o valor _undefined_.

v1.3.1 - Fix: Método GET chamado com query-string na URL estava com erro
Expand Down
2 changes: 1 addition & 1 deletion brief.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"description": "HTTP client module",
"name": "http-client",
"path": "index.js",
"version": "1.3.2",
"version": "1.3.3",
"author": "Nery Jr",
"contributors": [
"Cleverson Puche",
Expand Down
66 changes: 28 additions & 38 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function mountHttpRequest(method, url, reqParams) {
}

var fluent = {
params: function(pars) {
params: function (pars) {
if ((isObject(params) || params === undefined) && isObject(pars)) {
params = merge((params || {}), pars)
} else {
Expand All @@ -19,55 +19,50 @@ function mountHttpRequest(method, url, reqParams) {
return fluent
},

property: function(property, value) {
property: function (property, value) {
properties[property] = value

return fluent
},

headers: function(headers) {
headers: function (headers) {
properties = Object.assign({}, properties, headers)

return fluent
},

charset: function(value) {
charset: function (value) {
properties['Accept-Charset'] = value

return fluent
},

contentType: function(value) {
contentType: function (value) {
properties['Content-Type'] = value

return fluent
},

getContent: function(httpConnection) {
var inputStream = httpConnection.getInputStream()
var scanner = new Scanner(inputStream, 'UTF-8')
var content = scanner.useDelimiter('\\Z|\\A').next()
getContent: function (httpConnection) {
var inputStream;
var scanner;

scanner.close()
inputStream.close()
try {
inputStream = httpConnection.getErrorStream();

return content
},
if (!inputStream) {
inputStream = httpConnection.getInputStream();
}

getErrorContent: function(httpConnection) {
var inputStream = httpConnection.getErrorStream()
scanner = new Scanner(inputStream, 'UTF-8').useDelimiter('\\Z|\\A');

if(!inputStream) {
return undefined
if (scanner.hasNext()) {
return scanner.next();
}
} finally {
scanner && scanner.close()
inputStream && inputStream.close()
}

var scanner = new Scanner(inputStream, 'UTF-8')
var content = scanner.useDelimiter('\\Z|\\A').next()

scanner.close()
inputStream.close()

return content
},

fetch: function _fetch() {
Expand Down Expand Up @@ -99,7 +94,7 @@ function mountHttpRequest(method, url, reqParams) {

output = httpConnection.getOutputStream()
output.write((params || '').getBytes(properties.charset))
} else /* if (method.toUpperCase() == "GET") */ {
} else {
if (params && params.constructor.name === 'Object') {
url += '?' + serializeParams(params)
} else if (params !== undefined) {
Expand All @@ -120,15 +115,10 @@ function mountHttpRequest(method, url, reqParams) {
header[key] = headerFields[key][0]
}

if (httpCode >= 400) {
body = fluent.getErrorContent(httpConnection)
} else {
var data = fluent.getContent(httpConnection)
var data = fluent.getContent(httpConnection)
var isJSON = data && (header['Content-Type'] && header['Content-Type'].indexOf('application/json') >= 0);

body = (header['Content-Type'] && header['Content-Type'].indexOf('application/json') >= 0)
? JSON.parse(data)
: data
}
body = isJSON ? JSON.parse(data) : data

return { code: httpCode, body: body, headers: header }
}
Expand Down Expand Up @@ -176,10 +166,10 @@ function isObject(val) {
* HTTPClient.post("http://localhost:8080/test/hello").fetch()
*/
var HTTPClient = {
get: function(url, params) { return mountHttpRequest('GET', url, params) },
post: function(url, params) { return mountHttpRequest('POST', url, params) },
put: function(url, params) { return mountHttpRequest('PUT', url, params) },
delete: function(url, params) { return mountHttpRequest('DELETE', url, params) }
get: function (url, params) { return mountHttpRequest('GET', url, params) },
post: function (url, params) { return mountHttpRequest('POST', url, params) },
put: function (url, params) { return mountHttpRequest('PUT', url, params) },
delete: function (url, params) { return mountHttpRequest('DELETE', url, params) }
}

exports = HTTPClient
Expand Down
97 changes: 69 additions & 28 deletions test/test.httpClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,23 @@ function exec(describe, it, beforeEach, afterEach, expect, should, assert) {
// afterEach(function() { })
// beforeEach(function() { })

describe('Client HTTP e HTTPS para thrust', function() {
describe('Método [GET]', function() {
it('Executando método GET retornando um array de objetos json', function() {
describe('Client HTTP e HTTPS para thrust', function () {
describe('Método [GET]', function () {
it('GET com retorno 404', function () {
rs = httpClient.get('https://postman-echo.com/status/404')
.fetch()

expect(rs.code).to.equal(404)
})

it('GET com retorno 500', function () {
rs = httpClient.get('https://postman-echo.com/status/500')
.fetch()

expect(rs.code).to.equal(500)
})

it('Executando método GET retornando um array de objetos json', function () {
rs = httpClient.get('https://jsonplaceholder.typicode.com/posts')
.charset('UTF-8')
.fetch()
Expand All @@ -32,7 +46,8 @@ function exec(describe, it, beforeEach, afterEach, expect, should, assert) {
expect(rs.body).to.be.an('array')
expect(rs.body.length).to.equal(100)
})
it('Executando método GET retornando um objeto json', function() {

it('Executando método GET retornando um objeto json', function () {
rs = httpClient.get('https://jsonplaceholder.typicode.com/posts/1')
.charset('UTF-8')
.fetch()
Expand All @@ -41,7 +56,7 @@ function exec(describe, it, beforeEach, afterEach, expect, should, assert) {
expect(rs.body.id).to.equal(1)
})

it('Método GET utilizando [.headers]', function() {
it('Método GET utilizando [.headers]', function () {

rs = httpClient.get('https://postman-echo.com/headers')
.headers({
Expand All @@ -57,29 +72,37 @@ function exec(describe, it, beforeEach, afterEach, expect, should, assert) {
expect(rs.body.headers.app).to.equal('thrust')
})

it('Executando método POST inserindo um objeto json', function() {
var di = new Date().getTime()
})
describe('Método [POST]', function () {

rs = httpClient.post('https://reqres.in/api/users')
.property('user-agent', 'thrustBot-http-client/1.3.0')
.contentType('application/json')
.params({
'name': 'thrust',
'job': 'platform'
})
.fetch()
it('POST com retorno 404', function () {
rs = executaEMostraTempo(function () {
return httpClient.post('https://postman-echo.com/status/404')
.fetch()

expect(rs.code).to.equal(404)
})
})

var df = new Date().getTime()
it('Executando método POST inserindo um objeto json', function () {
rs = executaEMostraTempo(function () {
return httpClient.post('https://reqres.in/api/users')
.property('user-agent', 'thrustBot-http-client/1.3.0')
.contentType('application/json')
.params({
'name': 'thrust',
'job': 'platform'
})
.fetch()
})

expect(rs.code).to.equal(201)
expect(rs.body).to.have.own.property('id')
expect(rs.body.id).to.not.equal(undefined)
expect(rs.body).to.include({ 'name': 'thrust', 'job': 'platform' })

print('\tTempo de execução:', (df - di), 'ms.')
})

it('Executando método POST (site 2) inserindo um objeto json', function() {
it('Executando método POST (site 2) inserindo um objeto json', function () {
rs = httpClient.post('https://jsonplaceholder.typicode.com/posts')
.property('user-agent', 'thrustBot-http-client/1.3.0')
.contentType('application/json; charset=UTF-8')
Expand All @@ -97,7 +120,7 @@ function exec(describe, it, beforeEach, afterEach, expect, should, assert) {
expect(rs.body).to.include({ 'title': 'foo', 'body': 'bar' })
})

it('Método POST utilizando [.headers]', function() {
it('Método POST utilizando [.headers]', function () {
rs = httpClient.post('https://jsonplaceholder.typicode.com/posts')
.headers({
'origin': 'chrome-extension://aejoelaoggembcahagimdiliamlcdmfm',
Expand All @@ -118,22 +141,40 @@ function exec(describe, it, beforeEach, afterEach, expect, should, assert) {
expect(rs.body.id).to.not.equal(undefined)
expect(rs.body).to.include({ 'title': 'foo', 'body': 'bar' })
})

it('Método POST sem body no retorno', function () {
rs = executaEMostraTempo(function () {
return httpClient.post('https://mockbin.org/echo')
.headers({
'Accept': 'application/json'
})
.fetch()
})

expect(rs.code).to.equal(200)
expect(rs.body).to.equal(undefined)
})
})
})
}

function executaEMostraTempo(fn) {
var di = new Date().getTime()
var result = fn();
var df = new Date().getTime()

print('\tTempo de execução:', (df - di), 'ms.')

return result;
}

var res = majesty.run(exec)

print('', res.success.length, ' scenarios executed with success and')
print('', res.failure.length, ' scenarios executed with failure.\n')

res.failure.forEach(function(fail) {
print('[' + fail.scenario + '] =>', fail.execption)
var i = 0
if (fail.execption.printStackTrace && i === 0) {
// fail.execption.printStackTrace()
i++
}
res.failure.forEach(function (fail) {
print("[" + fail.scenario + "] =>", fail.execption)
})

// java.lang.Runtime.getRuntime().exec("cmd /k chcp 65001");
exit(res.failure.length);

0 comments on commit bdbb52d

Please sign in to comment.