Вопрос

I was looking at the Mercado Libre Java SDK and I noticed that they have a folder called "mockapi" in their repository. It looks like they have written an entire mock api in javascript that they use to test their Java client. However, I still don't quite get how it works. I've posted part of the javascript that is in app.js they are using to do this below.

var express = require('express');
var fs = require('fs');

var app = express.createServer();

app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.bodyParser());
});

app.post('/oauth/token', function(req, res) {
    if(req.query["grant_type"]=="authorization_code") {
        if(req.query["code"]=="bad code") {
            res.send({"message":"Error validando el parámetro   code","error":"invalid_grant","status":400,"cause":[]}, 400);
        } else if(req.query["code"]=="valid code without refresh token") {
            res.send({
                   "access_token" : "valid token",
                   "token_type" : "bearer",
                   "expires_in" : 10800,
                   "scope" : "write read"
            });
        } else if(req.query["code"]=="valid code with refresh token") {
            res.send({
                   "access_token" : "valid token",
                   "token_type" : "bearer",
                   "expires_in" : 10800,
                   "refresh_token" : "valid refresh token",
                   "scope" : "write read"
            });
        } else {
            res.send(404);
        }
    } else if(req.query['grant_type']=='refresh_token') {
        if(req.query['refresh_token']=='valid refresh token') {
            res.send({
                   "access_token" : "valid token",
                   "token_type" : "bearer",
                   "expires_in" : 10800,
                   "scope" : "write read"
            });
        }
    }
});

app.listen(3000);

fs.writeFileSync('/tmp/mockapi.pid', process.pid);

Also, after looking at their file package.json it looks like they are using node. The file is listed below.

{
    "name": "mockapi",
    "version": "1.0.0",
    "dependencies": {
        "express" : "2.5.x"
    },
    "engine": "node ~> 0.8.x"
}

However, after looking at their pom file, it doesn't look like they have Node as a dependancy.I've done mostly Java development, so server-side Javascript is still foreign to me. How is this working exactly? Why don't they have to include a dependency in their POM file? I should also note that most of the tests are failing because I can't make a connection with localhost:3000. Do I have to have node.js installed to be able to run the tests?

Edit: I've added the Junit test that tests the post below as well as a few other tests

package com.mercadolibre.sdk;

import java.io.IOException;

import org.junit.Assert;
import org.junit.Test;

import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;

public class MeliTest extends Assert {
@Test
public void testGetAuthUrl() {
assertEquals(
    "https://auth.mercadolibre.com.ar/authorization?response_type=code&client_id=123456&redirect_uri=http%3A%2F%2Fsomeurl.com",
    new Meli(123456l, "client secret")
        .getAuthUrl("http://someurl.com"));
}

@Test(expected = AuthorizationFailure.class)
public void testAuthorizationFailure() throws AuthorizationFailure {
Meli.apiUrl = "http://localhost:3000";

new Meli(123456l, "client secret").authorize("bad code",
    "http://someurl.com");
}

@Test
public void testAuthorizationSuccess() throws AuthorizationFailure {
Meli.apiUrl = "http://localhost:3000";

Meli m = new Meli(123456l, "client secret");
m.authorize("valid code with refresh token", "http://someurl.com");

assertEquals("valid token", m.getAccessToken());
assertEquals("valid refresh token", m.getRefreshToken());
}

@Test
public void testGetWithRefreshToken() throws MeliException, IOException {
Meli.apiUrl = "http://localhost:3000";

Meli m = new Meli(123456l, "client secret", "expired token",
    "valid refresh token");

FluentStringsMap params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
Response response = m.get("/users/me", params);

assertEquals(200, response.getStatusCode());
assertFalse(response.getResponseBody().isEmpty());
}

public void testPost() throws MeliException {
Meli m = new Meli(123456l, "client secret", "valid token");

FluentStringsMap params = new FluentStringsMap();
params.add("access_token", m.getAccessToken());
Response r = m.post("/items", params, "{\"foo\":\"bar\"}");

assertEquals(201, r.getStatusCode());
}
Это было полезно?

Решение

The short answer to your question is that yes, you need to install node, and make it available in your path for the tests to run. That is why you aren't getting a connection on 3000.

Your comment about "not sure how it works" - the short answer is that the javascript code running in node is a web server on its own. Node isn't a container in the way you would be used to with Tomcat, Glassfish, etc. Speaking generally, the Javascript code you have pasted above creates a webserver using Express (the most broadly-used node web framework, which along with Connect give you the sort of things that the Servlet API does). The server created responds to a single type of request, a POST to /oauth/token.

Другие советы

How is this working exactly?

It looks like the javascript is designed to be a mock server; i.e. to respond to requests sent by client-side library code under test. The unit tests you have added seems to be doing that.

Why don't they have to include a dependency in their POM file?

The intention is that you should set up the test server by hand in order to run those tests. Besides, it doesn't make sense to declare a Maven dependency on a piece of (non-Java) software that has to be installed and launched for unit testing.

(You might be able to get Maven to do that kind of thing, but I'm not sure it is a good idea. And clearly, the project developers haven't done this ...)

This theory is supported by the Makefile.

Do I have to have node.js installed to be able to run the tests?

I suggest that you try it and see ... and / or read and understand the Makefile and its significance.


But seriously, you should probably be asking these questions of the authors. The README file says:

"You can contact us if you have questions using the standard communication channels described in the developer's site"

and there is a link to the site.

Once you have figured it out, send them a pull request that improves their developer documentation by documenting the test procedures.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top