先日、slim3-1.0.6がリリースされました。たくさん機能追加がありますが、最近の自分的に嬉しい機能のひとつにController内でInputStreamが使えるissue62への対応があります。
Support for Controller#createRequestHandler():この機能を使用する際のテストケースの書き方の例を書いておこうと思います。あと、ついでにMetaクラスにJson->Model、Model->Jsonを行うユーティリティメソッドが追加されているのでそれも使っています。@takawitterさんの仕事です、ありがとうございます、便利です。
http://code.google.com/p/slim3/issues/detail?id=62
まずはController
Httpメソッドとリクエストパラメータによって追加・修正・削除と1件返却、リスト返却を実装しているだけのシンプルなものです。ポイントはControllerではなくSimpleControllerクラスを継承している点と、asString()は使わずrequest.getParameter()でパラメータを取得するという点と、ModelMetaクラスのJson用ユーティリティメソッドが便利という点です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.util.List; | |
import org.apache.commons.io.IOUtils; | |
import org.slim3.controller.Navigation; | |
import org.slim3.controller.SimpleController; | |
import org.slim3.datastore.Datastore; | |
import com.shin1ogawa.meta.Slim3ModelMeta; | |
import com.shin1ogawa.model.Slim3Model; | |
public class JsonController extends SimpleController { | |
@Override | |
protected Navigation run() throws Exception { | |
response.setContentType("application/json"); | |
response.setCharacterEncoding("utf-8"); | |
try { | |
String id = request.getParameter("id"); | |
if (isPost()) { | |
if (id != null && id.isEmpty() == false) { | |
return doPut(id); | |
} | |
return doPost(); | |
} else if (isPut()) { | |
if (id == null || id.isEmpty()) { | |
response.setStatus(400); | |
return null; | |
} | |
return doPut(id); | |
} else if (isDelete()) { | |
if (id == null || id.isEmpty()) { | |
response.setStatus(400); | |
return null; | |
} | |
return doDelete(id); | |
} else { | |
if (id == null || id.isEmpty()) { | |
return doList(); | |
} | |
return doGet(id); | |
} | |
} finally { | |
response.flushBuffer(); | |
} | |
} | |
static final Slim3ModelMeta meta = Slim3ModelMeta.get(); | |
Navigation doList() throws IOException { | |
List<Slim3Model> list = Datastore.query(meta).asList(); | |
StringBuilder b = new StringBuilder("entities: ["); | |
boolean first = true; | |
for (Slim3Model model : list) { | |
if (first == false) { | |
b.append(','); | |
} else { | |
first = false; | |
} | |
b.append(meta.modelToJson(model)); | |
} | |
b.append("]"); | |
response.getWriter().print(b); | |
return null; | |
} | |
Navigation doGet(String id) throws IOException { | |
Slim3Model model = Datastore.getOrNull(meta, Datastore.createKey(meta, id)); | |
if (model == null) { | |
response.setStatus(404); | |
return null; | |
} | |
response.getWriter().print(meta.modelToJson(model)); | |
return null; | |
} | |
Navigation doPut(String id) throws IOException { | |
Slim3Model model = Datastore.getOrNull(meta, Datastore.createKey(meta, id)); | |
if (model == null) { | |
response.setStatus(404); | |
return null; | |
} | |
String json = IOUtils.toString(request.getInputStream()); | |
Slim3Model newModel = meta.jsonToModel(json); | |
model.setProp1(newModel.getProp1()); | |
Datastore.put(model); | |
response.getWriter().print(meta.modelToJson(model)); | |
return null; | |
} | |
Navigation doPost() throws IOException { | |
String json = IOUtils.toString(request.getInputStream()); | |
Slim3Model model = meta.jsonToModel(json); | |
Datastore.put(model); | |
response.getWriter().print(meta.modelToJson(model)); | |
return null; | |
} | |
Navigation doDelete(String id) throws IOException { | |
Slim3Model model = Datastore.getOrNull(meta, Datastore.createKey(meta, id)); | |
if (model == null) { | |
response.setStatus(404); | |
return null; | |
} | |
Datastore.delete(model.getKey()); | |
response.getWriter().print(meta.modelToJson(model)); | |
return null; | |
} | |
} |
ControllerをテストするControllerTest
ServletInputStream
を実装したJsonInputStream
というクラスを用意し、MockHttpServletRequest#setInputStream()
に設定することでControllerへのpayloadを設定しています。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.hamcrest.CoreMatchers.*; | |
import static org.junit.Assert.*; | |
import java.io.ByteArrayInputStream; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.List; | |
import javax.servlet.ServletException; | |
import javax.servlet.ServletInputStream; | |
import org.junit.Test; | |
import org.slim3.datastore.Datastore; | |
import org.slim3.tester.ControllerTestCase; | |
import com.shin1ogawa.meta.Slim3ModelMeta; | |
import com.shin1ogawa.model.Slim3Model; | |
public class JsonControllerTest extends ControllerTestCase { | |
static final String PATH = "/json"; | |
static final Slim3ModelMeta meta = Slim3ModelMeta.get(); | |
@Test public void post() throws NullPointerException, IllegalArgumentException, | |
IOException, ServletException { | |
int beforeCount = tester.count(Slim3Model.class); | |
String content = "{\"prop1\":\"hoge\"}"; | |
tester.request.setInputStream(new JsonInputStream(content.getBytes("utf-8"))); | |
tester.request.setMethod("POST"); | |
tester.start(PATH); | |
assertThat(tester.getController(), is(instanceOf(JsonController.class))); | |
assertThat(tester.response.getStatus(), is(200)); | |
assertThat(tester.response.getContentType(), is("application/json")); | |
assertThat("postなので1件増える", tester.count(Slim3Model.class), is(beforeCount + 1)); | |
Slim3Model model = meta.jsonToModel(tester.response.getOutputAsString()); | |
assertThat(model.getProp1(), is("hoge")); | |
} | |
@Test public void put() throws NullPointerException, IllegalArgumentException, | |
IOException, ServletException { | |
int beforeCount = tester.count(Slim3Model.class); | |
String content = "{\"prop1\":\"hoge\"}"; | |
tester.request.addParameter("id", "8"); | |
tester.request.setInputStream(new JsonInputStream(content.getBytes("utf-8"))); | |
tester.request.setMethod("PUT"); | |
tester.start(PATH); | |
assertThat(tester.getController(), is(instanceOf(JsonController.class))); | |
assertThat(tester.response.getStatus(), is(200)); | |
assertThat(tester.response.getContentType(), is("application/json")); | |
assertThat("putでは増えない", tester.count(Slim3Model.class), is(beforeCount)); | |
Slim3Model model = meta.jsonToModel(tester.response.getOutputAsString()); | |
assertThat(model.getKey(), is(Datastore.createKey(meta, "8"))); | |
assertThat(model.getProp1(), is("hoge")); | |
} | |
@Test public void postWithId() throws NullPointerException, | |
IllegalArgumentException, IOException, ServletException { | |
int beforeCount = tester.count(Slim3Model.class); | |
String content = "{\"prop1\":\"hoge\"}"; | |
tester.request.addParameter("id", "8"); | |
tester.request.setInputStream(new JsonInputStream(content.getBytes("utf-8"))); | |
tester.request.setMethod("POST"); | |
tester.start(PATH); | |
assertThat(tester.getController(), is(instanceOf(JsonController.class))); | |
assertThat(tester.response.getStatus(), is(200)); | |
assertThat(tester.response.getContentType(), is("application/json")); | |
assertThat("id有りPostはPut操作となり、増えない", tester.count(Slim3Model.class), is(beforeCount)); | |
Slim3Model model = meta.jsonToModel(tester.response.getOutputAsString()); | |
assertThat(model.getKey(), is(Datastore.createKey(meta, "8"))); | |
assertThat(model.getProp1(), is("hoge")); | |
} | |
static class JsonInputStream extends ServletInputStream { | |
ByteArrayInputStream in; | |
JsonInputStream(byte[] content) { | |
this.in = new ByteArrayInputStream(content); | |
} | |
@Override public int available() throws IOException { | |
return in.available(); | |
} | |
@Override public int read() throws IOException { | |
return in.read(); | |
} | |
@Override public int read(byte[] b, int off, int len) throws IOException { | |
return in.read(b, off, len); | |
} | |
} | |
@Override public void setUp() throws Exception { | |
super.setUp(); | |
List<Slim3Model> entities = new ArrayList<Slim3Model>(); | |
for (int i = 0; i < 10; i++) { | |
Slim3Model model = new Slim3Model(); | |
model.setKey(Datastore.createKey(Slim3Model.class, String.valueOf(i))); | |
model.setProp1(String.valueOf(i)); | |
entities.add(model); | |
} | |
Datastore.put(entities); | |
} | |
} |
issue62とJson用ユーティリティメソッドのおかげでjsonをやりとりするControllerが一気に作り易くなって、かなーり助かります。ただ、jsonArrayToModels()
やmodelsToJsonArray()
が無いのがちょっと勿体無いかな?
0 件のコメント:
コメントを投稿