Compare commits

...

No commits in common. "main" and "master" have entirely different histories.
main ... master

31 changed files with 933 additions and 1 deletions

5
.gitignore vendored
View File

@ -1,6 +1,11 @@
# ---> Java
# Compiled class file
*.class
.idea
.idea/*
.gradle
out
build
# Log file
*.log

20
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,20 @@
pipeline {
agent {
docker {
image 'romanov73/is:ng-tracker-container-11'
}
}
stages {
stage('Cloning Git') {
steps {
git([url: 'https://git.athene.tech/romanov73/example-web.git', branch: 'master'])
}
}
stage('Test') {
steps {
sh 'java -version'
sh "bash ./gradlew bootRun --args='--example-web.check-run=true'"
}
}
}
}

View File

@ -1,2 +1,2 @@
# web-example
# example-web

40
build.gradle Normal file
View File

@ -0,0 +1,40 @@
plugins {
id 'java'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'org.springframework.boot' version '2.6.4'
}
jar {
archivesBaseName = 'example-web'
}
group 'ru.ulstu'
version '1.0-SNAPSHOT'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
ext {
versionSLF4J = '1.7.24'
versionJetty = '9.3.16.v20170120'
versionJackson = '2.9.4'
versionSwagger = '2.5.0'
}
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-jetty'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-test'
implementation group: 'org.slf4j', name: 'slf4j-api', version: versionSLF4J
implementation group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '3.1.0'
implementation group: 'org.powermock', name: 'powermock-module-junit4', version: '1.7.4'
implementation group: 'org.powermock', name: 'powermock-api-mockito', version: '1.7.4'
implementation group: 'org.powermock', name: 'powermock-api-mockito-common', version: '1.7.4'
implementation group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
}

View File

@ -0,0 +1,6 @@
#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip

160
gradlew vendored Normal file
View File

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
gradlew.bat vendored Normal file
View File

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,29 @@
package ru.ulstu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import ru.ulstu.configuration.ApplicationProperties;
@SpringBootApplication
public class ExampleWebApplication {
private final ApplicationProperties applicationProperties;
public ExampleWebApplication(ApplicationProperties applicationProperties) {
this.applicationProperties = applicationProperties;
}
public static void main(String[] args) {
SpringApplication.run(ExampleWebApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
System.out.println(applicationProperties.isCheckRun());
if (applicationProperties.isCheckRun()) {
System.exit(0);
}
}
}

View File

@ -0,0 +1,45 @@
package ru.ulstu;
import ru.ulstu.entity.User;
import ru.ulstu.exception.UserNotValidException;
import ru.ulstu.persistence.DbStore;
import ru.ulstu.persistence.FileStore;
import ru.ulstu.persistence.PersistentStore;
import ru.ulstu.util.PropertyManager;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
public class UserService {
private PersistentStore<User> persistentStore;
PropertyManager propertyManager = PropertyManager.getInstance();
public UserService(PersistentStore<User> persistentStore) {
this.persistentStore = persistentStore;
}
public UserService() {
persistentStore = propertyManager.getTargetStorage().equals("file")
? new FileStore(User.class)
: new DbStore(User.class);
}
public User saveUser(User user) throws UserNotValidException, IOException {
validateUser(user);
return persistentStore.save(user);
}
public List<User> getUsers() throws IOException {
return persistentStore.readAll()
.stream()
.limit(10)
.collect(Collectors.toList());
}
private void validateUser(User user) throws UserNotValidException {
if (user.getLogin() == null || user.getLogin().equals("")) {
throw new UserNotValidException("Пустой логин", UserNotValidException.Code.EMPTY_LOGIN);
}
}
}

View File

@ -0,0 +1,18 @@
package ru.ulstu.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "example-web")
public class ApplicationProperties {
private boolean checkRun;
public boolean isCheckRun() {
return checkRun;
}
public void setCheckRun(boolean checkRun) {
this.checkRun = checkRun;
}
}

View File

@ -0,0 +1,49 @@
package ru.ulstu.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login");
registry.addViewController("/loginError");
registry.addViewController("/index");
registry.addViewController("/admin");
registry.addViewController("/organizers");
registry.addViewController("/docs");
registry.addViewController("/editNews");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("/webjars/");
}
@Bean
public LocaleResolver localeResolver() {
return new CookieLocaleResolver();
}
@Bean
public LocaleChangeInterceptor localeInterceptor() {
LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
localeInterceptor.setParamName("lang");
return localeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeInterceptor());
}
}

View File

@ -0,0 +1,19 @@
package ru.ulstu.configuration;
import nz.net.ultraq.thymeleaf.layoutdialect.LayoutDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ITemplateResolver;
@Configuration
public class TemplateConfiguration {
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(templateResolver);
templateEngine.addDialect(new LayoutDialect());
return templateEngine;
}
}

View File

@ -0,0 +1,14 @@
package ru.ulstu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model model) {
return "index";
}
}

View File

@ -0,0 +1,36 @@
package ru.ulstu.entity;
import java.util.Objects;
public abstract class BaseEntity {
protected Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
return Objects.hashCode(this.id);
}
@Override
public boolean equals(Object o) {
// self check
if (this == o)
return true;
// null check
if (o == null)
return false;
// type check and cast
if (getClass() != o.getClass())
return false;
BaseEntity baseEntity = (BaseEntity) o;
// field comparison
return Objects.equals(id, (baseEntity.getId()));
}
}

View File

@ -0,0 +1,43 @@
package ru.ulstu.entity;
public class User extends BaseEntity {
private String login;
private String password;
private String fullName;
public User() {
}
public User(Long id, String login) {
this.login = login;
this.id = id;
}
public User(String login) {
this.login = login;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}

View File

@ -0,0 +1,18 @@
package ru.ulstu.exception;
public class UserNotValidException extends Exception {
public enum Code {
EMPTY_LOGIN
}
private final Code code;
public UserNotValidException(String message, Code code) {
super(message);
this.code = code;
}
public Code getCode() {
return code;
}
}

View File

@ -0,0 +1,27 @@
package ru.ulstu.persistence;
import ru.ulstu.entity.BaseEntity;
import java.util.List;
public class DbStore<T extends BaseEntity> extends PersistentStore<T> {
public DbStore(Class type) {
super(type);
}
@Override
public List<T> save(List<T> entities) {
throw new RuntimeException("not implemented yet");
}
@Override
public T save(T entity) {
throw new RuntimeException("not implemented yet");
}
@Override
public List readAll() {
throw new RuntimeException("not implemented yet");
}
}

View File

@ -0,0 +1,58 @@
package ru.ulstu.persistence;
import com.fasterxml.jackson.databind.ObjectMapper;
import ru.ulstu.entity.BaseEntity;
import ru.ulstu.util.PropertyManager;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class FileStore<T extends BaseEntity> extends PersistentStore<T> {
private ObjectMapper mapper;
private File storageFile;
public FileStore(Class type) {
super(type);
this.mapper = new ObjectMapper();
this.storageFile = new File(PropertyManager.getInstance().getFileStorage());
}
@Override
public List<T> save(List<T> entities) throws IOException {
mapper.writeValue(storageFile, entities);
return entities;
}
@Override
public T save(T entity) throws IOException {
List<T> entities = readAll();
entities.remove(entity);
entity.setId(getGeneratedId(entities));
entities.add(entity);
save(entities);
return entity;
}
private Long getGeneratedId(List<T> entities) {
if (entities == null || entities.isEmpty()) {
return 1L;
}
entities.sort(Comparator.comparing(BaseEntity::getId));
Long lastId = entities.get(entities.size() - 1).getId();
return lastId == null ? 1 : lastId + 1;
}
@Override
public List<T> readAll() throws IOException {
return mapper.readValue(storageFile, mapper.getTypeFactory().constructCollectionType(List.class, getType()));
}
public void reset() throws IOException {
List<T> list = new ArrayList();
save(list);
}
}

View File

@ -0,0 +1,24 @@
package ru.ulstu.persistence;
import ru.ulstu.entity.BaseEntity;
import java.io.IOException;
import java.util.List;
public abstract class PersistentStore<T extends BaseEntity> {
private Class type;
protected PersistentStore(Class type) {
this.type = type;
}
public abstract List<T> save(List<T> entities) throws IOException;
public abstract T save(T entity) throws IOException;
public abstract List<T> readAll() throws IOException;
public Class getType() {
return type;
}
}

View File

@ -0,0 +1,57 @@
package ru.ulstu.util;
import java.io.InputStream;
import java.util.Properties;
public class PropertyManager {
public static final PropertyManager INSTANCE = new PropertyManager();
private final static String CONFIG_NAME = "config.properties";
private enum ConfigKey {
FILE_STORAGE("fileStorage"),
TARGET_STORAGE("targetStorage"),
DB_NAME("dbName"),
DB_USER("dbUser"),
DB_PASSWORD("dbPassword"),
DB_HOST("dbHost"),
DB_PORT("dbPort");
private String keyName;
ConfigKey(String key) {
this.keyName = key;
}
public String getKeyName() {
return keyName;
}
}
private Properties properties;
private PropertyManager() {
properties = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try (InputStream resourceStream = loader.getResourceAsStream(CONFIG_NAME)) {
properties.load(resourceStream);
} catch (Exception ex) {
System.out.println(String.format("Config read error: %s", ex.getMessage()));
}
}
public static PropertyManager getInstance() {
return INSTANCE;
}
public String getFileStorage() {
return properties.getProperty(ConfigKey.FILE_STORAGE.getKeyName());
}
public String getTargetStorage() {
return properties.getProperty(ConfigKey.TARGET_STORAGE.getKeyName());
}
public void getProperty(String key) {
properties.getProperty(key);
}
}

View File

@ -0,0 +1,3 @@
spring.main.banner-mode=off
server.port=8080
example-web.check-run=false

View File

@ -0,0 +1,8 @@
# Possible values: file or db
targetStorage=file
fileStorage=test-users.json
dbHost=localhost
dbName=unit-test
dbPort=5432
dbUser=postgres
dbPassword=postgres

View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="ru"
xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title th:text="#{messages.app-name}">app-name</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<div class="body-container">
Стартовая страница
</div>
<footer>
</footer>
</body>
</html>

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div class="container" layout:fragment="content">
<h5>Доступ запрещён</h5>
<a href="/"><h6>Вернуться на главную</h6></a>
</div>
</body>
</html>

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div class="container" layout:fragment="content">
<h5>Страница не найдена</h5>
<a href="/"><h6>Вернуться на главную</h6></a>
</div>
</body>
</html>

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div class="container" layout:fragment="content">
<h5>Ошибка сервера</h5>
<a href="/"><h6>Вернуться на главную</h6></a>
</div>
</body>
</html>

View File

@ -0,0 +1,7 @@
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<div class="container" layout:fragment="content">
</div>
</html>

View File

@ -0,0 +1,33 @@
package ru.ulstu;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import ru.ulstu.entity.User;
import ru.ulstu.persistence.DbStore;
import java.io.IOException;
import static org.powermock.api.mockito.PowerMockito.when;
public class DbStoreTest {
@Mock
private DbStore dbStore = PowerMockito.mock(DbStore.class);
@Before
public void before() {
Mockito.reset(dbStore);
}
@Test
public void saveNewUserToFileTest() throws IOException {
User newUser = new User("login");
when(dbStore.save(Mockito.any(User.class))).thenReturn(new User(1L, "login"));
newUser = (User) dbStore.save(newUser);
Assert.assertEquals((long) newUser.getId(), 1L);
}
}

View File

@ -0,0 +1,33 @@
package ru.ulstu;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import ru.ulstu.entity.User;
import ru.ulstu.persistence.FileStore;
import ru.ulstu.persistence.PersistentStore;
import java.io.IOException;
public class FileStoreTest {
private final PersistentStore<User> fileStore = new FileStore<>(User.class);
@Before
public void before() throws IOException {
((FileStore) fileStore).reset();
}
@Test
public void saveNewUserToFileTest() throws IOException {
User newUser = new User("");
newUser = fileStore.save(newUser);
Assert.assertEquals((long) newUser.getId(), 1L);
}
@After
public void after() throws IOException {
((FileStore) fileStore).reset();
}
}

View File

@ -0,0 +1,26 @@
package ru.ulstu;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import ru.ulstu.entity.User;
import ru.ulstu.exception.UserNotValidException;
import ru.ulstu.persistence.FileStore;
import java.io.IOException;
public class UserServiceTest {
@Mock
private FileStore fileStore = PowerMockito.mock(FileStore.class);
private final UserService userService = new UserService(fileStore);
@Test
public void testUserSave() throws UserNotValidException, IOException {
User user = new User("login");
userService.saveUser(user);
Mockito.verify(fileStore, Mockito.times(1)).save(user);
}
}

View File

@ -0,0 +1,8 @@
# Possible values: file or db
targetStorage=file
fileStorage=test-users.json
dbHost=localhost
dbName=unit-test
dbPort=5432
dbUser=postgres
dbPassword=postgres