Skip to content

Commit

Permalink
#813 - added @transactional in tests where it is required. removed re…
Browse files Browse the repository at this point in the history
…dundant @transactional from prod code.
  • Loading branch information
petmongrels committed Nov 8, 2024
1 parent 0a4f644 commit b882689
Show file tree
Hide file tree
Showing 50 changed files with 86 additions and 35 deletions.
2 changes: 1 addition & 1 deletion avni-server-api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ dependencies {
implementation "com.zaxxer:HikariCP"
implementation "org.apache.poi:poi:3.16-beta2"
implementation "org.apache.poi:poi-ooxml:3.16-beta2"
implementation 'org.apache.httpcomponents:httpclient'
implementation 'org.apache.httpcomponents.client5:httpclient5:5.2.3'
implementation 'com.auth0:jwks-rsa:0.3.0'
implementation 'com.auth0:java-jwt:3.3.0'
// implementation(group: 'org.hibernate', name: 'hibernate-search-orm', version: '5.9.2.Final') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.avni.messaging.service.MessagingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
Expand All @@ -18,6 +19,7 @@ public ManualMessageController(MessagingService messagingService) {
}

@RequestMapping(value = "/web/scheduleManualMessage", method = RequestMethod.POST)
@Transactional
public ResponseEntity.BodyBuilder save(@RequestBody ManualMessageContract manualMessageContract) {
messagingService.scheduleManualMessage(manualMessageContract.getReceiverId(),
manualMessageContract.getReceiverType(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ public void onUserEntitySave(Long userId, User createdBy) throws RuleExecutionEx
}
}

@Transactional
public Page<MessageRule> findByEntityTypeAndEntityTypeId(EntityType entityType, Long entityTypeId, Pageable pageable) {
return messageRuleRepository.findByEntityTypeAndEntityTypeId(entityType, entityTypeId, pageable);
}
Expand Down Expand Up @@ -162,7 +161,6 @@ public void sendMessages(Duration duration) {
requests.forEach(this::sendMessage);
}

@Transactional
public void scheduleManualMessage(String receiverId, ReceiverType receiverType, String messageTemplateId, String[] parameters, DateTime scheduledDateTime) {
ManualMessage manualMessage = new ManualMessage(messageTemplateId, parameters);
manualMessage.assignUUIDIfRequired();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ default boolean isEntityChanged(SyncParameters syncParameters) {
) > 0;
}

@Transactional
@Modifying(clearAutomatically = true)
@Query(value = "update program_enrolment enl set " +
"address_id = :addressId, " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class AbstractEncounter extends SyncAttributeEntity {
private ObservationCollection observations;

@Column(name = ColumnNames.EncounterCancelDateTime)
private DateTime cancelDateTime;
private Instant cancelDateTime;

@Column(name = ColumnNames.EncounterCancelObservations)
@Type(value = ObservationCollectionUserType.class)
Expand Down Expand Up @@ -114,15 +114,15 @@ public void setMaxVisitDateTime(DateTime maxVisitDateTime) {
}

public DateTime getCancelDateTime() {
return cancelDateTime;
return DateTimeUtil.toJodaDateTime(cancelDateTime);
}

public boolean isCancelled() {
return cancelDateTime != null;
}

public void setCancelDateTime(DateTime cancelDateTime) {
this.cancelDateTime = cancelDateTime;
this.cancelDateTime = DateTimeUtil.toInstant(cancelDateTime);
}

public ObservationCollection getCancelObservations() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import org.hibernate.proxy.LazyInitializer;

import jakarta.persistence.*;

import java.util.Objects;
import java.util.UUID;

@MappedSuperclass
Expand Down Expand Up @@ -74,10 +76,10 @@ public static boolean equals(IdHolder a, Object other) {

IdHolder otherIdHolder = lazyInitializer2 == null ? (IdHolder) other : (IdHolder) lazyInitializer2.getImplementation();

if (otherIdHolder.getId() == null && a.getId() == null && otherIdHolder.getUuid() == null && a.getUuid() == null) return otherIdHolder == a;
if (a.getId() != null && Objects.equals(a.getId(), otherIdHolder.getId())) return true;
if (a.getUuid() != null && Objects.equals(a.getUuid(), otherIdHolder.getUuid())) return true;

if (a.getId() != null ? !a.getId().equals(otherIdHolder.getId()) : otherIdHolder.getId() != null) return false;
return a.getUuid() != null ? a.getUuid().equals(otherIdHolder.getUuid()) : otherIdHolder.getUuid() == null;
return false;
}

@Override
Expand All @@ -86,5 +88,4 @@ public int hashCode() {
result = 31 * result + (uuid != null ? uuid.hashCode() : 0);
return result;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public void addInterceptors(InterceptorRegistry registry) {
}

@Bean
public ObjectMapper myObjectMapper() {
public ObjectMapper objectMapper() {
return ObjectMapperSingleton.getObjectMapper();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.avni.server.util.ObjectMapperSingleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
Expand All @@ -18,8 +19,7 @@

@Service
public class MetadataBundleAndFileHandler {

private static final ObjectMapper objectMapper = new ObjectMapper();
private static final ObjectMapper objectMapper = ObjectMapperSingleton.getObjectMapper();

protected File extractZip(MultipartFile zipFile) throws IOException {
File tempDir = Files.createTempDirectory("metadata-zip").toFile();
Expand Down Expand Up @@ -77,7 +77,7 @@ protected Map<String, Map<String, Object>> parseJsonFiles(List<File> files, File

Map<String, Object> jsonMapFile = new HashMap<>();
if (jsonContent.toString().trim().startsWith("[")) {
List<Map<String, Object>> jsonArray = objectMapper.readValue(jsonContent.toString(), new TypeReference<List<Map<String, Object>>>() {});
List<Map<String, Object>> jsonArray = ObjectMapperSingleton.getObjectMapper().readValue(jsonContent.toString(), new TypeReference<List<Map<String, Object>>>() {});
for (Map<String, Object> jsonObject : jsonArray) {
String uuid = (String) jsonObject.get("uuid");
if (uuid != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ private User createUpdateUser(User user) {
return savedUser;
}

@Transactional
public void addToDefaultUserGroup(User user) {
if (user.getOrganisationId() != null) { //Not a super-admin
Group group = groupRepository.findByNameAndOrganisationId(Group.Everyone, user.getOrganisationId());
Expand Down Expand Up @@ -130,7 +129,6 @@ public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) {
return userRepository.existsByLastModifiedDateTimeGreaterThan(DateTimeUtil.toInstant(lastModifiedDateTime));
}

@Transactional
public User findByUuid(String uuid) {
return userRepository.findByUuid(uuid);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ private void addToSyncAttributes(String st, List<ConceptContract> syncAttributes
syncAttributes.add(ConceptContract.create(concept));
}

@Transactional
public LinkedHashMap<String, Object> searchSubjects(SubjectSearchRequest subjectSearchRequest) {
List<Map<String, Object>> searchResults = subjectSearchRepository.search(subjectSearchRequest, new SubjectAssignmentSearchQueryBuilder());
List<Long> subjectIds = searchResults.stream().map(s -> Long.parseLong(s.get("id").toString())).collect(Collectors.toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ public boolean isNonScopeEntityChanged(DateTime lastModifiedDateTime) {
return menuItemRepository.existsByLastModifiedDateTimeGreaterThan(lastModifiedDateTime);
}

@Transactional
public List<MenuItem> findAll() {
return menuItemRepository.findAll();
}
Expand All @@ -36,12 +35,10 @@ public MenuItem save(MenuItem menuItem) {
return menuItemRepository.save(menuItem);
}

@Transactional
public MenuItem find(String uuid) {
return menuItemRepository.findByUuid(uuid);
}

@Transactional
public MenuItem find(Long id) {
return menuItemRepository.findEntity(id);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
public final class ObjectMapperSingleton {
private static final ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JodaModule())
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

private ObjectMapperSingleton() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import jakarta.transaction.Transactional;
import org.avni.messaging.contract.glific.GlificAuth;
import org.avni.messaging.contract.glific.GlificMessageTemplateResponse;
import org.avni.messaging.contract.glific.GlificResponse;
Expand All @@ -26,6 +27,7 @@
@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = {"/test-data.sql"})
@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@Transactional
public class GlificRestClientTest extends AbstractControllerIntegrationTest {
private String SAMPLE_AUTH_RESPONSE = "{\"data\":{\"access_token\":\"SFMyNTY.YjQ2M2MzMmMtNGZlOC00OTEyLWIzYTEtZmRhZTRkOGQ1ZTIx.3TjKqpElrD5N2ffGHEAFX91cyp7zwoTztYR8p1jwwgA\",\"renewal_token\":\"SFMyNTY.MjYxODllMTgtNDM1OC00YjJjLTlmN2MtOTA5MzMwYzM3ZjA2.dDigSwftcGFGHu4o9MwkASp2KqH6eitp1aRmeYSgi5M\",\"token_expiry_time\":\"2022-10-13T21:42:33.342529Z\"}}";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.avni.server.dao.UserRepository;
import org.avni.server.domain.User;
import org.avni.server.framework.security.UserContextHolder;
import org.avni.server.util.ObjectMapperSingleton;
import org.avni.server.web.TestWebContextService;
import org.junit.After;
import org.junit.Before;
Expand Down Expand Up @@ -49,7 +50,7 @@ public abstract class AbstractControllerIntegrationTest {
@Autowired
private TestWebContextService testWebContextService;

protected static ObjectMapper mapper = new ObjectMapper();
protected static ObjectMapper mapper = ObjectMapperSingleton.getObjectMapper();

@PersistenceContext
private EntityManager em;
Expand All @@ -66,10 +67,14 @@ public void setUp() throws Exception {

@After
public void teardown() {
UserContextHolder.clear();
template.getRestTemplate().setInterceptors(new ArrayList<>());
testWebContextService.setRoles();
em.getEntityManagerFactory().getCache().evictAll();
try {
em.createNativeQuery("reset role;").executeUpdate();
} catch (Exception ignored) {
}
UserContextHolder.clear();
}

protected void post(String path, Object json) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.avni.server.dao;

import jakarta.transaction.Transactional;
import org.avni.server.application.Subject;
import org.avni.server.common.AbstractControllerIntegrationTest;
import org.avni.server.domain.ApprovalStatus;
Expand All @@ -23,6 +24,7 @@

@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@Transactional
public class EntityApprovalStatusRepositoryIntegrationTest extends AbstractControllerIntegrationTest {
@Autowired
private TestDataSetupService testDataSetupService;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.avni.server.dao;

import jakarta.transaction.Transactional;
import org.avni.server.common.AbstractControllerIntegrationTest;
import org.avni.server.domain.AddressLevel;
import org.avni.server.domain.factory.AddressLevelTypeBuilder;
Expand All @@ -13,6 +14,7 @@
import static org.assertj.core.api.Assertions.assertThat;

@Sql({"/test-data.sql"})
@Transactional
public class LocationRepositoryIntegrationTest extends AbstractControllerIntegrationTest {

@Autowired
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.avni.server.dao;

import jakarta.transaction.Transactional;
import org.avni.server.common.AbstractControllerIntegrationTest;
import org.avni.server.dao.ImplementationRepository;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

@Transactional
public class OrganisationRepositoryIntegrationTest extends AbstractControllerIntegrationTest {
@Autowired
private ImplementationRepository implementationRepository;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.avni.server.dao;

import jakarta.transaction.Transactional;
import org.avni.server.common.AbstractControllerIntegrationTest;
import org.avni.server.domain.*;
import org.avni.server.domain.factory.UserBuilder;
Expand Down Expand Up @@ -36,6 +37,7 @@ public class ProgramEnrolmentRepositoryIntegrationTest extends AbstractControlle
private ProgramEnrolmentRepository programEnrolmentRepository;

@Test
@Transactional
public void updateSyncAttributesForIndividual_should_update_last_modified_datetime() throws Exception {
TestDataSetupService.TestOrganisationData organisationData = testDataSetupService.setupOrganisation();
TestDataSetupService.TestCatchmentData catchmentData = testDataSetupService.setupACatchment();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;


public class QueryRepositoryTest extends AbstractControllerIntegrationTest {

@Autowired
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.avni.server.dao;

import jakarta.transaction.Transactional;
import org.avni.server.common.AbstractControllerIntegrationTest;
import org.avni.server.dao.sync.SyncEntityName;
import org.avni.server.domain.*;
Expand Down Expand Up @@ -32,6 +33,7 @@

@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@Transactional
public class SubjectMigrationIntegrationTest extends AbstractControllerIntegrationTest {
@Autowired
private TestDataSetupService testDataSetupService;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.avni.server.dao;

import jakarta.transaction.Transactional;
import org.avni.server.common.AbstractControllerIntegrationTest;
import org.avni.server.domain.accessControl.PrivilegeType;
import org.avni.server.framework.security.UserContextHolder;
Expand All @@ -11,6 +12,7 @@
import static org.junit.Assert.assertTrue;

@Sql({"/test-data.sql"})
@Transactional
public class UserRepositoryTest extends AbstractControllerIntegrationTest {
@Autowired
private UserRepository userRepository;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.avni.server.dao.accessControl;

import jakarta.transaction.Transactional;
import org.avni.server.common.AbstractControllerIntegrationTest;
import org.avni.server.dao.PrivilegeRepository;
import org.avni.server.domain.accessControl.Privilege;
Expand All @@ -17,6 +18,7 @@

@Sql(scripts = {"/test-data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@Transactional
public class PrivilegeRepositoryTest extends AbstractControllerIntegrationTest {
@Autowired
private PrivilegeRepository privilegeRepository;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.avni.server.dao.application;

import jakarta.transaction.Transactional;
import org.avni.server.common.AbstractControllerIntegrationTest;
import org.avni.server.dao.application.FormElementRepository;
import org.joda.time.DateTime;
Expand All @@ -19,6 +20,7 @@

@Sql(scripts = {"/test-data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@Transactional
public class FormElementRepositoryTest extends AbstractControllerIntegrationTest {
@Autowired
private FormElementRepository formElementRepository;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ private void tryFailedFormMappingSave(FormMapping formMapping) {
formMappingRepository.saveFormMapping(formMapping);
fail("Successfully saved form mapping");
} catch (JpaSystemException ignored) {
ignored.printStackTrace();
// ignored.printStackTrace();
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.avni.server.importer.batch.csv.writer;

import jakarta.transaction.Transactional;
import org.avni.server.application.*;
import org.avni.server.dao.LocationRepository;
import org.avni.server.dao.application.FormRepository;
Expand All @@ -24,6 +25,7 @@

@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(value = {"/tear-down.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@Transactional
public class BulkLocationEditorIntegrationTest extends BaseCSVImportTest {
@Autowired
private TestDataSetupService testDataSetupService;
Expand Down
Loading

0 comments on commit b882689

Please sign in to comment.