Модульный тест Grails Домен класса с мультитенантом - PullRequest
0 голосов
/ 29 апреля 2020

Я не могу выполнить модульное тестирование класса домена Grails для Multitenant. Я получаю

rg.spockframework.runtime.ConditionFailedWithExceptionError at AccountSpe c. groovy: 26 Вызвано: org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException в AccountSpe c. 1014 *: 26

 package crm

    import grails.gorm.MultiTenant
    import usermanagement.User

    class Account  implements MultiTenant<Account> {
        String avatar
        String tenantId
        String name
        String description
        Date establishedDate
        String email
        String mobile
        String website
        String fax
        Date dateCreated
        Date lastUpdated
        User user

        static constraints = {
            avatar nullable:true, blank:true
            name unique: 'tenantId'
            description nullable: true, blank: true
            establishedDate nullable: true, blank: true
            fax nullable: true, blank: true
            email unique:'tenantId',email: true
            website unique:'tenantId',nullable: true, blank: true

        }
    }

Юнит-тест для учетной записи

package crm

import grails.testing.gorm.DomainUnitTest
import spock.lang.Specification


class AccountSpec extends Specification implements DomainUnitTest<Account> {



    def setup() {

    }

    def cleanup() {

    }

    void 'test name cannot be null'() {
        when:
        domain.mobile = null
        then:
        !domain.validate(['mobile'])
        domain.errors['mobile'].code == 'nullable'
    }


}

Пользовательский резолвер арендатора

package usermanagement

import grails.plugin.springsecurity.SpringSecurityService
import org.grails.datastore.mapping.multitenancy.AllTenantsResolver
import org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.security.core.userdetails.UserDetails

class CustomTenentResolver implements AllTenantsResolver{
    @Lazy
    @Autowired
    SpringSecurityService springSecurityService

    @Override
    Iterable<Serializable> resolveTenantIds() {
        return DetachedCriteria(Organisation).distinct("namespace").list()
    }

    @Override
    Serializable resolveTenantIdentifier() throws TenantNotFoundException {
        final String tenantId = organisation()
        if(tenantId){
            return tenantId
        }
        throw new TenantNotFoundException("unable to retrive tenent")
    }

    String organisation(){

        if (springSecurityService.principal == null){
            return null
        }

        if (springSecurityService.principal instanceof  String){
            return springSecurityService.principal
        }

        if (springSecurityService.principal instanceof UserDetails){

           return User.findByUsername(((UserDetails)springSecurityService.principal).username).organisation.namespace
        }

        null
    }
}

1 Ответ

1 голос
/ 29 апреля 2020

Правильные действия зависят от того, чего вы на самом деле пытаетесь достичь sh. Поскольку это модульное тестирование, я предполагаю, что вы пытаетесь проверить Account проверку и полностью исключить мультитенантность. Существуют различные способы сделать это sh, и простой способ отключить многопользовательскую работу в тесте:

import grails.testing.gorm.DomainUnitTest
import spock.lang.Specification

class AccountSpec extends Specification implements DomainUnitTest<Account> {

    @Override
    Closure doWithConfig() {
        { config ->
            config.grails.gorm.multiTenancy.mode = null
        }
    }

    void 'test name cannot be null'() {
        when:
        domain.mobile = null
        then:
        !domain.validate(['mobile'])
        domain.errors['mobile'].code == 'nullable'
    }
}
...