Commit 20ca8008 authored by Alina Habibulina's avatar Alina Habibulina

+ unit test

parent eda567b5
......@@ -3,3 +3,4 @@ build
.idea
.gradle
/bin/
......@@ -56,7 +56,7 @@ synergy.user.password=1
Endpoint: `http[s]://host:[port]/sap`
1. Метод смены/установки пароля [`GET`]`/proxy/uservice/set_password`
1. Метод смены/установки пароля [`POST`]`/proxy/uservice/set_password`
```
/**
......
......@@ -19,4 +19,19 @@ dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5.1'
providedCompile(group: 'org.jboss.resteasy', name: 'resteasy-jaxrs', version: '2.3.3.Final', transitive: false)
providedCompile 'org.jboss.spec:jboss-javaee-6.0:3.0.3.Final'
}
\ No newline at end of file
// https://mvnrepository.com/artifact/org.testng/testng
testCompile group: 'org.testng', name: 'testng', version: '6.14.3'
// https://mvnrepository.com/artifact/org.mockito/mockito-all
testCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
// https://mvnrepository.com/artifact/org.mockito/mockito-core
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.19.0'
// https://mvnrepository.com/artifact/org.slf4j/slf4j-simple
testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
// https://mvnrepository.com/artifact/net.iharder/base64
compile group: 'net.iharder', name: 'base64', version: '2.3.9'
// https://mvnrepository.com/artifact/org.powermock/powermock-core
testCompile group: 'org.powermock', name: 'powermock-core', version: '1.7.4'
// https://mvnrepository.com/artifact/org.seleniumhq.selenium/jetty-repacked
compile group: 'org.seleniumhq.selenium', name: 'jetty-repacked', version: '9.2.13.v20150730'
}
......@@ -2,6 +2,8 @@ package kz.arta.ext.sap.db;
import kz.arta.ext.sap.service.SynergyUser;
import kz.arta.ext.sap.util.ConnectionPool;
import org.omg.PortableInterceptor.USER_EXCEPTION;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -27,20 +29,39 @@ public class UserManager {
private static final String EXIST = "exist";
private static final String ISADMIN = "isadmin";
private ConnectionPool cp;
private UserManager um;
public UserManager() {
this.cp = new ConnectionPool();
}
public UserManager(ConnectionPool conpool) {
this.cp = conpool;
this.um = new UserManager();
}
public UserManager(ConnectionPool conpool, UserManager uman) {
this.cp = conpool;
this.um = uman;
}
/**
*
* @param login Логин пользователя, которому требуется сменить/установить пароль
* @param new_pass Новый пароль
* @return Возвращает 200 - в случае успешной смены пароля, 500 - в случае возникновения каких-либо ошибок с базой данных.
* @return Возвращает 200 - в случае успешной смены пароля, 404 - в случае отсутствия пользователя (которому меняют пароль) в базе, 500 - в случае возникновения каких-либо ошибок с базой данных.
*/
public static int setPass(String login, String new_pass) {
if(UserManager.selectFromUsersQuery(login, null, "exist").isExist()) {
public int setPass(String login, String new_pass) {
if(um == null) um = new UserManager();
if(um.selectFromUsersQuery(login, null, "exist").isExist()) {
Connection con = null;
PreparedStatement updatePassword = null;
try {
con = ConnectionPool.getConnection();
con = cp.getConnection();
updatePassword = con.prepareStatement("UPDATE users SET password = MD5( ? ) WHERE login = ? ");
updatePassword.setString(1, new_pass);
updatePassword.setString(2, login);
......@@ -59,7 +80,7 @@ public class UserManager {
return 500;
}
}
ConnectionPool.close(con);
cp.close(con);
}
} else return 404;
}
......@@ -72,39 +93,41 @@ public class UserManager {
* @return Объект класса SynergyUser
*/
public static SynergyUser selectFromUsersQuery(String login, String value, String requestType) {
public SynergyUser selectFromUsersQuery(String login, String value, String requestType) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
SynergyUser user = new SynergyUser();
try {
con = ConnectionPool.getConnection();
con = cp.getConnection();
if(requestType.equals(AUTH)) {
ps = con.prepareStatement("SELECT isadmin FROM users WHERE login = ? AND password = md5( ? )");
ps.setString(2, value);
ps.setString(1, login);
ps.setString(2, value);
rs = ps.executeQuery();
} else if(requestType.equals(EXIST)){
ps = con.prepareStatement("SELECT isadmin FROM users WHERE login = ?");
ps.setString(1, login);
rs = ps.executeQuery();
}
ps.setString(1, login);
rs = ps.executeQuery();
if(rs.next()) {
user.setAdmin(rs.getBoolean(ISADMIN));
user.setAuth(true);
user.setExist(true);
}
if(rs != null) {
if(rs.next()) {
user.setAdmin(rs.getBoolean(ISADMIN));
user.setAuth(true);
user.setExist(true);
}
}
return user;
} catch (SQLException | NamingException e) {
} catch (SQLException | NullPointerException | NamingException e) {
LOGGER.error("", e);
user.setError(500);
return user;
......@@ -123,7 +146,7 @@ public class UserManager {
LOGGER.error("", e);
}
}
ConnectionPool.close(con);
cp.close(con);
}
}
......
......@@ -11,7 +11,6 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* Created by val
* Date: 04.10.2015
......@@ -25,6 +24,16 @@ import javax.ws.rs.core.MediaType;
@Path("/uservice")
@RequestScoped
public class PasswordSetService {
private UserManager um;
public PasswordSetService(UserManager usman) {
this.um = usman;
}
public PasswordSetService() {
this.um = new UserManager();
}
@GET
@Path("/test")
......@@ -47,15 +56,18 @@ public class PasswordSetService {
@Produces(MediaType.APPLICATION_JSON + "; charset=utf-8")
public String setPassword(@HeaderParam("authorization") String authParam, @QueryParam("currentUserLogin") String currentUserLogin, @QueryParam("currentUserPass") String currentUserPass, @QueryParam("login") String login, @QueryParam("new_password") String new_pass){
try {
boolean su = UserManager.selectFromUsersQuery(currentUserLogin, currentUserPass, "auth").isAdmin();
boolean su = um.selectFromUsersQuery(currentUserLogin, currentUserPass, "auth").isAdmin();
System.out.println(su);
if(su) {
return PasswordSetService.errorMessagesHandler(UserManager.setPass(login, new_pass));
int errorCode = um.setPass(login, new_pass);
return PasswordSetService.errorMessagesHandler(errorCode);
} else {
if( login.equals(currentUserLogin)) return PasswordSetService.errorMessagesHandler(UserManager.setPass(login, new_pass));
if( login.equals(currentUserLogin)) {
int errorCode = um.setPass(login, new_pass);
return PasswordSetService.errorMessagesHandler(errorCode);
}
else return PasswordSetService.errorMessagesHandler(403);
}
......@@ -73,7 +85,7 @@ public class PasswordSetService {
case 401: return "{\"status\":\"401 Unauthorized!\", \"errorCode\": \"401\"}";
case 403: return "{\"status\":\"403 Forbidden.\", \"error\":\"You don't have any access to the requested account\", \"errorCode\": \"403\"}";
case 404: return "{\"status\":\"There is no user with such login!\", \"errorCode\": \"404\"}";
default: return "{\"status\":\"Something has gone wrong on serve/db\", \"errorCode\": \"500\"}";
default: return "{\"status\":\"Something has gone wrong on server/db\", \"errorCode\": \"500\"}";
}
}
}
......@@ -28,25 +28,35 @@ import javax.ws.rs.ext.Provider;
*
* Обработчик доступа к методам REST API
*/
@Provider
@ServerInterceptor
@Precedence("SECURITY")
public class SecurityInterceptor implements PreProcessInterceptor {
@Context
HttpServletRequest request;
@Context
HttpServletResponse response;
private static final ServerResponse ACCESS_DENIED = new ServerResponse("{\"status\":\"401 Unauthorized!\", \"errorCode\": \"401\"}", 401, new Headers<Object>());
private static final ServerResponse DB_ERROR = new ServerResponse("{\"status\":\"Something has gone wrong on serve/db\", \"errorCode\": \"500\"}", 500, new Headers<Object>());
private static final String AUTHORIZATION = "Authorization";
@Context
HttpServletRequest request;
private UserManager um;
@Context
HttpServletResponse response;
public SecurityInterceptor(HttpServletRequest req, UserManager usman) {
this.request = req;
this.um = usman;
}
public SecurityInterceptor() {
um = new UserManager();
}
@Override
public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethod resourceMethod) throws Failure, WebApplicationException {
if (httpRequest.getUri().getPath().startsWith("/uservice/")){
String authParam = request.getHeader(AUTHORIZATION);
......@@ -67,7 +77,8 @@ public class SecurityInterceptor implements PreProcessInterceptor {
String currentUserLogin = authArray[0];
String currentUserPass = authArray[1];
SynergyUser su = UserManager.selectFromUsersQuery(currentUserLogin, currentUserPass, "auth");
SynergyUser su = um.selectFromUsersQuery(currentUserLogin, currentUserPass, "auth");
if (su.getError() == 500) {
return DB_ERROR;
......
......@@ -6,6 +6,17 @@ public class SynergyUser {
private boolean exist;
private int error;
public SynergyUser() {
}
public SynergyUser(boolean adm, boolean au, boolean ex, int er) {
this.admin = adm;
this.auth = au;
this.exist = ex;
this.error = er;
}
public boolean isAdmin() {
return admin;
}
......@@ -37,6 +48,18 @@ public class SynergyUser {
public void setExist(boolean isExist) {
this.exist = isExist;
}
/**
*
* Сравнивает два объекта типа SynergyUser
* @param firstObj
* @param secondObject
* @return Если они равны - true, иначе - false
*/
public static boolean equals(SynergyUser firstObj, SynergyUser secondObject) {
if(firstObj.isAdmin() == secondObject.isAdmin() & firstObj.isAuth() == secondObject.isAuth()
& firstObj.isExist() == secondObject.isExist() & firstObj.getError() == firstObj.getError()) {
return true;
} else return false;
}
}
......@@ -31,23 +31,23 @@ public class Config {
FileInputStream fis = null;
Reader isr = null;
try {
fis = new FileInputStream(confFile);
isr = new InputStreamReader(fis, "UTF-8");
if (confFile.exists()) {
try {
props.load(isr);
} catch (IOException e) {
LOGGER.error("Configuration file not found");
} finally {
}
}
fis = new FileInputStream(confFile);
isr = new InputStreamReader(fis, "UTF-8");
if (confFile.exists()) {
try {
props.load(isr);
} catch (IOException e) {
LOGGER.error("Configuration file not found");
} finally {
}
}
} catch(FileNotFoundException err) {
LOGGER.error("File not found");
LOGGER.error("File not found");
} catch (UnsupportedEncodingException e1) {
LOGGER.error("UnsupportedEncodingException");
} finally {
if (null != fis)
LOGGER.error("UnsupportedEncodingException");
} finally {
if (null != fis)
{
try
{
......@@ -58,7 +58,7 @@ public class Config {
e.printStackTrace();
}
}
if (null != isr)
if (null != isr)
{
try
{
......@@ -72,10 +72,6 @@ public class Config {
}
}
public static URL getResource(String path) {
return Config.class.getResource(path);
}
public static String getConfigDir() {
return System.getProperty("jboss.server.config.dir");
}
......@@ -83,66 +79,4 @@ public class Config {
public static String getProperty(String name, String defaultValue) {
return props.containsKey(name) ? props.getProperty(name) : defaultValue;
}
public static int getIntProperty(String name, int defaultValue) {
if (props.containsKey(name)) {
int value = defaultValue;
String v = props.getProperty(name);
try {
value = Integer.parseInt(v);
} catch (NumberFormatException e) {
LOGGER.error("Invalid type of value '" + v + "' for property '" + name + "'. Integer type required.");
}
return value;
} else
return defaultValue;
}
public static double getDoubleProperty(String name, double defaultValue) {
if (props.containsKey(name)) {
double value = defaultValue;
String v = props.getProperty(name);
try {
value = Double.parseDouble(v);
} catch (NumberFormatException e) {
LOGGER.error("Invalid type of value '" + v + "' for property '" + name + "'. Double type required.");
}
return value;
} else
return defaultValue;
}
public static boolean getBooleanProperty(String name, boolean defaultValue) {
if (props.containsKey(name)) {
boolean value = defaultValue;
String v = props.getProperty(name);
try {
value = Boolean.parseBoolean(v);
} catch (Exception e) {
LOGGER.error("Invalid type of value '" + v + "' for property '" + name + "'. Boolean type required.");
}
return value;
}
return defaultValue;
}
public static List<String> getPropertyList(String mask, String[] defaultValue) {
List<String> list = new ArrayList<String>();
for (String property : props.stringPropertyNames()) {
if (property.startsWith(mask)) {
list.add(property.substring(property.lastIndexOf(".") + 1));
}
}
return list.size() > 0 ? list : Arrays.asList(defaultValue);
}
public static Map<String, String> getPropertyList(String mask) {
Map<String, String> map = new HashMap<String, String>();
for (String property : props.stringPropertyNames()) {
if (property.startsWith(mask)) {
map.put(property, props.getProperty(property));
}
}
return map;
}
}
......@@ -19,19 +19,23 @@ public class ConnectionPool {
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionPool.class);
public static Connection getConnection() throws SQLException, NamingException {
InitialContext ctx = new InitialContext();
public Connection getConnection() throws SQLException, NamingException {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/jboss/datasources/ml");
return ds.getConnection();
}
public static void close(Connection con) {
public boolean close(Connection con) {
if (con != null) {
try {
con.close();
return true;
} catch (SQLException e) {
LOGGER.error("Unable to close connection", e);
return false;
}
}
return true;
}
}
\ No newline at end of file
<jboss-web>
<context-root>sap</context-root>
</jboss-web>
\ No newline at end of file
</jboss-web>
......@@ -4,4 +4,5 @@
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
\ No newline at end of file
</web-app>
package kz.arta.ext.sap.db;
import org.testng.Assert;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.annotations.Test;
import kz.arta.ext.sap.service.SynergyUser;
import kz.arta.ext.sap.util.ConnectionPool;
@PrepareForTest({ UserManager.class })
public class UserManagerTest {
/**
* Тест на отсутствие соединения с дб
* @throws Exception
*/
@Test
public void selectFromUsersQueryTest_failConnection() throws Exception {
ConnectionPool cp = Mockito.mock(ConnectionPool.class);
Connection con = Mockito.mock(Connection.class);
Mockito.when(cp.getConnection()).thenReturn(con);
SynergyUser su = new SynergyUser();
su.setError(500);
UserManager um = new UserManager(cp);
SynergyUser sufunc = um.selectFromUsersQuery("login", "pass", "auth");
verify(cp).getConnection();
Assert.assertEquals(true, SynergyUser.equals(su, sufunc));
}
/**
* Тест на отсутвие пользователя в базе
*/
@Test
public void setPassTest_userNotFound_return404() {
UserManager mockUM = Mockito.mock(UserManager.class);
UserManager um = new UserManager(null, mockUM);
SynergyUser suNotExist = new SynergyUser(false, false, false, 0);
Mockito.when(mockUM.selectFromUsersQuery(anyString(), anyString(), anyString())).thenReturn(suNotExist);
Assert.assertEquals(404, um.setPass("login", "new_pass"));
verify(mockUM).selectFromUsersQuery(anyString(), anyString(), anyString());
}
/**
* Тест на успешный запрос в базу
*/
@Test
public void setPassTest_successQuery() {
ConnectionPool cp = Mockito.mock(ConnectionPool.class);
Connection con = Mockito.mock(Connection.class);
PreparedStatement ps = Mockito.mock(PreparedStatement.class);
ResultSet rs = Mockito.mock(ResultSet.class);
UserManager mockUM = Mockito.mock(UserManager.class);
UserManager um = new UserManager(cp, mockUM);
SynergyUser suExist = new SynergyUser(true, true, true, 0);
Mockito.when(mockUM.selectFromUsersQuery(anyString(), anyString(), anyString())).thenReturn(suExist);
try {
Mockito.when(cp.getConnection()).thenReturn(con);
Mockito.when(con.prepareStatement("UPDATE users SET password = MD5( ? ) WHERE login = ? ")).thenReturn(ps);
Mockito.doNothing().when(ps).setString(1, "new_pass");
Mockito.doNothing().when(ps).setString(2, "login");
Mockito.when(ps.executeQuery()).thenReturn(rs);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assert.assertEquals(200, um.setPass("login", "new_pass"));
verify(mockUM).selectFromUsersQuery(anyString(), anyString(), anyString());
}
/**
* Тест на ошибку 500
*/
@Test
public void setPassTest_error500() {
ConnectionPool cp = Mockito.mock(ConnectionPool.class);
UserManager mockUM = Mockito.mock(UserManager.class);
UserManager um = new UserManager(cp, mockUM);
SynergyUser suExist = new SynergyUser(true, true, true, 0);
Mockito.when(mockUM.selectFromUsersQuery(anyString(), anyString(), anyString())).thenReturn(suExist);
try {
Mockito.doThrow(SQLException.class).when(cp).getConnection();
} catch (Exception e) {
e.printStackTrace();
}
Assert.assertEquals(500, um.setPass("login", "new_pass"));
verify(mockUM).selectFromUsersQuery(anyString(), anyString(), anyString());
}
}
package kz.arta.ext.sap.service;
import org.testng.annotations.Test;
import kz.arta.ext.sap.db.UserManager;
import static org.mockito.Mockito.*;
import static org.testng.Assert.assertEquals;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class PasswordSetServiceTest {
@Mock private UserManager um;
@Test
public void errorMessagesHandlerTest() throws Exception {
assertEquals("{\"result\":\"success\", \"errorCode\":\"0\"}", PasswordSetService.errorMessagesHandler(200));
assertEquals("{\"status\":\"Something has gone wrong on server/db\", \"errorCode\": \"500\"}", PasswordSetService.errorMessagesHandler(111));
assertEquals("{\"status\":\"401 Unauthorized!\", \"errorCode\": \"401\"}", PasswordSetService.errorMessagesHandler(401));
assertEquals("{\"status\":\"403 Forbidden.\", \"error\":\"You don't have any access to the requested account\", \"errorCode\": \"403\"}", PasswordSetService.errorMessagesHandler(403));
assertEquals("{\"status\":\"There is no user with such login!\", \"errorCode\": \"404\"}", PasswordSetService.errorMessagesHandler(404));
}
/**
* Тест пользователя, который меняет пароль к чужой записи
* @throws
*/
@Test
public void mockSetPassword_accessForbidden() throws Exception {
SynergyUser suAuth = new SynergyUser();
suAuth.setAuth(true);
MockitoAnnotations.initMocks(this);
doReturn(suAuth).when(um).selectFromUsersQuery(anyString(), anyString(), anyString());
PasswordSetService pass = new PasswordSetService(um);
assertEquals("{\"status\":\"403 Forbidden.\", \"error\":\"You don't have any access to the requested account\", \"errorCode\": \"403\"}", pass.setPassword("login", "pass", "pass2", "log2", "new_pass"));
verify(um).selectFromUsersQuery(anyString(), anyString(), anyString());
}
/**
* Тест пользователя, который меняет пароль к своей записи
* @throws
*/
@Test
public void mockSetPassword_userSuccess() throws Exception {
SynergyUser suAuth = new SynergyUser();
suAuth.setAuth(true);
MockitoAnnotations.initMocks(this);
doReturn(suAuth).when(um).selectFromUsersQuery(anyString(), anyString(), anyString());
Mockito.when(um.setPass(anyString(), anyString())).thenReturn(200);
PasswordSetService pass = new PasswordSetService(um);
assertEquals("{\"result\":\"success\", \"errorCode\":\"0\"}", pass.setPassword("pass", "pass", "pass", "pass", "new_pass"));
verify(um).selectFromUsersQuery(anyString(), anyString(), anyString());
verify(um).setPass(anyString(), anyString());
}
/**
* Тест админа, который меняет пароль к записи существующего пользователя
* @throws
*/
@Test
public void mockSetPassword_successFromAdmin() throws Exception {
SynergyUser synUser = new SynergyUser();
synUser.setAdmin(true);
MockitoAnnotations.initMocks(this);
Mockito.when(um.selectFromUsersQuery(anyString(), anyString(), anyString())).thenReturn(synUser);
Mockito.when(um.setPass(anyString(), anyString())).thenReturn(200);
PasswordSetService pss = new PasswordSetService(um);
assertEquals(pss.setPassword("frst", "second", "third", "frth", "fifth"), "{\"result\":\"success\", \"errorCode\":\"0\"}");
verify(um).selectFromUsersQuery(anyString(), anyString(), anyString());
verify(um).setPass(anyString(), anyString());
}
/**
* Тест админа, который меняет пароль к записи несуществующего пользователя
* @throws
*/
@Test
public void mockSetPassword_failFromAdmin() throws Exception {
SynergyUser synUser = new SynergyUser();
synUser.setAdmin(true);
MockitoAnnotations.initMocks(this);
Mockito.when(um.selectFromUsersQuery(anyString(), anyString(), anyString())).thenReturn(synUser);
Mockito.when(um.setPass(anyString(), anyString())).thenReturn(404);
PasswordSetService pss = new PasswordSetService(um);
assertEquals(pss.setPassword("frst", "second", "third", "frth", "fifth"), "{\"status\":\"There is no user with such login!\", \"errorCode\": \"404\"}");
verify(um).selectFromUsersQuery(anyString(), anyString(), anyString());
verify(um).setPass(anyString(), anyString());
}
/*
@Test
public void mockTest_success() throws Exception {
PasswordSetService pss = new PasswordSetService();
assertEquals("{\"status\":\"working\"}", pss.test());
}
*/
}
package kz.arta.ext.sap.service;
import org.testng.Assert;
import org.testng.annotations.Test;
import kz.arta.ext.sap.db.UserManager;
import static org.mockito.Mockito.*;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import javax.accessibility.AccessibleRelation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import org.jboss.resteasy.core.Headers;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.AsynchronousResponse;
import org.jboss.resteasy.spi.HttpRequest;
import org.mockito.Mockito;
import org.mockito.internal.configuration.injection.filter.MockCandidateFilter;
import org.seleniumhq.jetty9.server.Authentication.User;
public class SecurityInterceptorTest {
/**
* Обращение к другому методу rest api
*/
@Test
public void preProcessTest_anotherMethod() {
SecurityInterceptor si = new SecurityInterceptor();
HttpRequest httpReq = Mockito.mock(HttpRequest.class);
ResourceMethod resm= Mockito.mock(ResourceMethod.class);
UriInfo uri = Mockito.mock(UriInfo.class);
when(httpReq.getUri()).thenReturn(uri);
when(uri.getPath()).thenReturn("lalala");
ServerResponse serverResp = si.preProcess(httpReq, resm);
Assert.assertEquals(null, serverResp);
}
/**
* Неудачная попытка авторизации
*/
@Test
public void preProcessTest_authorizationFailed() {
UserManager um = Mockito.mock(UserManager.class);
HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
SecurityInterceptor secInterp = new SecurityInterceptor(req, um);
HttpRequest httpRequest = Mockito.mock(HttpRequest.class);
ResourceMethod resourceMethod = Mockito.mock(ResourceMethod.class);
UriInfo uriInfo = Mockito.mock(UriInfo.class);
ServerResponse access_denied = new ServerResponse("{\"status\":\"401 Unauthorized!\", \"errorCode\": \"401\"}", 401, new Headers<Object>());
SynergyUser su = new SynergyUser(false, false, false, 0);
when(httpRequest.getUri()).thenReturn(uriInfo);
when(uriInfo.getPath()).thenReturn("/uservice/lalala");
when(req.getHeader(anyString())).thenReturn("Basic bG9naW46cGFzc3dvcmQ=");
when(um.selectFromUsersQuery(anyString(), anyString(), anyString())).thenReturn(su);
ServerResponse sp = secInterp.preProcess(httpRequest, resourceMethod);
Assert.assertEquals(sp.getStatus(), access_denied.getStatus());
}
/**
* Ошибка бд при авторизации
*/
@Test
public void preProcessTest_dbError() {
UserManager um = Mockito.mock(UserManager.class);
HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
SecurityInterceptor secInterp = new SecurityInterceptor(req, um);
HttpRequest httpRequest = Mockito.mock(HttpRequest.class);
ResourceMethod resourceMethod = Mockito.mock(ResourceMethod.class);
UriInfo uriInfo = Mockito.mock(UriInfo.class);
ServerResponse db_error = new ServerResponse("{\"status\":\"Something has gone wrong on serve/db\", \"errorCode\": \"500\"}", 500, new Headers<Object>());
SynergyUser su = new SynergyUser(false, false, false, 500);
when(httpRequest.getUri()).thenReturn(uriInfo);
when(uriInfo.getPath()).thenReturn("/uservice/lalala");
when(req.getHeader(anyString())).thenReturn("Basic bG9naW46cGFzc3dvcmQ=");
when(um.selectFromUsersQuery(anyString(), anyString(), anyString())).thenReturn(su);
ServerResponse sp = secInterp.preProcess(httpRequest, resourceMethod);
Assert.assertEquals(sp.getStatus(), db_error.getStatus());
}
/**
* Удачная попытка авторизации
*/
@Test
public void preProcessTest_authorizationSuccess() {
UserManager um = Mockito.mock(UserManager.class);
HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
SecurityInterceptor secInterp = new SecurityInterceptor(req, um);
HttpRequest httpRequest = Mockito.mock(HttpRequest.class);
ResourceMethod resourceMethod = Mockito.mock(ResourceMethod.class);
UriInfo uriInfo = Mockito.mock(UriInfo.class);
@SuppressWarnings("unchecked")
MultivaluedMap<String, String> mm = Mockito.mock(MultivaluedMap.class);
SynergyUser su = new SynergyUser(true, true, true, 0);
when(httpRequest.getUri()).thenReturn(uriInfo);
when(uriInfo.getPath()).thenReturn("/uservice/lalala");
when(uriInfo.getQueryParameters()).thenReturn(mm);
Mockito.doNothing().when(mm).add(anyString(), anyString());
when(req.getHeader(anyString())).thenReturn("Basic bG9naW46cGFzc3dvcmQ=");
when(um.selectFromUsersQuery(anyString(), anyString(), anyString())).thenReturn(su);
secInterp.preProcess(httpRequest, resourceMethod);
}
}
package kz.arta.ext.sap.service;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class SynergyUserTest {
SynergyUser user = new SynergyUser();
@Test
public void isAdminTest_false() throws Exception {
assertEquals(false, user.isAdmin());
}
@Test
public void setAdminTest_true() throws Exception {
user.setAdmin(true);
assertEquals(true, user.isAdmin());
}
@Test
public void isAuthTest_false() throws Exception {
assertEquals(false, user.isAuth());
}
@Test
public void setAuthTest_true() throws Exception {
user.setAuth(true);
assertEquals(true, user.isAuth());
}
@Test
public void getErrorTest_0() throws Exception {
assertEquals(0, user.getError());
}
@Test
public void setErrorTest_200() throws Exception {
user.setError(200);
assertEquals(200, user.getError());
}
@Test
public void isExistTest_false() throws Exception {
assertEquals(false, user.isExist());
}
@Test
public void isExistTest_true() throws Exception {
user.setExist(true);
assertEquals(true, user.isExist());
}
@Test
public void equalsTest_returnTrue() {
SynergyUser su1 = new SynergyUser(false, true, false, 500);
SynergyUser su2 = new SynergyUser(false, true, false, 500);
assertEquals(true, SynergyUser.equals(su1, su2));
}
@Test
public void equalsTest_returnfalse() {
SynergyUser su1 = new SynergyUser(true, true, true, 500);
SynergyUser su2 = new SynergyUser(false, true, false, 500);
assertEquals(false, SynergyUser.equals(su1, su2));
}
}
package kz.arta.ext.sap.util;
import static org.mockito.Mockito.*;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
public class ConfigTest {
@Test
public void getPropertyTest_defaultValue() {
java.util.Properties props = mock(java.util.Properties.class);
when(props.containsKey(anyString())).thenReturn(false);
assertEquals("defaultValue", Config.getProperty("name", "defaultValue"));
}
}
package kz.arta.ext.sap.util;
import static org.mockito.Mockito.*;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
public class ConnectionPoolTest {
ConnectionPool cp = new ConnectionPool();
@Test
public void mockGetConnection() {
try {
when(cp.getConnection()).thenReturn(null);
assertEquals(null, cp.getConnection());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment