<%#
 Copyright 2013-2023 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.service;

import <%= packageName %>.IntegrationTest;
import <%= packageName %>.config.Constants;
<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) && authenticationTypeSession && !reactive) { _%>
import <%= packageName %>.domain.PersistentToken;
<%_ } _%>
<%_ if (!databaseTypeNo) { _%>
import <%= user.entityAbsoluteClass %>;
<%_ } _%>
<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) && authenticationTypeSession && !reactive) { _%>
import <%= packageName %>.repository.PersistentTokenRepository;
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>
import <%= packageName %>.repository.search.UserSearchRepository;
<%_ } _%>
<%_ if (!databaseTypeNo) { _%>
import <%= packageName %>.repository.UserRepository;
<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
import <%= packageName %>.security.AuthoritiesConstants;
import <%= packageName %>.service.dto.AuthorityDTO;
<%_ } _%>
import <%= packageName %>.service.dto.<%= user.adminUserDto %>;
<%_ if (!authenticationTypeOauth2 && (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase)) { _%>

import tech.jhipster.security.RandomUtil;
<%_ } _%>

<%_ if (!authenticationTypeOauth2) { _%>
import org.apache.commons.lang3.RandomStringUtils;
<%_ } _%>
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
<%_ if (searchEngineElasticsearch) { _%>
import org.springframework.boot.test.mock.mockito.SpyBean;
<%_ } _%>
<%_ if (databaseTypeSql && !reactive && !authenticationTypeOauth2) { _%>
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.auditing.AuditingHandler;
import org.springframework.data.auditing.DateTimeProvider;
<%_ } _%>
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
  <%_ if (ormTool !== 'mybatis') { _%>
    <%_ if (!reactive) { _%>
import org.springframework.data.domain.Page;
    <%_ } _%>
import org.springframework.data.domain.PageRequest;
  <%_ } _%>
<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
<%_ } _%>
<%_ if (databaseTypeCouchbase) { _%>
import org.springframework.security.test.context.support.WithAnonymousUser;
<%_ } _%>
<%_ if (databaseTypeSql && !reactive) { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
<%_ if (searchEngineElasticsearch && reactive) { _%>
import reactor.core.publisher.Mono;
<%_ } _%>

<%_ if (!authenticationTypeOauth2 && (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase)) { _%>
import java.time.Instant;
import java.time.temporal.ChronoUnit;
<%_ } _%>
<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) && authenticationTypeSession && !reactive) { _%>
import java.time.LocalDate;
<%_ } _%>
<%_ if (databaseTypeSql && reactive) { _%>
import java.time.ZoneOffset;
<%_ } _%>
<%_ if (databaseTypeSql && !authenticationTypeOauth2) { _%>
import java.time.ZonedDateTime;
import java.time.LocalDateTime;
<%_ } _%>
<%_ if (!authenticationTypeOauth2 || reactive) { _%>
import java.util.List;
<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
<%_ } _%>
<%_ if (!authenticationTypeOauth2 && (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase)) { _%>
import java.util.Optional;
<%_ } _%>
<%_ if (databaseTypeCassandra) { _%>
import java.util.UUID;
<%_ } _%>

<%_ if (databaseTypeCouchbase) { _%>
import static <%= packageName %>.web.rest.TestUtil.mockAuthentication;
<%_ } _%>
import static org.assertj.core.api.Assertions.assertThat;
<%_ if (searchEngineElasticsearch) { _%>
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
<%_ } _%>
<%_ if (reactive && searchEngineElasticsearch) { _%>
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.any;
<%_ } _%>
<%_ if (databaseTypeSql && !reactive && !authenticationTypeOauth2) { _%>
import static org.mockito.Mockito.when;
<%_ } _%>

/**
 * Integration tests for {@link UserService}.
 */
@IntegrationTest
<%_ if (databaseTypeSql && !reactive) { _%>
@Transactional
<%_ } _%>
class UserServiceIT {

    private static final String DEFAULT_LOGIN = "johndoe";

    private static final String DEFAULT_EMAIL = "johndoe@localhost";

    private static final String DEFAULT_FIRSTNAME = "john";

    private static final String DEFAULT_LASTNAME = "doe";

<%_ if (!databaseTypeCassandra) { _%>
    private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";

<%_ } _%>
    private static final String DEFAULT_LANGKEY = "dummy";

<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) && authenticationTypeSession && !reactive) { _%>
    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

<%_ } _%>
<%_ if (!databaseTypeNo) { _%>
    @Autowired
    private UserRepository userRepository;

<%_ } _%>
    @Autowired
    private UserService userService;
<%_ if (searchEngineElasticsearch) { _%>

    /**
     * This repository is mocked in the <%= packageName %>.repository.search test package.
     *
     * @see <%= packageName %>.repository.search.UserSearchRepositoryMockConfiguration
     */
    @SpyBean
    private UserSearchRepository spiedUserSearchRepository;
<%_ } _%>
<%_ if (databaseTypeSql && !reactive && !authenticationTypeOauth2) { _%>

    @Autowired
    private AuditingHandler auditingHandler;

    @MockBean
    private DateTimeProvider dateTimeProvider;
<%_ } _%>
    <%_ if (!databaseTypeNo) { _%>

    private <%= user.persistClass %> user;
    <%_ } _%>

<%_ if (authenticationTypeOauth2) { _%>
    private Map<String, Object> userDetails;

<%_ } _%>
    @BeforeEach
    public void init() {
<%_ if (databaseTypeCouchbase) { _%>
        mockAuthentication();
<%_ } _%>
<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) && authenticationTypeSession && !reactive) { _%>
        persistentTokenRepository.deleteAll();
<%_ } _%>
<%_ if (databaseTypeSql && reactive) { _%>
        userRepository.deleteAllUserAuthorities().block();
<%_ } _%>
<%_ if ((reactive && !databaseTypeNo) || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCassandra || databaseTypeCouchbase) { _%>
        userRepository.deleteAll()<% if (reactive) { %>.block()<% } %>;
<%_ } _%>
<%_ if (!databaseTypeNo) { _%>
        user = new <%= user.persistClass %>();
  <%_ if (databaseTypeCassandra) { _%>
        user.setId(UUID.randomUUID().toString());
  <%_ } _%>
        user.setLogin(DEFAULT_LOGIN);
  <%_ if (!authenticationTypeOauth2) { _%>
        user.setPassword(RandomStringUtils.randomAlphanumeric(60));
  <%_ } _%>
        user.setActivated(true);
        user.setEmail(DEFAULT_EMAIL);
        user.setFirstName(DEFAULT_FIRSTNAME);
        user.setLastName(DEFAULT_LASTNAME);
  <%_ if (!databaseTypeCassandra) { _%>
        user.setImageUrl(DEFAULT_IMAGEURL);
  <%_ } _%>
        user.setLangKey(DEFAULT_LANGKEY);
  <%_ if (databaseTypeSql && reactive) { _%>
        user.setCreatedBy(Constants.SYSTEM);
  <%_ } _%>
<%_ } _%>
<%_ if (authenticationTypeOauth2) { _%>

        userDetails = new HashMap<>();
        userDetails.put("sub", DEFAULT_LOGIN);
        userDetails.put("email", DEFAULT_EMAIL);
        userDetails.put("given_name", DEFAULT_FIRSTNAME);
        userDetails.put("family_name", DEFAULT_LASTNAME);
  <%_ if (!databaseTypeCassandra) { _%>
        userDetails.put("picture", DEFAULT_IMAGEURL);
  <%_ } _%>
<%_ } _%>
<%_ if (databaseTypeSql && !reactive && !authenticationTypeOauth2) { _%>

        when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now()));
        auditingHandler.setDateTimeProvider(dateTimeProvider);
<%_ } _%>
    }
<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) && authenticationTypeSession && !reactive) { _%>

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void testRemoveOldPersistentTokens() {
        userRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql) { %>AndFlush<% } %><% } else { %>insert<% } %>(user);
        int existingCount = persistentTokenRepository.findByUser(user).size();
        LocalDate today = LocalDate.now();
        generateUserToken(user, "1111-1111", today);
        generateUserToken(user, "2222-2222", today.minusDays(32));
        assertThat(persistentTokenRepository.findByUser(user)).hasSize(existingCount + 2);
        userService.removeOldPersistentTokens();
        assertThat(persistentTokenRepository.findByUser(user)).hasSize(existingCount + 1);
    }
<%_ } _%>
<%_ if (!authenticationTypeOauth2 && (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase)) { _%>

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void assertThatUserMustExistToResetPassword() {
        userRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %><% } else { %>insert<% } %>(user)<% if (reactive) { %>.block()<% } %>;
        Optional<<%= user.persistClass %>> maybeUser = userService.requestPasswordReset("invalid.login@localhost")<% if (reactive) { %>.blockOptional()<% } %>;
        assertThat(maybeUser).isNotPresent();

        maybeUser = userService.requestPasswordReset(user.getEmail())<% if (reactive) { %>.blockOptional()<% } %>;
        assertThat(maybeUser).isPresent();
        assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail());
        assertThat(maybeUser.orElse(null).getResetDate()).isNotNull();
        assertThat(maybeUser.orElse(null).getResetKey()).isNotNull();
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void assertThatOnlyActivatedUserCanRequestPasswordReset() {
        user.setActivated(false);
        userRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %><% } else { %>insert<% } %>(user)<% if (reactive) { %>.block()<% } %>;

        Optional<<%= user.persistClass %>> maybeUser = userService.requestPasswordReset(user.getLogin())<% if (reactive) { %>.blockOptional()<% } %>;
        assertThat(maybeUser).isNotPresent();
        userRepository.delete<%= ormTool === 'mybatis' ? 'ById': ''%>(user<%= ormTool === 'mybatis' ? '.getId()': ''%>)<% if (reactive) { %>.block()<% } %>;
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void assertThatResetKeyMustNotBeOlderThan24Hours() {
        Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
        String resetKey = RandomUtil.generateResetKey();
        user.setActivated(true);
        user.setResetDate(daysAgo);
        user.setResetKey(resetKey);
        userRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %><% } else { %>insert<% } %>(user)<% if (reactive) { %>.block()<% } %>;

        Optional<<%= user.persistClass %>> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey())<% if (reactive) { %>.blockOptional()<% } %>;
        assertThat(maybeUser).isNotPresent();
        userRepository.delete<%= ormTool === 'mybatis' ? 'ById': ''%>(user<%= ormTool === 'mybatis' ? '.getId()': ''%>)<% if (reactive) { %>.block()<% } %>;
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void assertThatResetKeyMustBeValid() {
        Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
        user.setActivated(true);
        user.setResetDate(daysAgo);
        user.setResetKey("1234");
        userRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %><% } else { %>insert<% } %>(user)<% if (reactive) { %>.block()<% } %>;

        Optional<<%= user.persistClass %>> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey())<% if (reactive) { %>.blockOptional()<% } %>;
        assertThat(maybeUser).isNotPresent();
        userRepository.delete<%= ormTool === 'mybatis' ? 'ById': ''%>(user<%= ormTool === 'mybatis' ? '.getId()': ''%>)<% if (reactive) { %>.block()<% } %>;
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void assertThatUserCanResetPassword() {
        String oldPassword = user.getPassword();
        Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS);
        String resetKey = RandomUtil.generateResetKey();
        user.setActivated(true);
        user.setResetDate(daysAgo);
        user.setResetKey(resetKey);
        userRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %><% } else { %>insert<% } %>(user)<% if (reactive) { %>.block()<% } %>;

        Optional<<%= user.persistClass %>> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey())<% if (reactive) { %>.blockOptional()<% } %>;
        assertThat(maybeUser).isPresent();
        assertThat(maybeUser.orElse(null).getResetDate()).isNull();
        assertThat(maybeUser.orElse(null).getResetKey()).isNull();
        assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword);

        userRepository.delete<%= ormTool === 'mybatis' ? 'ById': ''%>(user<%= ormTool === 'mybatis' ? '.getId()': ''%>)<% if (reactive) { %>.block()<% } %>;
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void assertThatNotActivatedUsersWithNotNullActivationKeyCreatedBefore3DaysAreDeleted() {
        ZonedDateTime now = ZonedDateTime.now();
  <%_ if (databaseTypeSql && !reactive) { _%>
        when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS)));
  <%_ } _%>
        user.setActivated(false);
        user.setActivationKey(RandomStringUtils.random(20));
  <%_ if (ormTool !== 'mybatis') { _%>
        <%= user.persistClass %> dbUser = userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>;
  <%_ } else { _%>
        userRepository.insert(user)<% if (reactive) { %>.block()<% } %>;
        User dbUser = userRepository.selectById(user.getId());
  <%_ } _%>
        dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
        userRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %><% } else { %>insert<% } %>(user)<% if (reactive) { %>.block()<% } %>;
  <%_ if (databaseTypeSql && reactive) { _%>
        LocalDateTime threeDaysAgo = LocalDateTime.ofInstant(now.minus(3, ChronoUnit.DAYS), ZoneOffset.UTC);
  <%_ } else { _%>
        ZonedDateTime threeDaysAgo = now.minus(3, ChronoUnit.DAYS);
  <%_ } _%>
        List<<%= user.persistClass %>> users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo)<% if (reactive) { %>
            .collectList().block()<% } %>;
        assertThat(users).isNotEmpty();
        userService.removeNotActivatedUsers();
        users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo)<% if (reactive) { %>
            .collectList().block()<% } %>;
        assertThat(users).isEmpty();
  <%_ if (searchEngineElasticsearch) { _%>

        // Verify Elasticsearch mock
        verify(spiedUserSearchRepository, times(1)).delete<% if (!reactive) { %>FromIndex<% } %>(user);
  <%_ } _%>
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void assertThatNotActivatedUsersWithNullActivationKeyCreatedBefore3DaysAreNotDeleted() {
        ZonedDateTime now = ZonedDateTime.now();
  <%_ if (databaseTypeSql && !reactive) { _%>
        when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS)<% if (databaseTypeSql && reactive) { %>.atOffset(ZoneOffset.UTC)<% } %>));
  <%_ } _%>
        user.setActivated(false);
  <%_ if (ormTool !== 'mybatis') { _%>
        <%= user.persistClass %> dbUser = userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(user)<% if (reactive) { %>.block()<% } %>;
  <%_ } else { _%>
        userRepository.insert(user)<% if (reactive) { %>.block()<% } %>;
        User dbUser = userRepository.selectById(user.getId());
  <%_ } _%>
        dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
        userRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %><% } else { %>insert<% } %>(user)<% if (reactive) { %>.block()<% } %>;
  <%_ if (databaseTypeSql && reactive) { _%>
        LocalDateTime threeDaysAgo = LocalDateTime.ofInstant(now.minus(3, ChronoUnit.DAYS), ZoneOffset.UTC);
  <%_ } else { _%>
        ZonedDateTime threeDaysAgo = now.minus(3, ChronoUnit.DAYS);
  <%_ } _%>
        List<<%= user.persistClass %>> users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo)<% if (reactive) { %>
            .collectList().block()<% } %>;
        assertThat(users).isEmpty();
        userService.removeNotActivatedUsers();
        Optional<<%= user.persistClass %>> maybeDbUser = userRepository.findById(dbUser.getId())<% if (reactive) { %>.blockOptional()<% } %>;
        assertThat(maybeDbUser).contains(dbUser);
  <%_ if (searchEngineElasticsearch) { _%>

        // Verify Elasticsearch mock
        verify(spiedUserSearchRepository, never()).delete<% if (!reactive) { %>FromIndex<% } %>(user);
  <%_ } _%>
    }
<%_ } _%>
<%_ if ((databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) && authenticationTypeSession && !reactive) { _%>

    private void generateUserToken(<%= user.persistClass %> user, String tokenSeries, LocalDate localDate) {
        PersistentToken token = new PersistentToken();
        token.setSeries(tokenSeries);<% if (databaseTypeCouchbase) { %>
        token.setLogin(user.getLogin());<% } else { %>
        token.setUser(user);<% } %>
        token.setTokenValue(tokenSeries + "-data");
        token.setTokenDate(localDate);
        token.setIpAddress("127.0.0.1");
        token.setUserAgent("Test agent");
        persistentTokenRepository.<% if (ormTool !== 'mybatis') { %>save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %><% } else { %>insert<% } %>(token);
    }
<%_ } _%>

<%_ if (authenticationTypeOauth2) { _%>
    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
   public void testDefaultUserDetails() {
        OAuth2AuthenticationToken authentication = createMockOAuth2AuthenticationToken(userDetails);
        <%= user.adminUserDto %> userDTO = userService.getUserFromAuthentication(authentication)<% if (reactive) { %>.block()<% } %>;

        assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN);
        assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
        assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME);
        assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL);
        assertThat(userDTO.isActivated()).isTrue();
        assertThat(userDTO.getLangKey()).isEqualTo(Constants.DEFAULT_LANGUAGE);
        assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
        assertThat(userDTO.getAuthorities().stream().map(AuthorityDTO::getCode)).contains(AuthoritiesConstants.ANONYMOUS);
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void testUserDetailsWithUsername() {
        userDetails.put("preferred_username", "TEST");

        OAuth2AuthenticationToken authentication = createMockOAuth2AuthenticationToken(userDetails);
        <%= user.adminUserDto %> userDTO = userService.getUserFromAuthentication(authentication)<% if (reactive) { %>.block()<% } %>;

        assertThat(userDTO.getLogin()).isEqualTo("test");
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void testUserDetailsWithLangKey() {
        userDetails.put("langKey", DEFAULT_LANGKEY);
        userDetails.put("locale", "en-US");

        OAuth2AuthenticationToken authentication = createMockOAuth2AuthenticationToken(userDetails);
        <%= user.adminUserDto %> userDTO = userService.getUserFromAuthentication(authentication)<% if (reactive) { %>.block()<% } %>;

        assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void testUserDetailsWithLocale() {
        userDetails.put("locale", "it-IT");

        OAuth2AuthenticationToken authentication = createMockOAuth2AuthenticationToken(userDetails);
        <%= user.adminUserDto %> userDTO = userService.getUserFromAuthentication(authentication)<% if (reactive) { %>.block()<% } %>;

        assertThat(userDTO.getLangKey()).isEqualTo("it");
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void testUserDetailsWithUSLocaleUnderscore() {
        userDetails.put("locale", "en_US");

        OAuth2AuthenticationToken authentication = createMockOAuth2AuthenticationToken(userDetails);
        <%= user.adminUserDto %> userDTO = userService.getUserFromAuthentication(authentication)<% if (reactive) { %>.block()<% } %>;

        assertThat(userDTO.getLangKey()).isEqualTo("en");
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void testUserDetailsWithUSLocaleDash() {
        userDetails.put("locale", "en-US");

        OAuth2AuthenticationToken authentication = createMockOAuth2AuthenticationToken(userDetails);
        <%= user.adminUserDto %> userDTO = userService.getUserFromAuthentication(authentication)<% if (reactive) { %>.block()<% } %>;

        assertThat(userDTO.getLangKey()).isEqualTo("en");
    }

    private OAuth2AuthenticationToken createMockOAuth2AuthenticationToken(Map<String, Object> userDetails) {
        Collection<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities);
        usernamePasswordAuthenticationToken.setDetails(userDetails);
        OAuth2User user = new DefaultOAuth2User(authorities, userDetails, "sub");

        return new OAuth2AuthenticationToken(user, authorities, "oidc");
    }
<%_ } _%>
}
