Skip to content

Commit

Permalink
make test more easy
Browse files Browse the repository at this point in the history
  • Loading branch information
allwefantasy committed Jun 30, 2013
1 parent 8735230 commit 0167a69
Show file tree
Hide file tree
Showing 21 changed files with 237 additions and 111 deletions.
9 changes: 9 additions & 0 deletions doc/develop_diary.md
Original file line number Diff line number Diff line change
Expand Up @@ -546,4 +546,13 @@ application:
上面我们只是讨论了Model,Controller的设计问题。其实还有Service和Util的设计问题。这个应该通过IOC来处理。至于静态资源文件则不在讨论方位之内。


## 约定

关于 类名 <=> 表明

BlogTag <=> blog_tag





Binary file modified jar/service_framework.jar
Binary file not shown.
Binary file modified lib/active-orm.jar
Binary file not shown.
Binary file modified lib/csdn-common.jar
Binary file not shown.
Binary file modified lib/mongomongo.jar
Binary file not shown.
1 change: 1 addition & 0 deletions src/net/csdn/bootstrap/Bootstrap.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ private static void configureSystem() throws Exception {
loaders.add(new ServiceLoader());
loaders.add(new UtilLoader());
loaders.add(new ControllerLoader());
loaders.add(new TemplateLoader());
if (!ServiceFramwork.mode.equals(ServiceFramwork.Mode.test)) {
loaders.add(new ThriftLoader());
}
Expand Down
25 changes: 25 additions & 0 deletions src/net/csdn/bootstrap/loader/impl/TemplateLoader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package net.csdn.bootstrap.loader.impl;

import net.csdn.bootstrap.loader.Loader;
import net.csdn.common.env.Environment;
import net.csdn.common.settings.Settings;
import org.apache.velocity.app.Velocity;

import java.util.Properties;

/**
* 6/29/13 WilliamZhu([email protected])
*/
public class TemplateLoader implements Loader {
@Override
public void load(Settings settings) throws Exception {
Environment environment = new Environment(settings);
if (settings.getAsBoolean("application.template.engine.enable", false)) {
Properties properties = new Properties();
properties.setProperty("file.resource.loader.path", environment.templateDirFile().getPath());
properties.setProperty("input.encoding", "utf-8");
properties.setProperty("output.encoding", "utf-8");
Velocity.init(properties);
}
}
}
104 changes: 104 additions & 0 deletions src/net/csdn/junit/BaseControllerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package net.csdn.junit;

import net.csdn.common.exception.RenderFinish;
import net.csdn.modules.http.RestController;
import net.csdn.modules.http.RestRequest;
import net.csdn.modules.http.RestResponse;
import net.csdn.modules.mock.MockRestRequest;
import net.csdn.modules.mock.MockRestResponse;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import static net.csdn.common.collections.WowCollections.map;

/**
* 6/28/13 WilliamZhu([email protected])
*/
public class BaseControllerTest extends IocTest {

public RestResponse runAction(String path, Map params, RestRequest.Method method) throws Exception {
RestResponse response = new MockRestResponse();
RestController controller = injector.getInstance(RestController.class);
try {
controller.dispatchRequest(new MockRestRequest(path, params, method, null), response);
} catch (Exception e) {
catchRenderFinish(e);
}
return response;
}

private void catchRenderFinish(Exception e) throws Exception {
if (e instanceof RenderFinish) {
} else if (e instanceof InvocationTargetException) {
if (((InvocationTargetException) e).getTargetException() instanceof RenderFinish) {

} else {
throw e;
}

} else {
throw e;
}
}

public RestResponse runAction(String path, String rawParamsStr, RestRequest.Method method) throws Exception {
RestResponse response = new MockRestResponse();
RestController controller = injector.getInstance(RestController.class);
try {
controller.dispatchRequest(new MockRestRequest(path, map(), method, rawParamsStr), response);
} catch (Exception e) {
catchRenderFinish(e);
}
return response;
}

public Map<RestRequest.Method, RestResponse> each(List<RestRequest.Method> methods, String path, Map params) throws Exception {
Map<RestRequest.Method, RestResponse> maps = map();
for (RestRequest.Method method : methods) {
maps.put(method, runAction(path, params, method));
}
return maps;
}

public Map<RestRequest.Method, RestResponse> each(List<RestRequest.Method> methods, String path, String rawParamStr) throws Exception {
Map<RestRequest.Method, RestResponse> maps = map();
for (RestRequest.Method method : methods) {
maps.put(method, runAction(path, rawParamStr, method));
}
return maps;
}

public RestResponse get(String path, Map params) throws Exception {
return runAction(path, params, RestRequest.Method.GET);
}

public RestResponse post(String path, Map params) throws Exception {
return runAction(path, params, RestRequest.Method.POST);
}

public RestResponse delete(String path, Map params) throws Exception {
return runAction(path, params, RestRequest.Method.DELETE);
}

public RestResponse put(String path, Map params) throws Exception {
return runAction(path, params, RestRequest.Method.PUT);
}

public RestResponse get(String path, String rawParamsStr) throws Exception {
return runAction(path, rawParamsStr, RestRequest.Method.GET);
}

public RestResponse post(String path, String rawParamsStr) throws Exception {
return runAction(path, rawParamsStr, RestRequest.Method.POST);
}

public RestResponse delete(String path, String rawParamsStr) throws Exception {
return runAction(path, rawParamsStr, RestRequest.Method.DELETE);
}

public RestResponse put(String path, String rawParamsStr) throws Exception {
return runAction(path, rawParamsStr, RestRequest.Method.PUT);
}
}
7 changes: 7 additions & 0 deletions src/net/csdn/junit/BaseServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package net.csdn.junit;

/**
* 6/28/13 WilliamZhu([email protected])
*/
public class BaseServiceTest extends IocTest {
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package net.csdn.junit;

import com.google.inject.Injector;
import javassist.CtClass;
import net.csdn.ServiceFramwork;
import net.csdn.jpa.JPA;
import org.junit.After;
import org.junit.Before;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
* BlogInfo: WilliamZhu
Expand All @@ -17,28 +13,20 @@
*/
public class IocTest {
protected final static Injector injector = ServiceFramwork.injector;
protected static boolean startUp = false;

// static {
// if (!startUp) {
// try {
// initEnv();
// } catch (Exception e) {
// e.printStackTrace();
// }
// startUp = true;
// }
// }

public void dbCommit() {
JPA.getJPAConfig().getJPAContext().closeTx(false);
}

public void commitTransaction() {
dbCommit();
}

/*
因为很多Service是private的。有时候我们需要替换掉一些Service对象。比如HttpTransportService.
这样可以避免去访问真实的服务。否则,你可以继承BaseServiceWithJettyTest
*/
protected void setService(Object targetObj, String fieldName, Object fieldValue) {
protected void mockService(Object targetObj, String fieldName, Object fieldValue) {
try {
Field field = targetObj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Expand All @@ -48,27 +36,15 @@ protected void setService(Object targetObj, String fieldName, Object fieldValue)
}
}

@Before
public void setUp() throws Exception {


}

public static void initEnv() throws Exception {
ServiceFramwork.mode = ServiceFramwork.Mode.test;
CtClass ctClass = ServiceFramwork.classPool.get("net.csdn.bootstrap.Bootstrap");
//加载Guice容器
Method method = ctClass.toClass().getDeclaredMethod("configureSystem");
method.setAccessible(true);
method.invoke(null);
public <T> T findController(Class<T> clzz) {
return injector.getInstance(clzz);
}

@After
public void tearDown() throws Exception {
dbCommit();
public <T> T findService(Class<T> clzz) {
return injector.getInstance(clzz);
}

protected void setService(Object targetObj, Class<?> fieldClass, Object fieldValue) {
protected void mockService(Object targetObj, Class<?> fieldClass, Object fieldValue) {
try {

Field[] fields = targetObj.getClass().getDeclaredFields();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import net.csdn.bootstrap.Bootstrap;
import org.junit.After;
import org.junit.Before;

/**
* BlogInfo: WilliamZhu
Expand All @@ -11,15 +10,10 @@
*/
public class JettyTest extends IocTest {

@Before
public void setUp() throws Exception {
super.setUp();
}

@After
public void tearDown() throws Exception {
Bootstrap.shutdown();
super.tearDown();
}

public void runTargetServer(Runnable runnable) {
Expand Down
47 changes: 44 additions & 3 deletions src/net/csdn/modules/http/ApplicationController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import net.csdn.ServiceFramwork;
import net.csdn.common.Strings;
import net.csdn.common.collect.Tuple;
import net.csdn.common.collections.WowCollections;
import net.csdn.common.exception.ArgumentErrorException;
import net.csdn.common.exception.RenderFinish;
Expand All @@ -23,8 +24,12 @@
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.joda.time.DateTime;

import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -103,10 +108,46 @@ public void render(int status, String content, ViewType viewType) {
throw new RenderFinish();
}

public void renderHtml(int status, String path, Map result) {
VelocityContext context = new VelocityContext();
if (result instanceof Map) {
Map<String, Object> temp = (Map) result;
for (Map.Entry<String, Object> entry : temp.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
}
StringWriter w = new StringWriter();
Velocity.mergeTemplate(path, "utf-8", context, w);
restResponse.write(status, w.toString(), ViewType.html);
}

public void render(int status, Object result, ViewType viewType) {
restResponse.originContent(result);
restResponse.write(status, viewType == ViewType.xml ? toXML(result) : toJson(result), viewType);
if (viewType == ViewType.xml) {
restResponse.write(status, toXML(result), viewType);
} else if (viewType == ViewType.json) {
restResponse.write(status, toJson(result), viewType);
} else if (viewType == ViewType.string) {
restResponse.write(status, result.toString(), viewType);
} else if (viewType == ViewType.html) {

String[] tempArray = getClass().getName().split("\\.");
String controllerName = StringUtils.substringBefore(Strings.toUnderscoreCase(tempArray[tempArray.length - 1]), "_controller");
RestController restController = ServiceFramwork.injector.getInstance(RestController.class);
Tuple<Class<ApplicationController>, Method> handlerKey = restController.getHandler(request);
String actionName = Strings.toUnderscoreCase(handlerKey.v2().getName());

VelocityContext context = new VelocityContext();
if (result instanceof Map) {
Map<String, Object> temp = (Map) result;
for (Map.Entry<String, Object> entry : temp.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
}
StringWriter w = new StringWriter();
Velocity.mergeTemplate(controllerName + "/" + actionName + ".vm", "utf-8", context, w);
restResponse.write(status, w.toString(), viewType);
}
throw new RenderFinish();
}

Expand All @@ -125,7 +166,7 @@ public void render(Object result) {
}


public class OutPutConfig extends JsonConfig {
public class JSONOutPutConfig extends JsonConfig {
private boolean pretty = false;

public boolean isPretty() {
Expand Down Expand Up @@ -159,7 +200,7 @@ public String toJson(Object obj) {
return _toJson(obj).toString();
}

protected OutPutConfig config = new OutPutConfig();
protected JSONOutPutConfig config = new JSONOutPutConfig();

public JSON _toJson(Object obj) {
JsonConfig config = new JsonConfig();
Expand Down
10 changes: 9 additions & 1 deletion src/net/csdn/modules/http/HttpServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,13 @@ public void write(String content) {

private void configureMimeType(ViewType viewType) {
if (viewType == ViewType.xml) {
content_type = "application/xml; charset=UTF-8";
content_type = "application/xml;charset=UTF-8";
} else if (viewType == ViewType.image) {
content_type = "image/jpeg";
} else if (viewType == ViewType.string) {
content_type = "text/plain;charset=UTF-8";
} else if (viewType == ViewType.html) {
content_type = "text/html;charset=UTF-8";
}
}

Expand Down Expand Up @@ -146,6 +150,10 @@ public RestResponse originContent(Object obj) {
return null;
}

@Override
public int status() {
return status;
}

public void send() throws IOException {
if (content != null) {
Expand Down
2 changes: 1 addition & 1 deletion src/net/csdn/modules/http/RestController.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private void filter(Tuple<Class<ApplicationController>, Method> handlerKey, Appl
}


private Tuple<Class<ApplicationController>, Method> getHandler(RestRequest request) {
public Tuple<Class<ApplicationController>, Method> getHandler(RestRequest request) {
String path = getPath(request);
RestRequest.Method method = request.method();
if (method == RestRequest.Method.GET) {
Expand Down
2 changes: 2 additions & 0 deletions src/net/csdn/modules/http/RestResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,6 @@ public interface RestResponse {
public Object originContent();

public RestResponse originContent(Object obj);

public int status();
}
Loading

0 comments on commit 0167a69

Please sign in to comment.