├── settings.gradle ├── README.md ├── src ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── demo │ │ │ ├── repository │ │ │ ├── RobotView.java │ │ │ ├── RobotFilter.java │ │ │ ├── CustomRobotServerRepository.java │ │ │ ├── RobotRepository.java │ │ │ └── CustomRobotServerRepositoryImpl.java │ │ │ ├── service │ │ │ ├── OperationStatus.java │ │ │ ├── RobotUpdateService.java │ │ │ ├── RobotRestrictions.java │ │ │ └── RobotAllowedOperations.java │ │ │ ├── exception │ │ │ └── OperationRestrictedException.java │ │ │ ├── SpringBootReadonlyTransactionsApplication.java │ │ │ ├── entity │ │ │ └── Robot.java │ │ │ └── annotation │ │ │ └── ReadTransactional.java │ └── resources │ │ └── application.properties └── test │ ├── java │ └── com │ │ └── example │ │ └── demo │ │ ├── testutils │ │ ├── TestBuilder.java │ │ ├── DBTest.java │ │ └── TestDBFacade.java │ │ ├── entity │ │ ├── RobotFactory.java │ │ └── RobotTestBuilder.java │ │ ├── repository │ │ └── RobotRepositoryTest.java │ │ └── service │ │ ├── RobotUpdateServiceTestH2TestDataBuilder.java │ │ ├── RobotUpdateServiceTestH2.java │ │ ├── RobotUpdateServiceTestH2DirtiesContext.java │ │ ├── RobotUpdateServiceTestH2DataJpa.java │ │ ├── RobotUpdateServiceTestH2DataJpaNonTransactional.java │ │ └── RobotAllowedOperationsTest.java │ └── resources │ └── application.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── LICENSE ├── gradlew.bat └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'spring-data-jpa-efficient-testing' 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-data-jpa-efficient-testing 2 | Код, фигурирующий в докладе "Spring Data JPA. Эффективное тестирование" 3 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/RobotView.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | public class RobotView { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/RobotFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | public class RobotFilter { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimonHarmonicMinor/spring-data-jpa-efficient-testing/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/test/java/com/example/demo/testutils/TestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.testutils; 2 | 3 | public interface TestBuilder { 4 | T build(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/service/OperationStatus.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | public enum OperationStatus { 4 | ALLOWED, 5 | RESTRICTED, 6 | ROBOT_IS_ABSENT 7 | } 8 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.hikari.auto-commit=false 2 | spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true 3 | spring.jpa.open-in-view=false -------------------------------------------------------------------------------- /src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.flyway.enabled=false 2 | spring.jpa.hibernate.ddl-auto=create 3 | spring.jpa.show-sql=true 4 | logging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUG -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/exception/OperationRestrictedException.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.exception; 2 | 3 | public class OperationRestrictedException extends RuntimeException { 4 | 5 | public OperationRestrictedException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/CustomRobotServerRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | import org.springframework.data.domain.Page; 4 | 5 | public interface CustomRobotServerRepository { 6 | Page findByFilter(RobotFilter filter, int page, int pageSize); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/SpringBootReadonlyTransactionsApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootReadonlyTransactionsApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootReadonlyTransactionsApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/example/demo/entity/RobotFactory.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.entity; 2 | 3 | import com.example.demo.entity.Robot.Type; 4 | 5 | public class RobotFactory { 6 | public static Robot createWithName(String name) { 7 | return null; 8 | } 9 | 10 | public static Robot createWithType(Type type) { 11 | return null; 12 | } 13 | 14 | public static Robot createWithNameAndType(String name, Type type) { 15 | return null; 16 | } 17 | 18 | public static Robot createWithTypeAndSwitched(Type type, boolean switched) { 19 | return null; 20 | } 21 | 22 | public static Robot createWithNameAndTypeAndSwitched(String name, Type type, boolean switched) { 23 | return null; 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/testutils/DBTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.testutils; 2 | 3 | import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; 4 | 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 8 | import org.springframework.context.annotation.Import; 9 | import org.springframework.core.annotation.AliasFor; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | @Retention(RetentionPolicy.RUNTIME) 13 | @DataJpaTest 14 | @Import({TestDBFacade.Config.class}) 15 | @Transactional(propagation = NOT_SUPPORTED) 16 | public @interface DBTest { 17 | 18 | @AliasFor(annotation = DataJpaTest.class, attribute = "properties") 19 | String[] properties() default {}; 20 | } 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | HELP.md 26 | .gradle 27 | build/ 28 | !gradle/wrapper/gradle-wrapper.jar 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### STS ### 33 | .apt_generated 34 | .classpath 35 | .factorypath 36 | .project 37 | .settings 38 | .springBeans 39 | .sts4-cache 40 | bin/ 41 | !**/src/main/**/bin/ 42 | !**/src/test/**/bin/ 43 | 44 | ### IntelliJ IDEA ### 45 | .idea 46 | *.iws 47 | *.iml 48 | *.ipr 49 | out/ 50 | !**/src/main/**/out/ 51 | !**/src/test/**/out/ 52 | 53 | ### NetBeans ### 54 | /nbproject/private/ 55 | /nbbuild/ 56 | /dist/ 57 | /nbdist/ 58 | /.nb-gradle/ 59 | 60 | ### VS Code ### 61 | .vscode/ 62 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/service/RobotUpdateService.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import com.example.demo.repository.RobotRepository; 4 | import org.springframework.stereotype.Service; 5 | import org.springframework.transaction.annotation.Transactional; 6 | 7 | @Service 8 | public class RobotUpdateService { 9 | 10 | private final RobotRepository robotRepository; 11 | private final RobotRestrictions robotRestrictions; 12 | 13 | public RobotUpdateService( 14 | RobotRepository robotRepository, 15 | RobotRestrictions robotRestrictions 16 | ) { 17 | this.robotRepository = robotRepository; 18 | this.robotRestrictions = robotRestrictions; 19 | } 20 | 21 | @Transactional 22 | public void switchOnRobot(Long robotId) { 23 | final var robot = 24 | robotRepository.findById(robotId) 25 | .orElseThrow(); 26 | robot.setSwitched(true); 27 | robotRepository.flush(); 28 | robotRestrictions.checkSwitchOn(robotId); 29 | } 30 | 31 | private void reallyLongOperation() { 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/repository/RobotRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | import static com.example.demo.entity.RobotTestBuilder.aRobot; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | 6 | import com.example.demo.testutils.TestDBFacade; 7 | import java.util.Set; 8 | import org.junit.jupiter.api.Test; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 11 | import org.springframework.context.annotation.Import; 12 | 13 | @DataJpaTest 14 | @Import(TestDBFacade.class) 15 | class RobotRepositoryTest { 16 | @Autowired 17 | private RobotRepository robotRepository; 18 | @Autowired 19 | private TestDBFacade db; 20 | 21 | @Test 22 | void shouldReturnUniqueNames() { 23 | db.saveAll( 24 | aRobot().name("s1"), 25 | aRobot().name("s1"), 26 | aRobot().name("s2") 27 | ); 28 | 29 | final var names = robotRepository.findUniqueNames(); 30 | 31 | assertEquals(Set.of("s1", "s2"), names); 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/RobotRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | import com.example.demo.entity.Robot; 4 | import com.example.demo.entity.Robot.Type; 5 | import java.util.List; 6 | import java.util.Set; 7 | import javax.persistence.QueryHint; 8 | import org.springframework.data.jpa.domain.Specification; 9 | import org.springframework.data.jpa.repository.JpaRepository; 10 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 11 | import org.springframework.data.jpa.repository.Query; 12 | import org.springframework.data.jpa.repository.QueryHints; 13 | 14 | public interface RobotRepository extends JpaRepository, 15 | CustomRobotServerRepository, JpaSpecificationExecutor { 16 | 17 | long countAllByTypeAndIdNot(Type type, Long id); 18 | 19 | @Query("SELECT DISTINCT name FROM Robot") 20 | Set findUniqueNames(); 21 | 22 | @Override 23 | @QueryHints( 24 | @QueryHint(name = "hint_name", value = "hint_value") 25 | ) 26 | List findAll(Specification spec); 27 | } 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Semyon Kirekov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/CustomRobotServerRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | import javax.persistence.EntityManager; 4 | import javax.persistence.EntityManagerFactory; 5 | import javax.persistence.PersistenceContext; 6 | import org.hibernate.SessionFactory; 7 | import org.hibernate.engine.spi.SessionFactoryImplementor; 8 | import org.hibernate.service.ServiceRegistry; 9 | import org.springframework.data.domain.Page; 10 | import org.springframework.stereotype.Repository; 11 | 12 | @Repository 13 | class CustomRobotServerRepositoryImpl implements 14 | CustomRobotServerRepository { 15 | 16 | @PersistenceContext 17 | private EntityManager em; 18 | 19 | private EntityManagerFactory emf; 20 | 21 | @Override 22 | public Page findByFilter(RobotFilter filter, int page, int pageSize) { 23 | // stub 24 | SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) emf.unwrap(SessionFactory.class); 25 | ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry(); 26 | emf.createEntityManager() 27 | .createQuery("") 28 | .getSingleResult(); 29 | return Page.empty(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/example/demo/entity/RobotTestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.entity; 2 | 3 | import static com.example.demo.entity.Robot.Type.DRIVER; 4 | 5 | import com.example.demo.entity.Robot.Type; 6 | import com.example.demo.testutils.TestBuilder; 7 | import java.util.function.Consumer; 8 | 9 | 10 | public class RobotTestBuilder implements TestBuilder { 11 | 12 | private String name = ""; 13 | private boolean switched = false; 14 | private Type type = DRIVER; 15 | 16 | private RobotTestBuilder() { 17 | } 18 | 19 | private RobotTestBuilder(RobotTestBuilder builder) { 20 | this.name = builder.name; 21 | this.switched = builder.switched; 22 | this.type = builder.type; 23 | } 24 | 25 | public static RobotTestBuilder aRobot() { 26 | return new RobotTestBuilder(); 27 | } 28 | 29 | public RobotTestBuilder name(String name) { 30 | return copyWith(b -> b.name = name); 31 | } 32 | 33 | public RobotTestBuilder switched(boolean switched) { 34 | return copyWith(b -> b.switched = switched); 35 | } 36 | 37 | public RobotTestBuilder type(Type type) { 38 | return copyWith(b -> b.type = type); 39 | } 40 | 41 | private RobotTestBuilder copyWith(Consumer consumer) { 42 | final var copy = new RobotTestBuilder(this); 43 | consumer.accept(copy); 44 | return copy; 45 | } 46 | 47 | @Override 48 | public Robot build() { 49 | final var server = new Robot(); 50 | server.setName(name); 51 | server.setSwitched(switched); 52 | server.setType(type); 53 | return server; 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/java/com/example/demo/entity/Robot.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.entity; 2 | 3 | import static javax.persistence.EnumType.STRING; 4 | import static javax.persistence.GenerationType.IDENTITY; 5 | 6 | import com.sun.istack.NotNull; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.Enumerated; 10 | import javax.persistence.GeneratedValue; 11 | import javax.persistence.Id; 12 | import javax.persistence.Table; 13 | 14 | @Entity 15 | @Table(name = "robot") 16 | public class Robot { 17 | @Id 18 | @GeneratedValue(strategy = IDENTITY) 19 | @Column(name = "robot_id") 20 | private Long id; 21 | 22 | @NotNull 23 | private String name; 24 | 25 | @NotNull 26 | private boolean switched; 27 | 28 | @Enumerated(STRING) 29 | @NotNull 30 | private Type type; 31 | 32 | public enum Type { 33 | DRIVER, 34 | LOADER, 35 | VACUUM 36 | } 37 | 38 | public Long getId() { 39 | return id; 40 | } 41 | 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public boolean isSwitched() { 47 | return switched; 48 | } 49 | 50 | public Type getType() { 51 | return type; 52 | } 53 | 54 | public void setName(String name) { 55 | this.name = name; 56 | } 57 | 58 | public void setSwitched(boolean switched) { 59 | this.switched = switched; 60 | } 61 | 62 | public void setType(Type type) { 63 | this.type = type; 64 | } 65 | 66 | public Robot(String name, boolean switched, Type type) { 67 | this.name = name; 68 | this.switched = switched; 69 | this.type = type; 70 | } 71 | 72 | public Robot() { 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/annotation/ReadTransactional.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | import org.springframework.core.annotation.AliasFor; 9 | import org.springframework.transaction.TransactionDefinition; 10 | import org.springframework.transaction.annotation.Isolation; 11 | import org.springframework.transaction.annotation.Propagation; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | @Target({ElementType.TYPE, ElementType.METHOD}) 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Transactional(readOnly = true, noRollbackFor = Exception.class) 17 | @Documented 18 | public @interface ReadTransactional { 19 | @AliasFor(annotation = Transactional.class, attribute = "value") 20 | String value() default ""; 21 | 22 | @AliasFor(annotation = Transactional.class, attribute = "transactionManager") 23 | String transactionManager() default ""; 24 | 25 | @AliasFor(annotation = Transactional.class, attribute = "label") 26 | String[] label() default {}; 27 | 28 | @AliasFor(annotation = Transactional.class, attribute = "propagation") 29 | Propagation propagation() default Propagation.REQUIRED; 30 | 31 | @AliasFor(annotation = Transactional.class, attribute = "isolation") 32 | Isolation isolation() default Isolation.DEFAULT; 33 | 34 | @AliasFor(annotation = Transactional.class, attribute = "timeout") 35 | int timeout() default TransactionDefinition.TIMEOUT_DEFAULT; 36 | 37 | @AliasFor(annotation = Transactional.class, attribute = "timeoutString") 38 | String timeoutString() default ""; 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/service/RobotRestrictions.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import static java.lang.String.format; 4 | import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW; 5 | 6 | import com.example.demo.annotation.ReadTransactional; 7 | import com.example.demo.exception.OperationRestrictedException; 8 | import com.example.demo.repository.RobotRepository; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | import org.springframework.transaction.annotation.Transactional; 12 | 13 | @Service 14 | public class RobotRestrictions { 15 | 16 | @Autowired 17 | private RobotRepository robotRepository; 18 | 19 | @Transactional(readOnly = true) 20 | public void checkSwitchOn(Long serverId) { 21 | innerCheckSwitchOn(serverId); 22 | } 23 | 24 | @Transactional(readOnly = true, propagation = REQUIRES_NEW) 25 | public void checkSwitchOnRequiresNew(Long serverId) { 26 | innerCheckSwitchOn(serverId); 27 | } 28 | 29 | @Transactional(readOnly = true, noRollbackFor = Exception.class) 30 | public void checkSwitchOnNoRollBackFor(Long serverId) { 31 | innerCheckSwitchOn(serverId); 32 | } 33 | 34 | @ReadTransactional 35 | public void checkSwitchOnReadTransactional(Long serverId) { 36 | innerCheckSwitchOn(serverId); 37 | } 38 | 39 | private void innerCheckSwitchOn(Long robotId) { 40 | final var robot = 41 | robotRepository.findById(robotId) 42 | .orElseThrow(); 43 | if (robot.isSwitched()) { 44 | throw new OperationRestrictedException( 45 | format("Robot %s is already switched on", robot.getName()) 46 | ); 47 | } 48 | final var count = robotRepository.countAllByTypeAndIdNot(robot.getType(), robotId); 49 | if (count >= 3) { 50 | throw new OperationRestrictedException( 51 | format("There is already 3 switched on robots of type %s", robot.getType()) 52 | ); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/example/demo/testutils/TestDBFacade.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.testutils; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; 5 | import org.springframework.boot.test.context.TestConfiguration; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.jdbc.core.JdbcTemplate; 8 | import org.springframework.test.jdbc.JdbcTestUtils; 9 | import org.springframework.transaction.support.TransactionTemplate; 10 | 11 | public class TestDBFacade { 12 | 13 | @Autowired 14 | private TestEntityManager testEntityManager; 15 | @Autowired 16 | private TransactionTemplate transactionTemplate; 17 | @Autowired 18 | private JdbcTemplate jdbcTemplate; 19 | 20 | public void cleanDatabase() { 21 | transactionTemplate.execute(status -> { 22 | JdbcTestUtils.deleteFromTables(jdbcTemplate, "robot"); 23 | return null; 24 | }); 25 | } 26 | 27 | public T find(Object id, Class entityClass) { 28 | return transactionTemplate.execute(status -> testEntityManager.find(entityClass, id)); 29 | } 30 | 31 | public void saveAll(TestBuilder... builders) { 32 | transactionTemplate.execute(status -> { 33 | for (TestBuilder b : builders) { 34 | save(b); 35 | } 36 | return null; 37 | }); 38 | } 39 | 40 | public T save(TestBuilder builder) { 41 | return transactionTemplate.execute( 42 | status -> testEntityManager.persistAndFlush(builder.build())); 43 | } 44 | 45 | public TestBuilder persistedOnce(TestBuilder builder) { 46 | return new TestBuilder<>() { 47 | private T entity; 48 | 49 | @Override 50 | public T build() { 51 | if (entity == null) { 52 | entity = save(builder); 53 | } 54 | return entity; 55 | } 56 | }; 57 | } 58 | 59 | @TestConfiguration 60 | public static class Config { 61 | 62 | @Bean 63 | public TestDBFacade testDBFacade() { 64 | return new TestDBFacade(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/example/demo/service/RobotUpdateServiceTestH2TestDataBuilder.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import static com.example.demo.entity.RobotTestBuilder.aRobot; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertThrows; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | import static org.mockito.Mockito.doNothing; 8 | import static org.mockito.Mockito.doThrow; 9 | 10 | import com.example.demo.entity.Robot; 11 | import com.example.demo.exception.OperationRestrictedException; 12 | import com.example.demo.testutils.TestDBFacade; 13 | import org.junit.jupiter.api.BeforeEach; 14 | import org.junit.jupiter.api.Test; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; 17 | import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager; 18 | import org.springframework.boot.test.context.SpringBootTest; 19 | import org.springframework.boot.test.mock.mockito.MockBean; 20 | import org.springframework.context.annotation.Import; 21 | 22 | @SpringBootTest 23 | @AutoConfigureTestDatabase 24 | @AutoConfigureTestEntityManager 25 | @Import(TestDBFacade.Config.class) 26 | class RobotUpdateServiceTestH2TestDataBuilder { 27 | @Autowired 28 | private RobotUpdateService service; 29 | @Autowired 30 | private TestDBFacade db; 31 | @MockBean 32 | private RobotRestrictions robotRestrictions; 33 | 34 | @BeforeEach 35 | void beforeEach() { 36 | db.cleanDatabase(); 37 | } 38 | 39 | @Test 40 | void shouldSwitchOnSuccessfully() { 41 | final var id = db.save(aRobot().switched(false)).getId(); 42 | doNothing().when(robotRestrictions).checkSwitchOn(id); 43 | 44 | service.switchOnRobot(id); 45 | 46 | final var savedServer = db.find(id, Robot.class); 47 | assertTrue(savedServer.isSwitched()); 48 | } 49 | 50 | @Test 51 | void shouldRollbackIfCannotSwitchOn() { 52 | final var id = db.save(aRobot().switched(false)).getId(); 53 | doThrow(new OperationRestrictedException("")).when(robotRestrictions).checkSwitchOn(id); 54 | 55 | assertThrows(OperationRestrictedException.class, () -> service.switchOnRobot(id)); 56 | 57 | final var savedRobot = db.find(id, Robot.class); 58 | assertFalse(savedRobot.isSwitched()); 59 | } 60 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/service/RobotUpdateServiceTestH2.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import static com.example.demo.entity.Robot.Type.DRIVER; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | import static org.junit.jupiter.api.Assertions.assertFalse; 6 | import static org.junit.jupiter.api.Assertions.assertThrows; 7 | import static org.junit.jupiter.api.Assertions.assertTrue; 8 | import static org.mockito.Mockito.doNothing; 9 | import static org.mockito.Mockito.doThrow; 10 | 11 | import com.example.demo.entity.Robot; 12 | import com.example.demo.exception.OperationRestrictedException; 13 | import com.example.demo.repository.RobotRepository; 14 | import java.time.LocalDate; 15 | import org.junit.jupiter.api.BeforeEach; 16 | import org.junit.jupiter.api.Test; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; 19 | import org.springframework.boot.test.context.SpringBootTest; 20 | import org.springframework.boot.test.mock.mockito.MockBean; 21 | 22 | @SpringBootTest 23 | @AutoConfigureTestDatabase 24 | class RobotUpdateServiceTestH2 { 25 | @Autowired 26 | private RobotUpdateService service; 27 | @Autowired 28 | private RobotRepository robotRepository; 29 | @MockBean 30 | private RobotRestrictions robotRestrictions; 31 | 32 | @BeforeEach 33 | void beforeEach() { 34 | robotRepository.deleteAll(); 35 | } 36 | 37 | @Test 38 | void shouldSwitchOnSuccessfully() { 39 | final var robot = new Robot(); 40 | robot.setSwitched(false); 41 | robot.setType(DRIVER); 42 | robot.setName("some_name"); 43 | robotRepository.save(robot); 44 | doNothing().when(robotRestrictions).checkSwitchOn(robot.getId()); 45 | 46 | service.switchOnRobot(robot.getId()); 47 | 48 | final var savedRobot = robotRepository.findById(robot.getId()).orElseThrow(); 49 | assertTrue(savedRobot.isSwitched()); 50 | } 51 | 52 | @Test 53 | void shouldRollbackIfCannotSwitchOn() { 54 | final var robot = new Robot(); 55 | robot.setSwitched(false); 56 | robot.setType(DRIVER); 57 | robot.setName("some_name"); 58 | robotRepository.save(robot); 59 | doThrow(new OperationRestrictedException("")).when(robotRestrictions).checkSwitchOn(robot.getId()); 60 | 61 | assertThrows(OperationRestrictedException.class, () -> service.switchOnRobot(robot.getId())); 62 | 63 | final var savedRobot = robotRepository.findById(robot.getId()).orElseThrow(); 64 | assertFalse(savedRobot.isSwitched()); 65 | } 66 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/service/RobotUpdateServiceTestH2DirtiesContext.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import static com.example.demo.entity.Robot.Type.DRIVER; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertThrows; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | import static org.mockito.Mockito.doNothing; 8 | import static org.mockito.Mockito.doThrow; 9 | import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; 10 | 11 | import com.example.demo.entity.Robot; 12 | import com.example.demo.exception.OperationRestrictedException; 13 | import com.example.demo.repository.RobotRepository; 14 | import org.junit.jupiter.api.Test; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; 17 | import org.springframework.boot.test.context.SpringBootTest; 18 | import org.springframework.boot.test.mock.mockito.MockBean; 19 | import org.springframework.test.annotation.DirtiesContext; 20 | 21 | @SpringBootTest 22 | @AutoConfigureTestDatabase 23 | @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) 24 | class RobotUpdateServiceTestH2DirtiesContext { 25 | @Autowired 26 | private RobotUpdateService service; 27 | @Autowired 28 | private RobotRepository robotRepository; 29 | @MockBean 30 | private RobotRestrictions robotRestrictions; 31 | 32 | @Test 33 | void shouldSwitchOnSuccessfully() { 34 | final var robot = new Robot(); 35 | robot.setSwitched(false); 36 | robot.setType(DRIVER); 37 | robot.setName("some_name"); 38 | robotRepository.save(robot); 39 | doNothing().when(robotRestrictions).checkSwitchOn(robot.getId()); 40 | 41 | service.switchOnRobot(robot.getId()); 42 | 43 | final var savedRobot = robotRepository.findById(robot.getId()).orElseThrow(); 44 | assertTrue(savedRobot.isSwitched()); 45 | } 46 | 47 | @Test 48 | void shouldRollbackIfCannotSwitchOn() { 49 | final var robot = new Robot(); 50 | robot.setSwitched(false); 51 | robot.setType(DRIVER); 52 | robot.setName("some_name"); 53 | robotRepository.save(robot); 54 | doThrow(new OperationRestrictedException("")).when(robotRestrictions) 55 | .checkSwitchOn(robot.getId()); 56 | 57 | assertThrows(OperationRestrictedException.class, () -> service.switchOnRobot(robot.getId())); 58 | 59 | final var savedRobot = robotRepository.findById(robot.getId()).orElseThrow(); 60 | assertFalse(savedRobot.isSwitched()); 61 | } 62 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/service/RobotUpdateServiceTestH2DataJpa.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import static com.example.demo.entity.RobotTestBuilder.aRobot; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertThrows; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | import static org.mockito.Mockito.doNothing; 8 | import static org.mockito.Mockito.doThrow; 9 | 10 | import com.example.demo.entity.Robot; 11 | import com.example.demo.exception.OperationRestrictedException; 12 | import com.example.demo.repository.RobotRepository; 13 | import com.example.demo.testutils.TestDBFacade; 14 | import org.junit.jupiter.api.Disabled; 15 | import org.junit.jupiter.api.Test; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 18 | import org.springframework.boot.test.context.TestConfiguration; 19 | import org.springframework.boot.test.mock.mockito.MockBean; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Import; 22 | 23 | @DataJpaTest 24 | @Import(TestDBFacade.Config.class) 25 | class RobotUpdateServiceTestH2DataJpa { 26 | 27 | @Autowired 28 | private RobotUpdateService service; 29 | @Autowired 30 | private TestDBFacade db; 31 | @MockBean 32 | private RobotRestrictions robotRestrictions; 33 | 34 | @TestConfiguration 35 | static class Config { 36 | 37 | @Bean 38 | public RobotUpdateService service( 39 | RobotRepository robotRepository, 40 | RobotRestrictions robotRestrictions 41 | ) { 42 | return new RobotUpdateService(robotRepository, robotRestrictions); 43 | } 44 | } 45 | 46 | @Test 47 | void shouldSwitchOnSuccessfully() { 48 | final var id = db.save(aRobot().switched(false)).getId(); 49 | doNothing().when(robotRestrictions).checkSwitchOn(id); 50 | 51 | service.switchOnRobot(id); 52 | 53 | final var savedRobot = db.find(id, Robot.class); 54 | assertTrue(savedRobot.isSwitched()); 55 | } 56 | 57 | @Test 58 | @Disabled("Always fails due to default transactional propagation") 59 | void shouldRollbackIfCannotSwitchOn() { 60 | final var id = db.save(aRobot().switched(false)).getId(); 61 | doThrow(new OperationRestrictedException("")).when(robotRestrictions).checkSwitchOn(id); 62 | 63 | assertThrows(OperationRestrictedException.class, () -> service.switchOnRobot(id)); 64 | 65 | final var savedRobot = db.find(id, Robot.class); 66 | assertFalse(savedRobot.isSwitched()); 67 | } 68 | } -------------------------------------------------------------------------------- /src/test/java/com/example/demo/service/RobotUpdateServiceTestH2DataJpaNonTransactional.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import static com.example.demo.entity.RobotTestBuilder.aRobot; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertThrows; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | import static org.mockito.Mockito.doNothing; 8 | import static org.mockito.Mockito.doThrow; 9 | import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; 10 | 11 | import com.example.demo.entity.Robot; 12 | import com.example.demo.exception.OperationRestrictedException; 13 | import com.example.demo.repository.RobotRepository; 14 | import com.example.demo.testutils.TestDBFacade; 15 | import org.junit.jupiter.api.BeforeEach; 16 | import org.junit.jupiter.api.Test; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 19 | import org.springframework.boot.test.context.TestConfiguration; 20 | import org.springframework.boot.test.mock.mockito.MockBean; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.context.annotation.Import; 23 | import org.springframework.transaction.annotation.Transactional; 24 | 25 | @DataJpaTest 26 | @Import(TestDBFacade.Config.class) 27 | @Transactional(propagation = NOT_SUPPORTED) 28 | class RobotUpdateServiceTestH2DataJpaNonTransactional { 29 | 30 | @Autowired 31 | private RobotUpdateService service; 32 | @Autowired 33 | private TestDBFacade db; 34 | @MockBean 35 | private RobotRestrictions robotRestrictions; 36 | 37 | @BeforeEach 38 | void beforeEach() { 39 | db.cleanDatabase(); 40 | } 41 | 42 | @TestConfiguration 43 | static class Config { 44 | 45 | @Bean 46 | public RobotUpdateService service( 47 | RobotRepository robotRepository, 48 | RobotRestrictions robotRestrictions 49 | ) { 50 | return new RobotUpdateService(robotRepository, robotRestrictions); 51 | } 52 | } 53 | 54 | @Test 55 | void shouldSwitchOnSuccessfully() { 56 | final var id = db.save(aRobot().switched(false)).getId(); 57 | doNothing().when(robotRestrictions).checkSwitchOn(id); 58 | 59 | service.switchOnRobot(id); 60 | 61 | final var savedRobot = db.find(id, Robot.class); 62 | assertTrue(savedRobot.isSwitched()); 63 | } 64 | 65 | @Test 66 | void shouldRollbackIfCannotSwitchOn() { 67 | final var id = db.save(aRobot().switched(false)).getId(); 68 | doThrow(new OperationRestrictedException("")).when(robotRestrictions).checkSwitchOn(id); 69 | 70 | assertThrows(OperationRestrictedException.class, () -> service.switchOnRobot(id)); 71 | 72 | final var savedRobot = db.find(id, Robot.class); 73 | assertFalse(savedRobot.isSwitched()); 74 | } 75 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/service/RobotAllowedOperations.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import static com.example.demo.service.OperationStatus.ALLOWED; 4 | import static com.example.demo.service.OperationStatus.RESTRICTED; 5 | import static com.example.demo.service.OperationStatus.ROBOT_IS_ABSENT; 6 | import static java.lang.String.format; 7 | 8 | import com.example.demo.annotation.ReadTransactional; 9 | import com.example.demo.exception.OperationRestrictedException; 10 | import java.util.Collection; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | import java.util.NoSuchElementException; 14 | import java.util.function.Consumer; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.stereotype.Service; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | @Service 22 | public class RobotAllowedOperations { 23 | 24 | private static final Logger LOG = LoggerFactory.getLogger(RobotAllowedOperations.class); 25 | @Autowired 26 | private RobotRestrictions robotRestrictions; 27 | 28 | @Transactional(readOnly = true) 29 | public Map getRobotsSwitchOnStatus(Collection robotIds) { 30 | return innerGetRobotsSwitchOnStatus(robotIds, robotRestrictions::checkSwitchOn); 31 | } 32 | 33 | @Transactional(readOnly = true) 34 | public Map getRobotsSwitchOnStatusRequiresNew( 35 | Collection robotIds 36 | ) { 37 | return innerGetRobotsSwitchOnStatus(robotIds, robotRestrictions::checkSwitchOnRequiresNew); 38 | } 39 | 40 | @Transactional(readOnly = true) 41 | public Map getRobotsSwitchOnStatusNoRollBackFor( 42 | Collection robotIds 43 | ) { 44 | return innerGetRobotsSwitchOnStatus(robotIds, robotRestrictions::checkSwitchOnNoRollBackFor); 45 | } 46 | 47 | @ReadTransactional 48 | public Map getRobotsSwitchOnStatusReadTransactional( 49 | Collection robotIds 50 | ) { 51 | return innerGetRobotsSwitchOnStatus( 52 | robotIds, 53 | robotRestrictions::checkSwitchOnReadTransactional 54 | ); 55 | } 56 | 57 | private Map innerGetRobotsSwitchOnStatus( 58 | Collection robotIds, 59 | Consumer restrictionChecker 60 | ) { 61 | final var result = new HashMap(); 62 | for (Long robotId : robotIds) { 63 | result.put(robotId, getOperationStatus(robotId, restrictionChecker)); 64 | } 65 | return result; 66 | } 67 | 68 | private OperationStatus getOperationStatus(Long robotId, Consumer restrictionChecker) { 69 | try { 70 | restrictionChecker.accept(robotId); 71 | return ALLOWED; 72 | } catch (NoSuchElementException e) { 73 | LOG.debug(format("Server with id %s is absent", robotId), e); 74 | return ROBOT_IS_ABSENT; 75 | } catch (OperationRestrictedException e) { 76 | LOG.debug(format("Server with id %s cannot be switched on", robotId), e); 77 | return RESTRICTED; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/test/java/com/example/demo/service/RobotAllowedOperationsTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | import static com.example.demo.entity.Robot.Type.DRIVER; 4 | import static com.example.demo.entity.Robot.Type.LOADER; 5 | import static com.example.demo.entity.Robot.Type.VACUUM; 6 | import static com.example.demo.entity.RobotTestBuilder.aRobot; 7 | import static com.example.demo.service.OperationStatus.ALLOWED; 8 | import static com.example.demo.service.OperationStatus.RESTRICTED; 9 | import static org.junit.jupiter.api.Assertions.assertEquals; 10 | import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; 11 | 12 | import com.example.demo.testutils.TestDBFacade; 13 | import java.util.Collection; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.function.Function; 17 | import org.junit.jupiter.api.BeforeEach; 18 | import org.junit.jupiter.api.Disabled; 19 | import org.junit.jupiter.api.Test; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 22 | import org.springframework.boot.test.context.TestConfiguration; 23 | import org.springframework.context.annotation.Bean; 24 | import org.springframework.context.annotation.Import; 25 | import org.springframework.transaction.annotation.Transactional; 26 | 27 | @DataJpaTest 28 | @Import(TestDBFacade.Config.class) 29 | @Transactional(propagation = NOT_SUPPORTED) 30 | class RobotAllowedOperationsTest { 31 | 32 | @Autowired 33 | private TestDBFacade db; 34 | @Autowired 35 | private RobotAllowedOperations robotAllowedOperations; 36 | 37 | @BeforeEach 38 | void beforeEach() { 39 | db.cleanDatabase(); 40 | } 41 | 42 | @TestConfiguration 43 | static class Config { 44 | 45 | @Bean 46 | public RobotAllowedOperations serverAllowedOperations() { 47 | return new RobotAllowedOperations(); 48 | } 49 | 50 | @Bean 51 | public RobotRestrictions serverRestrictions() { 52 | return new RobotRestrictions(); 53 | } 54 | } 55 | 56 | @Test 57 | @Disabled("Always fails due to rollback-only behavior") 58 | void shouldNotAllowSomeRobotsToSwitchOn() { 59 | innerShouldNotAllowSomeRobotsToSwitchOn(robotAllowedOperations::getRobotsSwitchOnStatus); 60 | } 61 | 62 | @Test 63 | void shouldNotAllowSomeRobotsToSwitchOnRequiresNew() { 64 | innerShouldNotAllowSomeRobotsToSwitchOn(robotAllowedOperations::getRobotsSwitchOnStatusRequiresNew); 65 | } 66 | 67 | @Test 68 | void shouldNotAllowSomeRobotsToSwitchOnNoRollbackFor() { 69 | innerShouldNotAllowSomeRobotsToSwitchOn(robotAllowedOperations::getRobotsSwitchOnStatusNoRollBackFor); 70 | } 71 | 72 | @Test 73 | void shouldNotAllowSomeRobotsToSwitchOnReadTransactional() { 74 | innerShouldNotAllowSomeRobotsToSwitchOn(robotAllowedOperations::getRobotsSwitchOnStatusReadTransactional); 75 | } 76 | 77 | private void innerShouldNotAllowSomeRobotsToSwitchOn( 78 | Function, Map> function) { 79 | final var driver = db.save( 80 | aRobot().switched(true).type(DRIVER) 81 | ); 82 | final var loader = db.save( 83 | aRobot().switched(false).type(LOADER) 84 | ); 85 | final var vacuumTemplate = aRobot().switched(false).type(VACUUM); 86 | final var vacuum = db.save(vacuumTemplate); 87 | db.saveAll( 88 | vacuumTemplate.switched(true), 89 | vacuumTemplate.switched(true), 90 | vacuumTemplate.switched(true) 91 | ); 92 | final var robotsIds = List.of(driver.getId(), loader.getId(), vacuum.getId()); 93 | 94 | final var operations = function.apply( 95 | robotsIds 96 | ); 97 | 98 | assertEquals(RESTRICTED, operations.get(driver.getId())); 99 | assertEquals(ALLOWED, operations.get(loader.getId())); 100 | assertEquals(RESTRICTED, operations.get(vacuum.getId())); 101 | } 102 | 103 | 104 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | --------------------------------------------------------------------------------