小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

【nodejs】使用Node.js實(shí)現(xiàn)REST Client調(diào)用REST API

 時(shí)間要去哪 2015-08-12

最近在產(chǎn)品中開發(fā)基于REST的API接口,結(jié)合自己最近對(duì)Node.js的研究,想基于它開發(fā)一個(gè)REST Client做測(cè)試之用。

通過初步研究,Node.js開發(fā)HTTP Client還是挺方便的。

 

選用Node的理由:

1. 使用完全基于JavaScript的Node測(cè)試JSON格式的數(shù)據(jù),非常之方便

2. Node有很好的社區(qū)支持。(現(xiàn)在GitHub上已成了JavaScript最大的開源社區(qū))

 

By Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var http = require('http');
var equal = require('assert').equal;
var username = 'falcon';
var password = '';
var _auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64')
var options = {
    host: 'localhost',
    port: 13080,
    path: '/SM/7/rest/1.1/incident_list/',
    method: 'GET',
    headers:{
        'accept': '*/*',
        'content-type': "application/atom+xml",
        'accept-encoding': 'gzip, deflate',
        'accept-language': 'en-US,en;q=0.9',
        'authorization': _auth,
        'user-agent': 'nodejs rest client'
    }
};
var req = http.request(options, function (res) {
    console.log('STATUS: ' + res.statusCode);
    equal(200, res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.on('data',function (chunk) {
         console.log('BODY: ' + chunk);
    });
});
req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});
req.end();

 

將上述代碼保存成RestTest.js,然后在命令行上運(yùn)行: node RestTest.js 就可以看輸出的結(jié)果了。

 

上面的代碼只是使用Node自帶的Assert做Unit Test,如果有興趣的話,還是引入Jasmine等BDD的測(cè)試框架。(待續(xù)。。。)

 

生成測(cè)報(bào)告:

1. Maven Jasmine plugin (SM Client Team已在使用了)

2. Testacular by Google(本博主推薦)

 

P.S.:

如果你是CoffeeScript的Fans可以參考下面的代碼片段

復(fù)制代碼
http = require 'http'
equal = require('assert').equal

username = 'falcon'
password = ''
_auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64')

options = 
    host: 'localhost'
    port: 13080
    path: '/SM/7/rest/1.1/incident_list/'
    method: 'GET'
    headers:
        'accept': '*/*'
        'content-type': "application/atom+xml"
        'accept-encoding': 'gzip, deflate'
        'accept-language': 'en-US,en;q=0.9'
        'authorization': _auth
        'user-agent': 'nodejs rest client'

req = http.request options, (res) -> 
    console.log('STATUS: ' + res.statusCode)
    equal(200, res.statusCode)
    console.log('HEADERS: ' + JSON.stringify(res.headers))

    res.on 'data', (chunk)-> 
         console.log('BODY: ' + chunk)

    req.on 'error', (e)->
      console.log('problem with request: ' + e.message)

req.end()
復(fù)制代碼

 

 

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多