jira-plugin-intellij /src/main/resources/com/onresolve/jira/groovy/test/TestRenameUser.groovy

Language Groovy Lines 366
MD5 Hash de31318208a757683757a01a322e0483
Repository https://bitbucket.org/sorin/jira-plugin-intellij View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package com.onresolve.jira.groovy.test

import com.atlassian.core.action.ActionUtils
import com.atlassian.core.ofbiz.CoreFactory
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.ManagerFactory
import com.atlassian.jira.action.ActionNames
import com.atlassian.jira.bc.JiraServiceContextImpl
import com.atlassian.jira.bc.filter.SearchRequestService
import com.atlassian.jira.bc.user.UserService
import com.atlassian.jira.bc.user.UserService.DeleteUserValidationResult
import com.atlassian.jira.favourites.FavouritesManager
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.customfields.impl.MultiUserCFType
import com.atlassian.jira.issue.customfields.impl.UserCFType
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.search.SearchRequest
import com.atlassian.jira.issue.watchers.WatcherManager
import com.atlassian.jira.jql.builder.JqlQueryBuilder
import com.atlassian.jira.jql.parser.JqlQueryParser
import com.atlassian.jira.project.Project
import com.atlassian.jira.security.roles.actor.UserRoleActorFactory
import com.atlassian.jira.sharing.ShareManager
import com.atlassian.jira.sharing.SharedEntity.SharePermissions
import com.atlassian.query.Query
import com.atlassian.query.order.SortOrder
import com.onresolve.jira.groovy.canned.admin.RenameUser
import org.apache.log4j.Category
import org.junit.Before
import org.junit.Test
import org.ofbiz.core.entity.GenericValue
import webwork.dispatcher.ActionResult
import com.atlassian.jira.security.roles.*
import static junit.framework.Assert.*
import com.atlassian.jira.issue.search.SearchProvider
import com.atlassian.jira.web.bean.PagerFilter
import com.atlassian.jira.issue.search.SearchResults
import com.atlassian.jira.bc.user.UserService.CreateUserValidationResult
import com.atlassian.jira.bc.group.GroupService
import com.atlassian.crowd.embedded.api.User
import com.atlassian.jira.user.util.UserUtil
import com.atlassian.jira.security.groups.GroupManager
import com.onresolve.jira.groovy.GroovyRunner

class TestRenameUser {

    Category log = Category.getInstance(this.class)
    RenameUser renameUser
    ComponentManager componentManager = ComponentManager.getInstance()
    CustomFieldManager customFieldManager = componentManager.getCustomFieldManager()
    JqlQueryBuilder builder = JqlQueryBuilder.newBuilder()
    JqlQueryParser jqlQueryParser = ComponentManager.getComponentInstanceOfType(JqlQueryParser.class) as JqlQueryParser
    final String sourceUser = "def"
    final String targetUser = "abc"
    SearchRequestService searchRequestService = componentManager.getSearchRequestService()
    User currentUser = componentManager.getJiraAuthenticationContext().getUser()
    IssueManager issueManager = ManagerFactory.getIssueManager()
    Project project = componentManager.getProjectManager().getProjectObjByKey('JRA')
    GroovyRunner runner = new GroovyRunner()
    UserUtil userUtil = ComponentManager.getInstance().getUserUtil()
    FavouritesManager favouritesManager = ComponentManager.getComponentInstanceOfType(FavouritesManager.class) as FavouritesManager
    ShareManager shareManager = ComponentManager.getComponentInstanceOfType(ShareManager.class) as ShareManager
    SearchProvider searchProvider = componentManager.getSearchProvider()
    UserService userService = ComponentManager.getComponentInstanceOfType(UserService.class) as UserService
    GroupService groupService = ComponentManager.getComponentInstanceOfType(GroupService.class) as GroupService
    GroupManager groupManager = ComponentManager.getComponentInstanceOfType(GroupManager.class)

    @Before
    public void setUp() {
        renameUser = new RenameUser()
        log.debug("===================================================================================================")

        // check group exists
        userUtil.getGroup("SomeGroup")

        ["xxx", "yyy"].each {String u ->
            if (userUtil.getUser(u)) {
                log.debug("Deleting user: $u")

                builder.clear()
                Query query = builder.where().reporterUser(u).or().assigneeUser(u).buildQuery()
                SearchResults results = searchProvider.search(query, currentUser, PagerFilter.getUnlimitedFilter())
                results.getIssues().each {Issue issue ->
                    log.debug("Delete issue $issue.key")
                    deleteIssue(issueManager.getIssueObject(issue.id))
                }

                deleteUser(userUtil.getUser(u))
            }
        }
    }

    @Test
    public void testUpdateSearchRequest() {
        builder.clear()
        Query query = builder.where().reporterUser(sourceUser).buildQuery()
        query = JqlQueryBuilder.newBuilder(query).orderBy().assignee(SortOrder.ASC).buildQuery()

        SearchRequest sr = new SearchRequest(query, currentUser.getName(), "ReporterIsDef", "some desc")
        sr = createAndUpdate(sr)
        assertEquals '{reporter = "abc"} order by assignee ASC', sr.query.toString()
        deleteSearchRequest(sr)

        // this query should not need to be updated
        builder.clear()
        query = builder.where().reporterUser("admin").buildQuery()
        sr = new SearchRequest(query, currentUser.getName(), "ReporterIsDef", "some desc")
        sr = createAndUpdate(sr)
        log.debug(sr.query.queryString)
        deleteSearchRequest(sr)
    }

    private void deleteSearchRequest (SearchRequest sr) {
        JiraServiceContextImpl ctx = new JiraServiceContextImpl(userUtil.getUser(sr.ownerUserName))
        searchRequestService.deleteFilter(ctx, sr.id)
        assertFalse ctx.errorCollection.hasAnyErrors()
    }

    private SearchRequest createAndUpdate(SearchRequest sr) {
        JiraServiceContextImpl ctx = new JiraServiceContextImpl(currentUser)
        searchRequestService.validateFilterForCreate(ctx, sr)
        assertFalse ctx.errorCollection.hasAnyErrors()
        sr = searchRequestService.createFilter(ctx, sr, true)
        assertFalse ctx.errorCollection.hasAnyErrors()
        renameUser.updateSingleRequest(sr, sourceUser, targetUser)
        sr = searchRequestService.getFilter(ctx, sr.id)
        sr
    }

    @Test
    public void testTransformQuery() {
        log.debug("testTransformQuery")
        Query query, transformedQuery

        CustomField cfUserPicker = customFieldManager.getCustomFieldObjectByName("UserPicker")
        CustomField cfMultiUserPicker = customFieldManager.getCustomFieldObjectByName("MultiUserPicker")
        assertNotNull cfUserPicker
        assertNotNull cfMultiUserPicker

        log.debug(cfMultiUserPicker.getCustomFieldType().class)
        assertTrue (cfUserPicker.getCustomFieldType() instanceof UserCFType)
        assertTrue (cfMultiUserPicker.getCustomFieldType() instanceof MultiUserCFType)

        query = builder.where().reporterUser('def').buildQuery()
        query = JqlQueryBuilder.newBuilder(query).orderBy().assignee(SortOrder.ASC).buildQuery()
        assertEquals "{reporter = \"def\"} order by assignee ASC", query.toString()
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        assertEquals "{reporter = \"abc\"} order by assignee ASC", transformedQuery.toString()

        builder.clear()
        query = builder.where().reporterUser('def').and().assigneeUser("def").buildQuery()
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        assertEquals '{reporter = "abc"} AND {assignee = "abc"}', transformedQuery.toString()

        builder.clear()
        query = builder.where().reporter().in().strings("admin", "def").buildQuery()
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        assertEquals '{reporter in ("admin", "abc")}', transformedQuery.toString()

        builder.clear()
        query = builder.where().reporter().notIn().strings("admin", "def").buildQuery()
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        assertEquals '{reporter not in ("admin", "abc")}', transformedQuery.toString()

        builder.clear()
        query = builder.where().reporter().notEq("def").buildQuery()
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        assertEquals '{reporter != "abc"}', transformedQuery.toString()

        builder.clear()
        query = builder.where().sub().reporter().eq("def").or().priority("1").endsub().and().sub().reporterUser("admin").or().priority("2").endsub().buildQuery()
        assertEquals '( {reporter = "def"} OR {priority = "1"} ) AND ( {reporter = "admin"} OR {priority = "2"} )', query.toString()
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        assertEquals '( {reporter = "abc"} OR {priority = "1"} ) AND ( {reporter = "admin"} OR {priority = "2"} )', transformedQuery.toString()

        builder.clear()
        query = builder.where().not().reporter().eq("def").buildQuery()
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        assertEquals 'NOT {reporter = "abc"}', transformedQuery.toString()

        builder.clear()
        query = builder.where().not().sub().reporter().eq("def").or().priority("1").endsub()
            .and().not().sub().reporterUser("admin").or().priority("2").endsub().buildQuery()
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        assertEquals 'NOT ( {reporter = "abc"} OR {priority = "1"} ) AND NOT ( {reporter = "admin"} OR {priority = "2"} )', transformedQuery.toString()

        // custom fields
        builder.clear()
        query = builder.where().customField(cfUserPicker.idAsLong).eq("def").buildQuery()
        log.debug query
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        log.debug(transformedQuery)
        assertEquals '{cf[10040] = "abc"}', transformedQuery.toString()

        // There are two UserPickers, how is it supposed to know which is which
        // Do we want two user pickers for these tests?
        query = jqlQueryParser.parseQuery("UserPicker is def")
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        log.debug(transformedQuery)
        assertEquals '{UserPicker is "abc"}', transformedQuery.toString()

        query = jqlQueryParser.parseQuery("UserPicker IN (admin, def)")
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        log.debug(transformedQuery)
        assertEquals '{UserPicker in ("admin", "abc")}', transformedQuery.toString()

        query = jqlQueryParser.parseQuery("project = JRA AND MultiUserPicker in (def,admin)")
        log.debug(query.queryString)
        transformedQuery = renameUser.transformSearchRequest(query, "def", "abc")
        log.debug(transformedQuery)
        assertEquals '{project = "JRA"} AND {MultiUserPicker in ("abc", "admin")}', transformedQuery.toString()
    }

    @Test
    public void testRename() {
        testDoScript(false)
    }

    @Test
    public void testMerge() {
        testDoScript(true)
    }

    public void testDoScript(boolean merge) {
        log.debug('testDoScript')
        User userSrc = createUser("xxx")
        User userTarget = null
        if (merge) {
            userTarget = createUser("yyy")
        }

        groupManager.addUserToGroup(userSrc, userUtil.getGroup("SomeGroup"))

        GenericValue issueGv1 = createIssue(userSrc);
        GenericValue issueGv2 = null
        if (merge) {
            issueGv2 = createIssue(userTarget);
        }

        builder.clear()
        Query query = builder.where().reporterUser(userSrc.name).buildQuery()
        query = JqlQueryBuilder.newBuilder(query).orderBy().assignee(SortOrder.ASC).buildQuery()
        SearchRequest sr = new SearchRequest(query, userSrc.name, "ReporterIsXXDef", "some desc")
        sr.setPermissions(SharePermissions.GLOBAL)
        JiraServiceContextImpl ctx = new JiraServiceContextImpl(userSrc)
        searchRequestService.validateFilterForCreate(ctx, sr)
        log.debug(ctx.errorCollection)
        assertFalse ctx.errorCollection.hasAnyErrors()
        sr = searchRequestService.createFilter(ctx, sr, true)
        assertFalse ctx.errorCollection.hasAnyErrors()

        favouritesManager.addFavourite(userSrc, sr)
        if (merge) {
            favouritesManager.addFavourite(userTarget, sr)
        }

        WatcherManager watcherManager = componentManager.getWatcherManager()
        watcherManager.startWatching(userSrc, issueGv1)
        if (merge) {
            watcherManager.startWatching(userSrc, issueGv2)
            watcherManager.startWatching(userTarget, issueGv1)
        }

        ProjectRoleManager projectRoleManager = ComponentManager.getComponentInstanceOfType(ProjectRoleManager.class) as ProjectRoleManager
        RoleActorFactory roleActorFactory = ComponentManager.getComponentInstanceOfType(RoleActorFactory.class) as RoleActorFactory
        ProjectRole devsRole = projectRoleManager.getProjectRole("Developers")
        ProjectRoleActors actors = projectRoleManager.getProjectRoleActors(devsRole, project)
        RoleActor roleActor = roleActorFactory.createRoleActor(null, devsRole.id, project.id, UserRoleActorFactory.TYPE, userSrc.name);
        actors = actors.addRoleActor(roleActor) as ProjectRoleActors
        if (merge) {
            roleActor = roleActorFactory.createRoleActor(null, devsRole.id, project.id, UserRoleActorFactory.TYPE, userTarget.name);
            actors = actors.addRoleActor(roleActor) as ProjectRoleActors
        }
        projectRoleManager.updateProjectRoleActors(actors)
        assertTrue projectRoleManager.getProjectRoleActors(devsRole, project).getUsers()*.name.contains(userSrc.name)

        Map<String, Object> inputs = [
            (RenameUser.FIELD_FROM_USER_ID) : userSrc.name,
            (RenameUser.FIELD_TO_USER_ID): (merge ? userTarget.name : "yyy"),
            (RenameUser.FIELD_MERGE): merge,
        ] as Map<String, Object>
        log.debug(inputs)

        Map params = new RenameUser().doScript(inputs)

        userTarget = userUtil.getUser("yyy")

        // post-script assertions
        if (merge) {
            assertEquals "Mr yyy", userTarget.displayName
        }

        assertNull userUtil.getUser(userSrc.name)
        assertNotNull userUtil.getUser(userTarget.name)
        assertTrue groupManager.isUserInGroup(userTarget.name, "SomeGroup")
        assertTrue projectRoleManager.getProjectRoleActors(devsRole, project).getUsers()*.name.contains(userTarget.name)
        assertFalse projectRoleManager.getProjectRoleActors(devsRole, project).getUsers()*.name.contains(userSrc.name)
        assertTrue watcherManager.isWatching(userTarget, issueGv1)
        if (merge) {
            assertTrue watcherManager.isWatching(userTarget, issueGv2)
        }
        // reload sr because the owner has changed now
        sr = searchRequestService.getFilter(new JiraServiceContextImpl(userTarget), sr.id)

        // check that the favourite count has been reduced now these two are the same user
        assertEquals(1, sr.getFavouriteCount())

        // post-script clean-up


        Issue issue = issueManager.getIssueObject(issueGv1.getLong("id"))
        assertEquals userTarget.name, issue.reporterId

        // deleteUser(userSrc)
        deleteIssue(issueManager.getIssueObject(issueGv1.getLong("id")))

        if (merge) {
            deleteIssue(issueManager.getIssueObject(issueGv2.getLong("id")))
        }
        deleteUser(userTarget)

        // don't deleteSearchRequest(sr) because it's handled when the user is deleted properly
    }

    private GenericValue createIssue(User user) {
        Issue issue = componentManager.getIssueFactory().getIssue()
        issue.setProject(project.getGenericValue())
        issue.setSummary "my summary"
        issue.setReporterId user.name
        issue.setIssueTypeId "1"
        issue.setPriorityId('2')
        GenericValue issueGv = issueManager.createIssue(user, issue)
        return issueGv
    }

    private def deleteUser(User user) {
        DeleteUserValidationResult validationResult = userService.validateDeleteUser(componentManager.getJiraAuthenticationContext().getUser(), user.name)
        log.debug(validationResult.errorCollection)
        assertTrue validationResult.isValid()
        userService.removeUser(user, validationResult)
        assertNull userUtil.getUser(user.name)
    }

    private User createUser(String userId) {
        assertNull userUtil.getUser(userId)
        CreateUserValidationResult res = userService.validateCreateUserForAdmin(currentUser, userId, "pw", "pw", "${userId}@blah.com", "Mr ${userId}")
        assertFalse res.errorCollection.hasAnyErrors()
        User user = userService.createUserNoNotification(res)
        assertNotNull userUtil.getUser(userId)
        return user
    }

    public def deleteIssue(Issue theIssue) {
        Map parameters = [
                issue: theIssue.getGenericValue(),
                remoteUser: userUtil.getUser("admin"),
                dispatchEvent: false,
                permissionOverride: true,
        ]
        ActionResult aResult = CoreFactory.getActionDispatcher().execute(ActionNames.ISSUE_DELETE, parameters);
        ActionUtils.checkForErrors(aResult)
    }
}
Back to Top