throws ServerException {
if (getUriPathSegments().containsAll(request.getUriPathSegments())) {
+ checkQueryException(Arrays.asList(Constants.REQ_GROUP_MASTER_ID,
+ Constants.REQ_GROUP_ID), request.getUriQueryMap());
+
String gmid = request.getUriQueryMap()
.get(Constants.REQ_GROUP_MASTER_ID).get(0);
String gid = request.getUriQueryMap().get(Constants.REQ_GROUP_ID)
.get(0);
- if (gmid == null || gid == null) {
- throw new PreconditionFailedException(
- "gmid and gid property is invalid");
- }
mGrManager.deleteGroup(gmid, gid);
} else {
String gid = request.getUriPathSegments()
.get(getUriPathSegments().size());
-
if (request.getUriQueryMap()
.containsKey(Constants.REQ_MEMBER_LIST)) {
List<String> midList = request.getUriQueryMap()
import org.iotivity.cloud.accountserver.db.UserTable;
import org.iotivity.cloud.accountserver.resources.acl.group.GroupResource;
import org.iotivity.cloud.accountserver.util.TypeCastingManager;
-import org.iotivity.cloud.base.ServerSystem;
-import org.iotivity.cloud.base.ServerSystem.PersistentPacketReceiver;
import org.iotivity.cloud.base.device.CoapDevice;
-import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelId;
-import io.netty.util.Attribute;
-
public class AccountResourceTest {
private static final String REGISTER_URI = "/.well-known/ocf/account";
private static final String GROUP_URI = "/.well-known/ocf/acl/group";
- private String di = "B371C481-38E6-4D47-8320-7688D8A5B58C";
- private String authProvider = "Github";
- private String authCode = "7af49183966f84e553dc";
- String userId = "testuser";
- private CoapDevice mockDevice = mock(
+ private static final String DEVICE_ID = "B371C481-38E6-4D47-8320-7688D8A5B58C";
+ private String mAuthProvider = "Github";
+ private String mAuthCode = "c2820e39232088dca7d4";
+ private CoapDevice mMockDevice = mock(
CoapDevice.class);
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
- IResponse res = null;
- ServerSystem serverSystem = new ServerSystem();
- final CountDownLatch latch = new CountDownLatch(
+ private IResponse mResponse = null;
+ private CountDownLatch mLatch = new CountDownLatch(
1);
private TypeCastingManager<UserTable> mUserTableCastingManager = new TypeCastingManager<>();
private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
-
- @Mock
- ChannelHandlerContext ctx;
-
- @InjectMocks
- PersistentPacketReceiver receiver = serverSystem.new PersistentPacketReceiver();
+ private AccountResource mAccountResource = new AccountResource();
+ private GroupResource mGroupResource = new GroupResource();
@Before
public void setUp() throws Exception {
- // create log file
- Log.createfile();
- // add resource
- serverSystem.addResource(new AccountResource());
- serverSystem.addResource(new GroupResource());
MockitoAnnotations.initMocks(this);
- ChannelId channelId = mock(ChannelId.class);
- // inject mocked coapDevice into the api
- Channel channel = mock(Channel.class);
- Attribute<Device> attribute = mock(Attribute.class);
- Mockito.doReturn(channel).when(ctx).channel();
- Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
- Mockito.doReturn(mockDevice).when(attribute).get();
- Mockito.doReturn(channelId).when(channel).id();
- Mockito.doReturn(
- "0000000141f3edcfc2c3000000000001d0000000000000000000000000000000000000")
- .when(channelId).asLongText();
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public CoapResponse answer(InvocationOnMock invocation)
- throws Throwable {
- Object[] args = invocation.getArguments();
- CoapResponse resp = (CoapResponse) args[0];
- System.out.println(
- "\t----Exception responsestatus : " + resp.getStatus());
- res = resp;
- latch.countDown();
- return null;
- }
- }).when(channel).writeAndFlush(Mockito.any());
// callback mock
Mockito.doAnswer(new Answer<Object>() {
@Override
.println("\t----payload : " + resp.getPayloadString());
System.out
.println("\t----responsestatus : " + resp.getStatus());
- res = resp;
- return resp;
+ mResponse = resp;
+ mLatch.countDown();
+ return null;
}
- }).when(mockDevice).sendResponse(Mockito.anyObject());
- receiver.channelActive(ctx);
- }
-
- @After
- public void end() throws Exception {
- receiver.channelInactive(ctx);
+ }).when(mMockDevice).sendResponse(Mockito.anyObject());
}
@Test
public void testSignUpOnDefaultRequestReceived() throws Exception {
- System.out.println("\t--------------Sign Up Test------------");
- signUp(di, authProvider, authCode);
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
- assertTrue(hashmapCheck(res, "accesstoken"));
- assertTrue(hashmapCheck(res, "refreshtoken"));
- assertTrue(hashmapCheck(res, "tokentype"));
- assertTrue(hashmapCheck(res, "uid"));
+ getTestMethodName();
+ signUp(DEVICE_ID, mAuthProvider, mAuthCode);
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
+ assertTrue(hashmapCheck(mResponse, "accesstoken"));
+ assertTrue(hashmapCheck(mResponse, "refreshtoken"));
+ assertTrue(hashmapCheck(mResponse, "tokentype"));
+ assertTrue(hashmapCheck(mResponse, "uid"));
}
- @Test
+ @Test(expected = ServerException.InternalServerErrorException.class)
public void testSignUpwithWrongAuthCodeOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign Up with Wrong AuthCode Test------------");
+ getTestMethodName();
String wrongAuthCode = "5fc4fcf376f8d7087a3a";
- signUp(di, authProvider, wrongAuthCode);
- assertTrue(methodCheck(res, ResponseStatus.INTERNAL_SERVER_ERROR));
+ signUp(DEVICE_ID, mAuthProvider, wrongAuthCode);
}
- @Test
+ @Test(expected = ServerException.InternalServerErrorException.class)
+ public void testSignUpwithWrongAuthProviderOnDefaultRequestReceived()
+ throws Exception {
+ getTestMethodName();
+ signUp(DEVICE_ID, "wrongAuthProvider", mAuthCode);
+ }
+
+ @Test(expected = ServerException.PreconditionFailedException.class)
public void testSignUpNullAuthProviderOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign Up Null AuthProvider Test------------");
- signUp(di, null, authCode);
- assertTrue(methodCheck(res, ResponseStatus.PRECONDITION_FAILED));
+ getTestMethodName();
+ signUp(DEVICE_ID, null, mAuthCode);
}
- @Test
+ @Test(expected = ServerException.PreconditionFailedException.class)
public void testSignUpNullAuthCodeOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign Up with Null AuthCode Test------------");
- signUp(di, authProvider, null);
- assertTrue(methodCheck(res, ResponseStatus.PRECONDITION_FAILED));
+ getTestMethodName();
+ signUp(DEVICE_ID, mAuthProvider, null);
}
- @Test
+ @Test(expected = ServerException.PreconditionFailedException.class)
public void testSignUpNullDiOnDefaultRequestReceived() throws Exception {
- System.out.println(
- "\t--------------Sign Up with Null DeviceId Test------------");
- signUp(null, authProvider, authCode);
- assertTrue(methodCheck(res, ResponseStatus.PRECONDITION_FAILED));
+ getTestMethodName();
+ signUp(null, mAuthProvider, mAuthCode);
}
- @Test
+ @Test(expected = ServerException.BadRequestException.class)
public void testSignUpInvalidMethodOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign Up with Invalid Method (GET) Test------------");
- signUpInvalidMethod(di, authProvider, authCode);
- assertTrue(methodCheck(res, ResponseStatus.BAD_REQUEST));
+ getTestMethodName();
+ signUpInvalidMethod(DEVICE_ID, mAuthProvider, mAuthCode);
+ }
+
+ @Test
+ public void testGetUserInfoSearchOnDefaultRequestReceived()
+ throws Exception {
+ getTestMethodName();
+ String uuid = "u0001Search";
+ // register TokenInfo and UserInfo to the DB
+ HashMap<String, Object> tokenInfo = mTokenTableCastingManager
+ .convertObjectToMap(makeTokenTable(uuid));
+ HashMap<String, Object> userInfo = mUserTableCastingManager
+ .convertObjectToMap(makeUserTable(uuid));
+ AccountDBManager.getInstance()
+ .insertAndReplaceRecord(Constants.TOKEN_TABLE, tokenInfo);
+ AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
+ userInfo);
+ // request uuid using search criteria
+ getUserInfoSearch("search=userid:userId");
+ Cbor<HashMap<String, ArrayList<HashMap<String, Object>>>> cbor = new Cbor<>();
+ HashMap<String, ArrayList<HashMap<String, Object>>> payloadData = cbor
+ .parsePayloadFromCbor(mResponse.getPayload(), HashMap.class);
+ HashMap<String, Object> getUserInfo = ((ArrayList<HashMap<String, Object>>) payloadData
+ .get("ulist")).get(0);
+ assertTrue(getUserInfo.get("uid").equals(uuid));
+ }
+
+ private void getUserInfoSearch(String query) {
+ System.out.println("-----get User Info Search using query: " + query);
+ IRequest request = MessageBuilder.createRequest(RequestMethod.GET,
+ REGISTER_URI, query);
+ mAccountResource.onDefaultRequestReceived(mMockDevice, request);
}
@Test
public void testDeleteDeviceOnDefaultRequestReceived() throws Exception {
- System.out.println(
- "\t--------------Delete Device from all Groups Test------------");
+ getTestMethodName();
// register the token table and user table to the DB
String uuid = "u0001";
HashMap<String, Object> tokenInfo = mTokenTableCastingManager
AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
userInfo);
createDefaultGroup(uuid);
- shareDevice(ctx, di);
- deleteDevice(di);
- assertTrue(methodCheck(res, ResponseStatus.DELETED));
+ shareDevice(DEVICE_ID);
+ deleteDevice(DEVICE_ID);
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
}
- // @Test
+ @Test
public void testGetUserInfoUsingUuidOnDefaultRequestReceived()
throws Exception {
System.out.println(
AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
userInfo);
getUserInfoUsingUuid(uuid);
- assertTrue(methodCheck(res, ResponseStatus.CONTENT));
+ assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
}
- public void getUserInfoUsingUuid(String uuid) throws Exception {
+ private void getTestMethodName() {
+ StackTraceElement[] stacks = new Throwable().getStackTrace();
+ StackTraceElement currentStack = stacks[1];
+ System.out.println("\t---Test Name : " + currentStack.getMethodName());
+ }
+
+ private void getUserInfoUsingUuid(String uuid) throws Exception {
System.out.println("-----Get User Info : " + uuid);
IRequest request = null;
request = getUserInfoUsingUuidRequest(uuid);
- receiver.channelRead(ctx, request);
+ mAccountResource.onDefaultRequestReceived(mMockDevice, request);
}
- public IRequest getUserInfoUsingUuidRequest(String uuid) {
+ private IRequest getUserInfoUsingUuidRequest(String uuid) {
IRequest request = MessageBuilder.createRequest(RequestMethod.GET,
REGISTER_URI, "uid=" + uuid);
return request;
}
- public void createDefaultGroup(String uuid) throws Exception {
+ private void createDefaultGroup(String uuid) throws Exception {
System.out.println("-----Create Default Group");
IRequest request = null;
request = createDefaultGroupRequest(uuid);
- receiver.channelRead(ctx, request);
+ mGroupResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void deleteDevice(String di) throws Exception {
+ private void deleteDevice(String di) throws Exception {
System.out.println("-----Delete Device");
IRequest request = null;
request = deleteDeviceRequest(di);
- receiver.channelRead(ctx, request);
+ mAccountResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void signUp(String di, String authProvider, String authCode)
+ private void signUp(String di, String authProvider, String authCode)
throws Exception {
System.out.println("-----Sign Up");
IRequest request = null;
request = signUpRequest(di, authProvider, authCode);
- receiver.channelRead(ctx, request);
+ mAccountResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void signUpInvalidMethod(String di, String authProvider,
+ private void signUpInvalidMethod(String di, String authProvider,
String authCode) throws Exception {
System.out.println("-----Sign Up Invalid RequestMethod");
IRequest request = null;
request = signUpInvalidMethodRequest(di, authProvider, authCode);
- receiver.channelRead(ctx, request);
+ mAccountResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void shareDevice(ChannelHandlerContext ctx, String deviceId)
- throws Exception {
+ private void shareDevice(String deviceId) throws Exception {
System.out.println("-----Share Device");
IRequest request = null;
request = createShareDeviceRequest(deviceId);
- receiver.channelRead(ctx, request);
+ mGroupResource.onDefaultRequestReceived(mMockDevice, request);
}
- public IRequest deleteDeviceRequest(String deviceId) {
+ private IRequest deleteDeviceRequest(String deviceId) {
IRequest request = MessageBuilder.createRequest(RequestMethod.DELETE,
REGISTER_URI, "di=" + deviceId + ";uid=u0001");
return request;
}
- public IRequest createDefaultGroupRequest(String uuid) {
+ private IRequest createDefaultGroupRequest(String uuid) {
IRequest request = null;
HashMap<String, String> payloadData = new HashMap<String, String>();
payloadData.put("gmid", uuid);
payloadData.put("gtype", "Private");
- Cbor<HashMap<String, String>> cbor = new Cbor<HashMap<String, String>>();
request = MessageBuilder.createRequest(RequestMethod.POST, GROUP_URI,
null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public IRequest createShareDeviceRequest(String deviceId) {
+ private IRequest createShareDeviceRequest(String deviceId) {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
ArrayList<String> diList = new ArrayList<>();
diList.add(deviceId);
payloadData.put("dilist", diList);
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
request = MessageBuilder.createRequest(RequestMethod.POST,
GROUP_URI + "/" + "u0001", null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public IRequest signUpRequest(String deviceId, String authProvider,
+ private IRequest signUpRequest(String deviceId, String authProvider,
String authCode) {
IRequest request = null;
HashMap<String, String> payloadData = new HashMap<String, String>();
payloadData.put("authcode", authCode);
payloadData.put("authprovider", authProvider);
payloadData.put("di", deviceId);
- Cbor<HashMap<String, String>> cbor = new Cbor<HashMap<String, String>>();
request = MessageBuilder.createRequest(RequestMethod.POST, REGISTER_URI,
null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public IRequest signUpInvalidMethodRequest(String deviceId,
+ private IRequest signUpInvalidMethodRequest(String deviceId,
String authProvider, String authCode) {
IRequest request = null;
HashMap<String, String> payloadData = new HashMap<String, String>();
payloadData.put("authcode", authCode);
payloadData.put("authprovider", authProvider);
payloadData.put("di", deviceId);
- Cbor<HashMap<String, String>> cbor = new Cbor<HashMap<String, String>>();
request = MessageBuilder.createRequest(RequestMethod.GET, REGISTER_URI,
null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public boolean hashmapCheck(IResponse response, String propertyName) {
+ private boolean hashmapCheck(IResponse response, String propertyName) {
HashMap<String, Object> payloadData = mCbor
.parsePayloadFromCbor(response.getPayload(), HashMap.class);
if (payloadData.containsKey(propertyName))
return false;
}
- public boolean methodCheck(IResponse response,
+ private boolean methodCheck(IResponse response,
ResponseStatus responseStatus) {
if (responseStatus == response.getStatus())
return true;
private TokenTable makeTokenTable(String uuid) {
TokenTable tokenInfo = new TokenTable();
tokenInfo.setUuid(uuid);
- tokenInfo.setDid(di);
+ tokenInfo.setDid(DEVICE_ID);
tokenInfo.setAccesstoken("at0001");
tokenInfo.setRefreshtoken("rt0001");
- tokenInfo.setProvider(authProvider);
+ tokenInfo.setProvider(mAuthProvider);
tokenInfo.setExpiredtime(-1);
Date currentTime = new Date();
DateFormat transFormat = new SimpleDateFormat("yyyyMMddkkmm");
private UserTable makeUserTable(String uuid) {
UserTable userInfo = new UserTable();
userInfo.setUuid(uuid);
- userInfo.setProvider(authProvider);
+ userInfo.setProvider(mAuthProvider);
userInfo.setUserid("userId");
return userInfo;
}
package org.iotivity.cloud.accountserver.resources.account.session;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
+import org.iotivity.cloud.accountserver.db.MongoDB;
import org.iotivity.cloud.accountserver.db.TokenTable;
import org.iotivity.cloud.accountserver.db.UserTable;
import org.iotivity.cloud.accountserver.util.TypeCastingManager;
-import org.iotivity.cloud.base.ServerSystem;
-import org.iotivity.cloud.base.ServerSystem.PersistentPacketReceiver;
import org.iotivity.cloud.base.device.CoapDevice;
-import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelId;
-import io.netty.util.Attribute;
-
public class SessionResourceTest {
- private final String DEFAULT_AUTH_LOGIN = "/.well-known/ocf/account/session";
- private final String DEFAULT_AUTH_LOGOUT = "/.well-known/ocf/account/session";
- private String di = "d0001";
- private String accessToken = "5f5536c896da7dd437316585b86ef9dd03441c40";
- private String refreshToken = "rt0001";
+ private static final String DEFAULT_AUTH_LOGIN = "/.well-known/ocf/account/session";
+ private static final String DEFAULT_AUTH_LOGOUT = "/.well-known/ocf/account/session";
+ private static final String DEVICE_ID = "d0001";
+ private static final String ACCESS_TOKEN = "5f5536c896da7dd437316585b86ef9dd03441c40";
+ private static final String REFRESH_TOKEN = "rt0001";
+ private static final String USER_UUID = "bc38f243-aab5-44d3-8eb9-4a54ebbaf359";
+ private static final String AUTH_PROVIDER = "Github";
private TypeCastingManager<UserTable> mUserTableCastingManager = new TypeCastingManager<>();
private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
- ServerSystem serverSystem = new ServerSystem();
- final CountDownLatch latch = new CountDownLatch(
+ private CountDownLatch mLatch = new CountDownLatch(
1);
- private String uuid = "bc38f243-aab5-44d3-8eb9-4a54ebbaf359";
- private String authProvider = "github";
- private CoapDevice mockDevice = Mockito
+ private CoapDevice mMockDevice = Mockito
.mock(CoapDevice.class);
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
- IResponse res = null;
-
- @Mock
- ChannelHandlerContext ctx;
-
- @InjectMocks
- PersistentPacketReceiver receiver = serverSystem.new PersistentPacketReceiver();
+ private IResponse mResponse = null;
+ private SessionResource mSessionResource = new SessionResource();
@Before
public void setUp() throws Exception {
- // create log file
- Log.createfile();
- // add resource
- serverSystem.addResource(new SessionResource());
MockitoAnnotations.initMocks(this);
- ChannelId channelId = mock(ChannelId.class);
- // inject mocked coapDevice into the api
- Channel channel = mock(Channel.class);
- Attribute<Device> attribute = mock(Attribute.class);
- Mockito.doReturn(channel).when(ctx).channel();
- Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
- Mockito.doReturn(mockDevice).when(attribute).get();
- Mockito.doReturn(channelId).when(channel).id();
- Mockito.doReturn(
- "0000000141f3edcfc2c3000000000001d0000000000000000000000000000000000000")
- .when(channelId).asLongText();
+ // reset data base
+ resetDB();
// register the token table and user table to the DB
HashMap<String, Object> tokenInfo = mTokenTableCastingManager
.convertObjectToMap(makeTokenTable());
CoapResponse resp = (CoapResponse) args[0];
System.out.println(
"\t----------payload : " + resp.getPayloadString());
- System.out.println("\t---------method : " + resp.getMethod());
- res = resp;
- latch.countDown();
- return resp;
- }
- }).when(mockDevice).sendResponse(Mockito.anyObject());
- // exception handler mock
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public CoapResponse answer(InvocationOnMock invocation)
- throws Throwable {
- Object[] args = invocation.getArguments();
- CoapResponse resp = (CoapResponse) args[0];
- System.out.println("\t----exception response status : "
- + resp.getStatus());
- res = resp;
- latch.countDown();
+ System.out.println("\t---------method : " + resp.getStatus());
+ mResponse = resp;
+ mLatch.countDown();
return null;
}
- }).when(channel).writeAndFlush(Mockito.any());
- }
-
- @After
- public void endTest() {
- AccountDBManager.getInstance().deleteRecord(Constants.TOKEN_TABLE,
- mTokenTableCastingManager.convertObjectToMap(makeTokenTable()));
- AccountDBManager.getInstance().deleteRecord(Constants.USER_TABLE,
- mUserTableCastingManager.convertObjectToMap(makeUserTable()));
+ }).when(mMockDevice).sendResponse(Mockito.anyObject());
}
@Test
public void testSignInOnDefaultRequestReceived() throws Exception {
- System.out.println("\t--------------Sign In Test------------");
- SignIn(di, accessToken);
- assertTrue(hashmapCheck(res, "expiresin"));
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
+ getTestMethodName();
+ SignIn(DEVICE_ID, ACCESS_TOKEN);
+ assertTrue(hashmapCheck(mResponse, "expiresin"));
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
}
- @Test
+ @Test(expected = ServerException.UnAuthorizedException.class)
+ public void testSignInExpiredTokenOnDefaultRequestReceived()
+ throws Exception {
+ getTestMethodName();
+ TokenTable tokenTable = makeTokenTable();
+ tokenTable.setExpiredtime(0);
+ HashMap<String, Object> tokenInfo = mTokenTableCastingManager
+ .convertObjectToMap(tokenTable);
+ Thread.sleep(500);
+ AccountDBManager.getInstance()
+ .insertAndReplaceRecord(Constants.TOKEN_TABLE, tokenInfo);
+ SignIn(DEVICE_ID, ACCESS_TOKEN);
+ }
+
+ @Test(expected = ServerException.BadRequestException.class)
public void testSignInWithInvalidMethodOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign In With Invalid RequestMethod Test------------");
- SignInWithInvalidMethod(di, accessToken);
- assertTrue(methodCheck(res, ResponseStatus.BAD_REQUEST));
+ getTestMethodName();
+ SignInWithInvalidMethod(DEVICE_ID, ACCESS_TOKEN);
}
- @Test
+ @Test(expected = ServerException.UnAuthorizedException.class)
public void testWrongAccessTokenSignInOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Wrong AccessToken Sign In Test------------");
+ getTestMethodName();
String accessTokenNotStored = "5689c70ffa245effc563017fee36d250";
// sign in request
- SignIn(di, accessTokenNotStored);
- assertTrue(methodCheck(res, ResponseStatus.UNAUTHORIZED));
+ SignIn(DEVICE_ID, accessTokenNotStored);
}
- @Test
+ @Test(expected = ServerException.UnAuthorizedException.class)
public void testInvalidDeviceIdSignInOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Invalid DeviceId Sign In Test------------");
+ getTestMethodName();
String diNotStored = "F371C481-38E6-4D47-8320-7688D8A5B58C";
- SignIn(diNotStored, accessToken);
- assertTrue(methodCheck(res, ResponseStatus.UNAUTHORIZED));
+ SignIn(diNotStored, ACCESS_TOKEN);
}
@Test
public void testSignOutOnDefaultRequestReceived() throws Exception {
- System.out.println("\t--------------Sign Out Test------------");
- SignOut(di, accessToken);
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
+ getTestMethodName();
+ SignOut(DEVICE_ID, ACCESS_TOKEN);
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
}
- @Test
+ public void getTestMethodName() {
+ StackTraceElement[] stacks = new Throwable().getStackTrace();
+ StackTraceElement currentStack = stacks[1];
+ System.out.println("\t---Test Name : " + currentStack.getMethodName());
+ }
+
+ @Test(expected = ServerException.BadRequestException.class)
public void testSignInWithNullPayloadOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign In With Null Payload Test------------");
+ getTestMethodName();
SignInWithNullPayload();
- assertTrue(methodCheck(res, ResponseStatus.BAD_REQUEST));
}
- @Test
+ @Test(expected = ServerException.BadRequestException.class)
public void testSignOutWithNullPayloadOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign Out With Null Payload Test------------");
- // sign out request
+ getTestMethodName();
SignOutWithNullPayload();
- assertTrue(methodCheck(res, ResponseStatus.BAD_REQUEST));
}
- @Test
+ @Test(expected = ServerException.PreconditionFailedException.class)
public void testSignInWithBlankHashMapPayloadOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign In With Blank HashMap Payload Test------------");
+ getTestMethodName();
SignInWithBlankHashMapPayload();
- assertTrue(methodCheck(res, ResponseStatus.PRECONDITION_FAILED));
}
- @Test
+ @Test(expected = ServerException.PreconditionFailedException.class)
public void testSignOutWithBlankHashMapPayloadOnDefaultRequestReceived()
throws Exception {
- System.out.println(
- "\t--------------Sign Out With Blank HashMap Test------------");
+ getTestMethodName();
SignOutWithBlankHashMapPayload();
- assertTrue(methodCheck(res, ResponseStatus.PRECONDITION_FAILED));
}
- public void SignInWithInvalidMethod(String di, String accessToken)
+ private void SignInWithInvalidMethod(String di, String accessToken)
throws Exception {
System.out.println("-----Sign In With Invalid Method (GET)");
IRequest request = null;
request = SignInWithInvalidMethodRequest(di, accessToken);
- receiver.channelRead(ctx, request);
+ mSessionResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void SignIn(String di, String accessToken) throws Exception {
+ private void SignIn(String di, String accessToken) throws Exception {
System.out.println("-----Sign In");
IRequest request = null;
request = SignInRequest(di, accessToken);
- receiver.channelRead(ctx, request);
+ mSessionResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void SignInWithBlankHashMapPayload() throws Exception {
+ private void SignInWithBlankHashMapPayload() throws Exception {
System.out.println("-----Sign In With Blank Hashmap Payload");
IRequest request = null;
request = SignInBlankHashmapPayloadRequest();
- receiver.channelRead(ctx, request);
+ mSessionResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void SignInWithNullPayload() throws Exception {
+ private void SignInWithNullPayload() throws Exception {
System.out.println("-----Sign In With Null Payload");
IRequest request = null;
request = SignInNullPayloadRequest();
- receiver.channelRead(ctx, request);
+ mSessionResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void SignOut(String di, String accessToken) throws Exception {
+ private void SignOut(String di, String accessToken) throws Exception {
System.out.println("-----Sign Out");
IRequest request = null;
request = SignOutRequest(di, accessToken);
- receiver.channelRead(ctx, request);
+ mSessionResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void SignOutWithBlankHashMapPayload() throws Exception {
+ private void SignOutWithBlankHashMapPayload() throws Exception {
System.out.println("-----Sign Out With Blank Hashmap Payload");
IRequest request = null;
request = SignOutBlankHashmapPayloadRequest();
- receiver.channelRead(ctx, request);
+ mSessionResource.onDefaultRequestReceived(mMockDevice, request);
}
- public void SignOutWithNullPayload() throws Exception {
+ private void SignOutWithNullPayload() throws Exception {
System.out.println("-----Sign Out With Null Payload");
IRequest request = null;
request = SignOutNullPayloadRequest();
- receiver.channelRead(ctx, request);
+ mSessionResource.onDefaultRequestReceived(mMockDevice, request);
}
- public IRequest SignInNullPayloadRequest() {
+ private IRequest SignInNullPayloadRequest() {
IRequest request = null;
request = MessageBuilder.createRequest(RequestMethod.POST,
DEFAULT_AUTH_LOGIN, null);
return request;
}
- public IRequest SignInBlankHashmapPayloadRequest() {
+ private IRequest SignInBlankHashmapPayloadRequest() {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
request = MessageBuilder.createRequest(RequestMethod.POST,
DEFAULT_AUTH_LOGIN, null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public IRequest SignOutNullPayloadRequest() {
+ private IRequest SignOutNullPayloadRequest() {
IRequest request = null;
request = MessageBuilder.createRequest(RequestMethod.POST,
DEFAULT_AUTH_LOGOUT, null);
return request;
}
- public IRequest SignOutBlankHashmapPayloadRequest() {
+ private IRequest SignOutBlankHashmapPayloadRequest() {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
request = MessageBuilder.createRequest(RequestMethod.POST,
DEFAULT_AUTH_LOGOUT, null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public IRequest SignInWithInvalidMethodRequest(String deviceId,
+ private IRequest SignInWithInvalidMethodRequest(String deviceId,
String accessToken) {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
payloadData.put("accesstoken", accessToken);
payloadData.put("status", true);
payloadData.put("di", deviceId);
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
request = MessageBuilder.createRequest(RequestMethod.GET,
DEFAULT_AUTH_LOGIN, null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public IRequest SignInRequest(String deviceId, String accessToken) {
+ private IRequest SignInRequest(String deviceId, String accessToken) {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
payloadData.put("accesstoken", accessToken);
payloadData.put("login", true);
payloadData.put("di", deviceId);
- payloadData.put("uid", uuid);
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
+ payloadData.put("uid", USER_UUID);
request = MessageBuilder.createRequest(RequestMethod.POST,
DEFAULT_AUTH_LOGIN, null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public IRequest SignOutRequest(String deviceId, String accessToken) {
+ private IRequest SignOutRequest(String deviceId, String accessToken) {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
payloadData.put("accesstoken", accessToken);
payloadData.put("login", false);
payloadData.put("di", deviceId);
- payloadData.put("uid", uuid);
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
+ payloadData.put("uid", USER_UUID);
request = MessageBuilder.createRequest(RequestMethod.POST,
DEFAULT_AUTH_LOGOUT, null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public boolean hashmapCheck(IResponse response, String propertyName) {
+ private boolean hashmapCheck(IResponse response, String propertyName) {
HashMap<String, Object> payloadData = mCbor
.parsePayloadFromCbor(response.getPayload(), HashMap.class);
if (payloadData.get(propertyName) != null)
return false;
}
- public boolean methodCheck(IResponse response,
+ private boolean methodCheck(IResponse response,
ResponseStatus responseStatus) {
if (responseStatus == response.getStatus())
return true;
private TokenTable makeTokenTable() {
TokenTable tokenInfo = new TokenTable();
- tokenInfo.setUuid(uuid);
- tokenInfo.setDid(di);
- tokenInfo.setAccesstoken(accessToken);
- tokenInfo.setRefreshtoken(refreshToken);
- tokenInfo.setProvider(authProvider);
+ tokenInfo.setUuid(USER_UUID);
+ tokenInfo.setDid(DEVICE_ID);
+ tokenInfo.setAccesstoken(ACCESS_TOKEN);
+ tokenInfo.setRefreshtoken(REFRESH_TOKEN);
+ tokenInfo.setProvider(AUTH_PROVIDER);
tokenInfo.setExpiredtime(-1);
Date currentTime = new Date();
DateFormat transFormat = new SimpleDateFormat("yyyyMMddkkmm");
private UserTable makeUserTable() {
UserTable userInfo = new UserTable();
- userInfo.setUuid(uuid);
- userInfo.setProvider(authProvider);
+ userInfo.setUuid(USER_UUID);
+ userInfo.setProvider(AUTH_PROVIDER);
userInfo.setUserid("userId");
return userInfo;
}
+
+ private void resetDB() throws Exception {
+ MongoDB mongoDB = new MongoDB(Constants.DB_NAME);
+ mongoDB.deleteTable(Constants.GROUP_TABLE);
+ mongoDB.createTable(Constants.GROUP_TABLE);
+ mongoDB.deleteTable(Constants.USER_TABLE);
+ mongoDB.createTable(Constants.USER_TABLE);
+ mongoDB.deleteTable(Constants.TOKEN_TABLE);
+ mongoDB.createTable(Constants.TOKEN_TABLE);
+ }
}
--- /dev/null
+package org.iotivity.cloud.accountserver.resources.account.tokenrefresh;
+
+import static org.mockito.Mockito.mock;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.db.AccountDBManager;
+import org.iotivity.cloud.accountserver.db.TokenTable;
+import org.iotivity.cloud.accountserver.db.UserTable;
+import org.iotivity.cloud.accountserver.util.TypeCastingManager;
+import org.iotivity.cloud.base.device.CoapDevice;
+import org.iotivity.cloud.base.exception.ServerException;
+import org.iotivity.cloud.base.protocols.IRequest;
+import org.iotivity.cloud.base.protocols.MessageBuilder;
+import org.iotivity.cloud.base.protocols.coap.CoapResponse;
+import org.iotivity.cloud.base.protocols.enums.ContentFormat;
+import org.iotivity.cloud.base.protocols.enums.RequestMethod;
+import org.iotivity.cloud.util.Cbor;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+public class TokenRefreshResourceTest {
+ private static final String REFRESH_TOKEN_URI = "/.well-known/ocf/account/tokenrefresh";
+ private static final String DEVICE_ID = "B371C481-38E6-4D47-8320-7688D8A5B58C";
+ private String mAuthProvider = "Samsung";
+ private String mRefreshToken = "rt0001";
+ private String mUuid = "u0001";
+ private String mUserId = "userId";
+ private Cbor<HashMap<String, String>> mCbor = new Cbor<HashMap<String, String>>();
+ private CoapDevice mockDevice = mock(
+ CoapDevice.class);
+ private TypeCastingManager<UserTable> mUserTableCastingManager = new TypeCastingManager<>();
+ private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
+ private TokenRefreshResource mTokenRefreshResource = new TokenRefreshResource();
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ // callback mock
+ Mockito.doAnswer(new Answer<Object>() {
+ @Override
+ public CoapResponse answer(InvocationOnMock invocation)
+ throws Throwable {
+ Object[] args = invocation.getArguments();
+ CoapResponse resp = (CoapResponse) args[0];
+ System.out
+ .println("\t----payload : " + resp.getPayloadString());
+ System.out
+ .println("\t----responsestatus : " + resp.getStatus());
+ return resp;
+ }
+ }).when(mockDevice).sendResponse(Mockito.anyObject());
+ }
+
+ @Test(expected = ServerException.NotFoundException.class)
+ public void testRefreshTokenonRequestReceivedWrongRefreshToken()
+ throws Exception {
+ String uuid = this.mUuid + "WrongRefreshTokenCase";
+ RegisterTokenInfo(uuid, mUserId, mAuthProvider, mRefreshToken);
+ TokenRefresh(RequestMethod.POST, mockDevice, uuid, DEVICE_ID,
+ mRefreshToken + "NotExist");
+ }
+
+ @Test(expected = ServerException.BadRequestException.class)
+ public void testRefreshTokenonRequestReceivedInvalidMethod()
+ throws Exception {
+ String uuid = this.mUuid + "InvalidRequestMethod (GET)";
+ RegisterTokenInfo(uuid, mUserId, mAuthProvider, mRefreshToken);
+ TokenRefresh(RequestMethod.GET, mockDevice, uuid, DEVICE_ID,
+ mRefreshToken + "InvalidMethod");
+ }
+
+ @Test(expected = ServerException.PreconditionFailedException.class)
+ public void testRefreshTokenonRequestReceivedNullUuid() throws Exception {
+ String uuid = this.mUuid + "NullUuid";
+ RegisterTokenInfo(uuid, mUserId, mAuthProvider, mRefreshToken);
+ TokenRefresh(RequestMethod.POST, mockDevice, null, DEVICE_ID,
+ mRefreshToken + "InvalidMethod");
+ }
+
+ @Test(expected = ServerException.PreconditionFailedException.class)
+ public void testRefreshTokenonRequestReceivedNullDi() throws Exception {
+ String uuid = this.mUuid + "NullDi";
+ RegisterTokenInfo(uuid, mUserId, mAuthProvider, mRefreshToken);
+ TokenRefresh(RequestMethod.POST, mockDevice, uuid, null,
+ mRefreshToken + "InvalidMethod");
+ }
+
+ @Test(expected = ServerException.PreconditionFailedException.class)
+ public void testRefreshTokenonRequestReceivedNullRefreshToken()
+ throws Exception {
+ String uuid = this.mUuid + "NullRefreshToken";
+ RegisterTokenInfo(uuid, mUserId, mAuthProvider, mRefreshToken);
+ TokenRefresh(RequestMethod.POST, mockDevice, uuid, DEVICE_ID, null);
+ }
+
+ public void TokenRefresh(RequestMethod method, CoapDevice device,
+ String uuid, String di, String refreshToken) throws Exception {
+ System.out.println(
+ "-----Token Refresh using refreshtoken : " + refreshToken);
+ IRequest request = null;
+ request = RefreshTokenRequest(method, uuid, di, refreshToken);
+ mTokenRefreshResource.onDefaultRequestReceived(device, request);
+ }
+
+ public IRequest RefreshTokenRequest(RequestMethod method, String uuid,
+ String deviceId, String refreshToken) {
+ IRequest request = null;
+ HashMap<String, String> payloadData = new HashMap<String, String>();
+ payloadData.put("uid", uuid);
+ payloadData.put("di", deviceId);
+ payloadData.put("granttype", "refresh_token");
+ payloadData.put("refreshtoken", refreshToken);
+ request = MessageBuilder.createRequest(method, REFRESH_TOKEN_URI, null,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(payloadData));
+ return request;
+ }
+
+ public void RegisterTokenInfo(String uuid, String userId,
+ String accessToken, String refreshToken) {
+ HashMap<String, Object> tokenInfo = mTokenTableCastingManager
+ .convertObjectToMap(
+ makeTokenTable(uuid, accessToken, refreshToken));
+ HashMap<String, Object> userInfo = mUserTableCastingManager
+ .convertObjectToMap(makeUserTable(uuid, userId));
+ AccountDBManager.getInstance()
+ .insertAndReplaceRecord(Constants.TOKEN_TABLE, tokenInfo);
+ AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
+ userInfo);
+ }
+
+ private TokenTable makeTokenTable(String uuid, String accessToken,
+ String refreshToken) {
+ TokenTable tokenInfo = new TokenTable();
+ tokenInfo.setUuid(uuid);
+ tokenInfo.setDid(DEVICE_ID);
+ tokenInfo.setAccesstoken(accessToken);
+ tokenInfo.setRefreshtoken(refreshToken);
+ tokenInfo.setProvider(mAuthProvider);
+ tokenInfo.setExpiredtime(-1);
+ Date currentTime = new Date();
+ DateFormat transFormat = new SimpleDateFormat("yyyyMMddkkmm");
+ tokenInfo.setIssuedtime(transFormat.format(currentTime));
+ return tokenInfo;
+ }
+
+ private UserTable makeUserTable(String uuid, String userId) {
+ UserTable userInfo = new UserTable();
+ userInfo.setUuid(uuid);
+ userInfo.setProvider(mAuthProvider);
+ userInfo.setUserid(userId);
+ return userInfo;
+ }
+}
*/
package org.iotivity.cloud.accountserver.resources.acl.group;
+import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
-import org.iotivity.cloud.accountserver.db.TokenTable;
-import org.iotivity.cloud.accountserver.db.UserTable;
-import org.iotivity.cloud.accountserver.util.TypeCastingManager;
-import org.iotivity.cloud.base.ServerSystem;
-import org.iotivity.cloud.base.ServerSystem.PersistentPacketReceiver;
+import org.iotivity.cloud.accountserver.Constants;
+import org.iotivity.cloud.accountserver.db.MongoDB;
import org.iotivity.cloud.base.device.CoapDevice;
-import org.iotivity.cloud.base.device.Device;
+import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Cbor;
-import org.iotivity.cloud.util.Log;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelId;
-import io.netty.util.Attribute;
-
public class GroupResourceTest {
- private static final String GROUP_URI = "/.well-known/ocf/acl/group";
- private String di = "d0001";
- private String accessToken = "5f5536c896da7dd437316585b86ef9dd03441c40";
- private String refreshToken = "rt0001";
- private String gid = null;
- private TypeCastingManager<UserTable> mUserTableCastingManager = new TypeCastingManager<>();
- private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
- ServerSystem serverSystem = new ServerSystem();
- final CountDownLatch latch = new CountDownLatch(
+ private static final String GROUP_URI = "/.well-known/ocf/acl/group";
+ private final String mUserUuid = "bc38f243-aab5-44d3-8eb9-4a54ebbaf359";
+ private String mGroupId = null;
+ final CountDownLatch mLatch = new CountDownLatch(
1);
- private String uuid = "bc38f243-aab5-44d3-8eb9-4a54ebbaf359";
- private String authProvider = "github";
- private CoapDevice mockDevice = Mockito
+ private CoapDevice mMockDevice = Mockito
.mock(CoapDevice.class);
- private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
- IResponse res = null;
- IResponse resObserver = null;
-
- @Mock
- ChannelHandlerContext ctx;
-
- @InjectMocks
- PersistentPacketReceiver receiver = serverSystem.new PersistentPacketReceiver();
+ private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
+ private IResponse mResponse = null;
+ private IResponse mResponseObserver = null;
+ private GroupResource mGroupResource = new GroupResource();
@Before
public void setUp() throws Exception {
- // create log file
- Log.createfile();
- // add resource
- serverSystem.addResource(new GroupResource());
MockitoAnnotations.initMocks(this);
- ChannelId channelId = mock(ChannelId.class);
- // inject mocked coapDevice into the api
- Channel channel = mock(Channel.class);
- Attribute<Device> attribute = mock(Attribute.class);
- Mockito.doReturn(channel).when(ctx).channel();
- Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
- Mockito.doReturn(mockDevice).when(attribute).get();
- Mockito.doReturn(channelId).when(channel).id();
- Mockito.doReturn(
- "0000000141f3edcfc2c3000000000001d0000000000000000000000000000000000000")
- .when(channelId).asLongText();
+ // reset data base
+ resetDB();
Mockito.doAnswer(new Answer<Object>() {
@Override
public CoapResponse answer(InvocationOnMock invocation)
System.out.println(
"\t----------payload : " + resp.getPayloadString());
System.out.println("\t---------method : " + resp.getStatus());
- res = resp;
- HashMap<String, Object> payloadData = mCbor
- .parsePayloadFromCbor(resp.getPayload(), HashMap.class);
- if (payloadData.containsKey("gid")) {
- gid = (String) payloadData.get("gid");
+ mResponse = resp;
+ if (mGroupId == null) {
+ HashMap<String, Object> payloadData = mCbor
+ .parsePayloadFromCbor(resp.getPayload(),
+ HashMap.class);
+ if (payloadData.containsKey("gid")) {
+ mGroupId = (String) payloadData.get("gid");
+ }
}
- latch.countDown();
- return resp;
+ mLatch.countDown();
+ return null;
}
- }).when(mockDevice).sendResponse(Mockito.anyObject());
+ }).when(mMockDevice).sendResponse(Mockito.anyObject());
}
@Test
public void testCreateGroup() throws Exception {
- System.out.println("\t--------------Create Group Test------------");
- createGroup(ctx, uuid + "create", "Public");
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
- assertTrue(hashmapCheck(res, "gid"));
-
+ getTestMethodName();
+ createGroup(mMockDevice, mUserUuid + "create", "Public");
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
+ assertTrue(hashmapCheck(mResponse, "gid"));
+ assertTrue(mLatch.await(2L, SECONDS));
}
@Test
public void testFindMyGroup() throws Exception {
- System.out.println("\t--------------Find My Group Test------------");
- String uuid = this.uuid + "find";
- createGroup(ctx, uuid, "Public");
- findGroup(ctx, uuid);
- assertTrue(methodCheck(res, ResponseStatus.CONTENT));
- assertTrue(hashmapCheck(res, "gidlist"));
+ getTestMethodName();
+ String uuid = this.mUserUuid + "find";
+ createGroup(mMockDevice, uuid, "Public");
+ findGroup(mMockDevice, uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
+ assertTrue(hashmapCheck(mResponse, "gidlist"));
+ assertTrue(mLatch.await(2L, SECONDS));
+ }
+
+ @Test(expected = ServerException.BadRequestException.class)
+ public void testCreateGroupNotSupportedType() throws Exception {
+ getTestMethodName();
+ String uuid = this.mUserUuid + "delete";
+ createGroup(mMockDevice, uuid, "NotSupported");
+ deleteGroup(mMockDevice, uuid);
}
@Test
public void testDeleteGroup() throws Exception {
- System.out.println("\t--------------Delete Group Test------------");
- String uuid = this.uuid + "delete";
- createGroup(ctx, uuid, "Public");
- deleteGroup(ctx, uuid);
- System.out.println("\t--------res : " + res.getStatus());
- assertTrue(methodCheck(res, ResponseStatus.DELETED));
+ getTestMethodName();
+ String uuid = this.mUserUuid + "delete";
+ createGroup(mMockDevice, uuid, "Public");
+ deleteGroup(mMockDevice, uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
+ assertTrue(mLatch.await(2L, SECONDS));
+ }
+
+ @Test(expected = ServerException.PreconditionFailedException.class)
+ public void testDeleteGroupWithoutGid() throws Exception {
+ getTestMethodName();
+ String uuid = this.mUserUuid + "delete";
+ createGroup(mMockDevice, uuid, "Public");
+ deleteGroupWithoutGid(mMockDevice, uuid);
+ }
+
+ @Test
+ public void testAddDeviceAndUserToGroup() throws Exception {
+ getTestMethodName();
+ String uuid = this.mUserUuid + "AddDeviceAndUser";
+ createGroup(mMockDevice, uuid, "Public");
+ ArrayList<String> midList = new ArrayList<>();
+ midList.add("member0001");
+ midList.add("member0002");
+ ArrayList<String> diList = new ArrayList<>();
+ diList.add("device0001");
+ diList.add("device0002");
+ addDeviceAndUser(mMockDevice, midList, diList);
+ }
+
+ @Test
+ public void testDeleteDeviceAndUserToGroup() throws Exception {
+ getTestMethodName();
+ String uuid = this.mUserUuid + "AddDeviceAndUser";
+ createGroup(mMockDevice, uuid, "Public");
+ ArrayList<String> midList = new ArrayList<>();
+ midList.add("member0001");
+ midList.add("member0002");
+ ArrayList<String> diList = new ArrayList<>();
+ diList.add("device0001");
+ diList.add("device0002");
+ addDeviceAndUser(mMockDevice, midList, diList);
+ deleteDeviceAndUser(mMockDevice, midList, diList);
+ }
+
+ @Test(expected = ServerException.BadRequestException.class)
+ public void testDeleteGroupInvalidGmid() throws Exception {
+ getTestMethodName();
+ String uuid = this.mUserUuid + "delete";
+ createGroup(mMockDevice, uuid, "Public");
+ deleteGroup(mMockDevice, uuid + "invlidGmid");
}
@Test
public void testJoinToinvitedGroup() throws Exception {
- System.out.println(
- "\t--------------Join to invited group Test------------");
- String uuid = this.uuid + "join";
- createGroup(ctx, uuid, "Public");
- joinGroup(ctx, "u0002");
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
+ getTestMethodName();
+ String uuid = this.mUserUuid + "join";
+ createGroup(mMockDevice, uuid, "Public");
+ joinGroup(mMockDevice, "u0002");
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
+ assertTrue(mLatch.await(2L, SECONDS));
}
@Test
public void testObserveGroup() throws Exception {
- System.out.println("\t--------------Observe Group Test------------");
- String uuid = this.uuid + "obs";
- createGroup(ctx, uuid, "Public");
- observeGroup(ctx, uuid);
- assertTrue(methodCheck(res, ResponseStatus.CONTENT));
- assertTrue(hashmapCheck(res, "gid"));
- assertTrue(hashmapCheck(res, "gmid"));
- assertTrue(hashmapCheck(res, "midlist"));
- assertTrue(hashmapCheck(res, "dilist"));
+ getTestMethodName();
+ String uuid = this.mUserUuid + "obs";
+ createGroup(mMockDevice, uuid, "Public");
+ observeGroup(mMockDevice, uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
+ assertTrue(hashmapCheck(mResponse, "gid"));
+ assertTrue(hashmapCheck(mResponse, "gmid"));
+ assertTrue(hashmapCheck(mResponse, "midlist"));
+ assertTrue(hashmapCheck(mResponse, "dilist"));
+ assertTrue(mLatch.await(2L, SECONDS));
+ }
+
+ @Test
+ public void testObserveDeregisterGroup() throws Exception {
+ getTestMethodName();
+ String uuid = this.mUserUuid + "obs";
+ createGroup(mMockDevice, uuid, "Public");
+ observeGroup(mMockDevice, uuid);
+ observeDeregisterGroup(mMockDevice, uuid);
+ assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
}
@Test
public void testShareDeviceIntoGroup() throws Exception {
- System.out.println(
- "\t--------------Share device into group Test------------");
- String uuid = this.uuid + "share";
- createGroup(ctx, uuid, "Public");
- shareDevice(ctx, "d0002");
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
+ getTestMethodName();
+ String uuid = this.mUserUuid + "share";
+ createGroup(mMockDevice, uuid, "Public");
+ shareDevice(mMockDevice, "d0002");
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
+ assertTrue(mLatch.await(2L, SECONDS));
}
@Test
public void testShareDeviceNotification() throws Exception {
- System.out.println(
- "\t--------------Share device Notification into group Test------------");
- String uuid = this.uuid + "share";
+ getTestMethodName();
+ String uuid = this.mUserUuid + "share";
String uuidGuest = "u0002guest";
- ChannelHandlerContext ctxGuest = mock(ChannelHandlerContext.class);
- ChannelId channelIdGuest = mock(ChannelId.class);
CoapDevice mockDeviceGuest = mock(CoapDevice.class);
- // inject mocked coapDevice into the api
- Channel channelGuest = mock(Channel.class);
- Attribute<Device> attributeGuest = mock(Attribute.class);
- Mockito.doReturn(channelGuest).when(ctxGuest).channel();
- Mockito.doReturn(attributeGuest).when(channelGuest).attr(Mockito.any());
- Mockito.doReturn(mockDeviceGuest).when(attributeGuest).get();
- Mockito.doReturn(channelIdGuest).when(channelGuest).id();
- Mockito.doReturn(
- "0000000141f3edcfc2c3000000000001d0000000000000000000000000000000000001")
- .when(channelIdGuest).asLongText();
+ CountDownLatch memberLatch = new CountDownLatch(1);
Mockito.doAnswer(new Answer<Object>() {
@Override
public CoapResponse answer(InvocationOnMock invocation)
+ resp.getPayloadString());
System.out.println(
"\t---------new member method : " + resp.getStatus());
- resObserver = resp;
+ memberLatch.countDown();
+ mResponseObserver = resp;
return resp;
}
}).when(mockDeviceGuest).sendResponse(Mockito.anyObject());
- createGroup(ctx, uuid, "Public");
- joinGroup(ctxGuest, uuidGuest);
- observeGroup(ctxGuest, uuidGuest);
- shareDevice(ctx, "d0002");
+ createGroup(mMockDevice, uuid, "Public");
+ joinGroup(mockDeviceGuest, uuidGuest);
+ observeGroup(mockDeviceGuest, uuidGuest);
+ shareDevice(mMockDevice, "d0002");
// assertion for the group master
- assertTrue(methodCheck(res, ResponseStatus.CHANGED));
+ assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
// assertion for the observer
- assertTrue(methodCheck(resObserver, ResponseStatus.CONTENT));
+ assertTrue(methodCheck(mResponseObserver, ResponseStatus.CONTENT));
+ assertTrue(mLatch.await(2L, SECONDS));
+ assertTrue(memberLatch.await(2L, SECONDS));
+ }
+ public void addDeviceAndUser(CoapDevice device, ArrayList<String> midList,
+ ArrayList<String> diList) throws Exception {
+ HashMap<String, Object> payloadData = new HashMap<>();
+ payloadData.put("midlist", midList);
+ payloadData.put("dilist", diList);
+ IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
+ GROUP_URI + "/" + mGroupId, null,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(payloadData));
+ System.out.println("-----add Device and User : " + payloadData);
+ mGroupResource.onDefaultRequestReceived(device, request);
}
- public void shareDevice(ChannelHandlerContext ctx, String deviceId)
+ public void deleteDeviceAndUser(CoapDevice device,
+ ArrayList<String> midList, ArrayList<String> diList)
throws Exception {
- System.out.println("-----Share Device");
- IRequest request = null;
- request = createShareDeviceRequest(deviceId);
- receiver.channelRead(ctx, request);
+ String midListString = "";
+ String didListString = "";
+ for (String mid : midList) {
+ midListString += "midlist=";
+ midListString += mid;
+ midListString += ";";
+ }
+ for (String di : diList) {
+ didListString += "dilist=";
+ didListString += di;
+ didListString += ";";
+ }
+ System.out.println("-----delete Device and User, Query: "
+ + midListString + didListString);
+ IRequest request = MessageBuilder.createRequest(RequestMethod.DELETE,
+ GROUP_URI + "/" + mGroupId, midListString + didListString);
+ mGroupResource.onDefaultRequestReceived(device, request);
}
- public IRequest createShareDeviceRequest(String deviceId) {
+ private void shareDevice(CoapDevice device, String deviceId)
+ throws Exception {
+ System.out.println("-----Share Device");
IRequest request = null;
- HashMap<String, Object> payloadData = new HashMap<String, Object>();
- ArrayList<String> diList = new ArrayList<>();
- diList.add(deviceId);
- payloadData.put("dilist", diList);
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
- request = MessageBuilder.createRequest(RequestMethod.POST,
- GROUP_URI + "/" + gid, null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
- return request;
+ request = createShareDeviceRequest(deviceId);
+ mGroupResource.onDefaultRequestReceived(device, request);
}
- public void createGroup(ChannelHandlerContext ctx, String gmid,
- String gtype) throws Exception {
+ private void createGroup(CoapDevice device, String gmid, String gtype)
+ throws Exception {
System.out.println("-----Create Group");
IRequest request = null;
request = createGroupRequest(gmid, gtype);
- receiver.channelRead(ctx, request);
+ mGroupResource.onDefaultRequestReceived(device, request);
}
- public void findGroup(ChannelHandlerContext ctx, String uuid)
- throws Exception {
+ private void findGroup(CoapDevice device, String uuid) throws Exception {
System.out.println("-----Find Group");
IRequest request = null;
request = findGroupRequest(uuid);
- receiver.channelRead(ctx, request);
+ mGroupResource.onDefaultRequestReceived(device, request);
}
- public void observeGroup(ChannelHandlerContext ctx, String uuid)
+ private void observeDeregisterGroup(CoapDevice device, String uuid)
throws Exception {
+ System.out.println("-----Observe Deregister Group");
+ IRequest request = null;
+ request = observeDeregisterGroupRequest(uuid);
+ mGroupResource.onDefaultRequestReceived(device, request);
+ }
+
+ private void observeGroup(CoapDevice device, String uuid) throws Exception {
System.out.println("-----Observe Group");
IRequest request = null;
request = observeGroupRequest(uuid);
- receiver.channelRead(ctx, request);
+ mGroupResource.onDefaultRequestReceived(device, request);
}
- public void joinGroup(ChannelHandlerContext ctx, String uuid)
- throws Exception {
+ private void joinGroup(CoapDevice device, String uuid) throws Exception {
System.out.println("-----Join Group");
IRequest request = null;
request = joinGroupRequest(uuid);
- receiver.channelRead(ctx, request);
+ mGroupResource.onDefaultRequestReceived(device, request);
}
- public void deleteGroup(ChannelHandlerContext ctx, String uuid)
- throws Exception {
+ private void deleteGroup(CoapDevice device, String uuid) throws Exception {
System.out.println("-----Delete Group");
IRequest request = null;
request = deleteGroupRequest(uuid);
- receiver.channelRead(ctx, request);
+ mGroupResource.onDefaultRequestReceived(device, request);
+ }
+
+ private void deleteGroupWithoutGid(CoapDevice device, String uuid)
+ throws Exception {
+ System.out.println("-----Delete Group");
+ IRequest request = null;
+ request = deleteGroupWithoutGidRequest(uuid);
+ mGroupResource.onDefaultRequestReceived(device, request);
+ }
+
+ private IRequest deleteGroupWithoutGidRequest(String uuid) {
+ IRequest request = null;
+ request = MessageBuilder.createRequest(RequestMethod.DELETE, GROUP_URI,
+ "gmid=" + uuid);
+ return request;
}
- public IRequest deleteGroupRequest(String uuid) {
+ private IRequest deleteGroupRequest(String uuid) {
IRequest request = null;
request = MessageBuilder.createRequest(RequestMethod.DELETE, GROUP_URI,
- "gid=" + gid + ";" + "gmid=" + uuid);
+ "gid=" + mGroupId + ";" + "gmid=" + uuid);
return request;
}
- public IRequest findGroupRequest(String uuid) {
+ private IRequest findGroupRequest(String uuid) {
IRequest request = null;
request = MessageBuilder.createRequest(RequestMethod.GET, GROUP_URI,
"mid=" + uuid);
return request;
}
- public IRequest observeGroupRequest(String uuid) {
+ private IRequest createShareDeviceRequest(String deviceId) {
+ IRequest request = null;
+ HashMap<String, Object> payloadData = new HashMap<String, Object>();
+ ArrayList<String> diList = new ArrayList<>();
+ diList.add(deviceId);
+ payloadData.put("dilist", diList);
+ request = MessageBuilder.createRequest(RequestMethod.POST,
+ GROUP_URI + "/" + mGroupId, null,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(payloadData));
+ return request;
+ }
+
+ private IRequest observeDeregisterGroupRequest(String uuid) {
IRequest request = null;
request = MessageBuilder.createRequest(RequestMethod.GET,
- GROUP_URI + "/" + gid, "mid=" + uuid);
+ GROUP_URI + "/" + mGroupId, "mid=" + uuid);
+ ((CoapRequest) request).setObserve(Observe.UNSUBSCRIBE);
+ return request;
+ }
+
+ private IRequest observeGroupRequest(String uuid) {
+ IRequest request = null;
+ request = MessageBuilder.createRequest(RequestMethod.GET,
+ GROUP_URI + "/" + mGroupId, "mid=" + uuid);
((CoapRequest) request).setObserve(Observe.SUBSCRIBE);
return request;
}
- public IRequest joinGroupRequest(String uuid) {
+ private IRequest joinGroupRequest(String uuid) {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
ArrayList<String> midList = new ArrayList<>();
midList.add(uuid);
payloadData.put("midlist", midList);
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
request = MessageBuilder.createRequest(RequestMethod.POST,
- GROUP_URI + "/" + gid, null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ GROUP_URI + "/" + mGroupId, null,
+ ContentFormat.APPLICATION_CBOR,
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public IRequest createGroupRequest(String uuid, String gtype) {
+ private IRequest createGroupRequest(String uuid, String gtype) {
IRequest request = null;
HashMap<String, Object> payloadData = new HashMap<String, Object>();
payloadData.put("gmid", uuid);
payloadData.put("gtype", gtype);
- Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>();
request = MessageBuilder.createRequest(RequestMethod.POST, GROUP_URI,
null, ContentFormat.APPLICATION_CBOR,
- cbor.encodingPayloadToCbor(payloadData));
+ mCbor.encodingPayloadToCbor(payloadData));
return request;
}
- public boolean hashmapCheck(IResponse response, String propertyName) {
+ private boolean hashmapCheck(IResponse response, String propertyName) {
HashMap<String, Object> payloadData = mCbor
.parsePayloadFromCbor(response.getPayload(), HashMap.class);
if (payloadData.containsKey(propertyName))
return false;
}
- public boolean methodCheck(IResponse response,
+ private boolean methodCheck(IResponse response,
ResponseStatus responseStatus) {
if (responseStatus == response.getStatus())
return true;
return false;
}
- private TokenTable makeTokenTable() {
- TokenTable tokenInfo = new TokenTable();
- tokenInfo.setUuid(uuid);
- tokenInfo.setDid(di);
- tokenInfo.setAccesstoken(accessToken);
- tokenInfo.setRefreshtoken(refreshToken);
- tokenInfo.setProvider(authProvider);
- tokenInfo.setExpiredtime(-1);
- Date currentTime = new Date();
- DateFormat transFormat = new SimpleDateFormat("yyyyMMddkkmm");
- tokenInfo.setIssuedtime(transFormat.format(currentTime));
- return tokenInfo;
- }
-
- private UserTable makeUserTable() {
- UserTable userInfo = new UserTable();
- userInfo.setUuid(uuid);
- userInfo.setProvider(authProvider);
- userInfo.setUserid("userId");
- return userInfo;
+ private void getTestMethodName() {
+ StackTraceElement[] stacks = new Throwable().getStackTrace();
+ StackTraceElement currentStack = stacks[1];
+ System.out.println("\t---Test Name : " + currentStack.getMethodName());
+ }
+
+ public void resetDB() throws Exception {
+ MongoDB mongoDB = new MongoDB(Constants.DB_NAME);
+ mongoDB.deleteTable(Constants.GROUP_TABLE);
+ mongoDB.createTable(Constants.GROUP_TABLE);
+ mongoDB.deleteTable(Constants.USER_TABLE);
+ mongoDB.createTable(Constants.USER_TABLE);
+ mongoDB.deleteTable(Constants.TOKEN_TABLE);
+ mongoDB.createTable(Constants.TOKEN_TABLE);
}
}