类hudson.model.User源码实例Demo

下面列出了怎么用hudson.model.User的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void shouldSucceedForAuthedUserWithCredentialCreatedAndCredentialIdMissingEnterprise() throws Exception {
    // switch to bob and create a credential
    User user = login();
    createGithubEnterpriseCredential(user);

    String orgFolderName = "cloudbeers";
    Map resp = new RequestBuilder(baseUrl)
            .status(201)
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( this.crumb )
            .post("/organizations/"+getOrgName()+"/pipelines/")
            // since credentialId will default to 'github', it's okay to omit it in request
            .data(GithubTestUtils.buildRequestBody(GithubEnterpriseScm.ID, null, githubApiUrl, orgFolderName, "PR-demo"))
            .build(Map.class);
    assertNotNull(resp);
}
 
源代码2 项目: blueocean-plugin   文件: ProfileApiTest.java
@Test
public void userCurrentTest() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    SecurityContextHolder.getContext().setAuthentication(j.jenkins.ANONYMOUS);

    Assert.assertNull(User.current());

    List<Map> l = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/pipelines/")
        .authAlice()
        .build(List.class);

    assertEquals(0, l.size());
    Assert.assertNull(User.current());
}
 
private static User createAccount(HudsonPrivateSecurityRealm target, UserWithPassword user)
    throws IOException {
    User updatedUser;
    if (StringUtils.isNotBlank(user.password)) {
        if (StringUtils.startsWith(user.password, HASHED_PASSWORD_PREFIX)) {
            try {
                updatedUser = target
                    .createAccountWithHashedPassword(user.id, user.password);
            } catch (IllegalArgumentException | IOException e) {
                logger.log(Level.WARNING,
                    "Failed to create user with presumed hashed password", e);
                // fallback, just create the account as is
                updatedUser = target.createAccount(user.id, user.password);
            }
        } else {
            updatedUser = target.createAccount(user.id, user.password);
        }
    } else {
        updatedUser = User.getById(user.id, true);
    }
    return updatedUser;
}
 
public void addDevelopers() {
    if (!(run instanceof RunWithSCM)) {
        return;
    }
    RunWithSCM runWithSCM = (RunWithSCM) run;

    List<ChangeLogSet<ChangeLogSet.Entry>> sets = runWithSCM.getChangeSets();

    Set<User> authors = new HashSet<>();
    sets.stream()
            .filter(set -> set instanceof ChangeLogSet)
            .forEach(set -> set
                    .forEach(entry -> authors.add(entry.getAuthor())));

    addFact(NAME_DEVELOPERS, StringUtils.join(sortUsers(authors), ", "));
}
 
源代码5 项目: blueocean-plugin   文件: APIHeadTest.java
@Test
public void defaultCacheHeaderTest() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    RequestBuilder requestBuilder = request().authAlice().get("/organizations/jenkins/users/");

    HttpResponse<List> response = requestBuilder.execute(List.class);

    List<String> list = response.getHeaders().get("Cache-Control");

    assertThat(list.get(0), containsString("no-cache"));
    assertThat(list.get(0), containsString("no-store"));
    assertThat(list.get(0), containsString("no-transform"));
}
 
源代码6 项目: flaky-test-handler-plugin   文件: TestGitRepo.java
public TestGitRepo(String name, File tmpDir, TaskListener listener) throws IOException, InterruptedException {
  this.name = name;
  this.listener = listener;

  envVars = new EnvVars();

  gitDir = tmpDir;
  User john = User.get(johnDoe.getName(), true);
  UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress());
  john.addProperty(johnsMailerProperty);

  User jane = User.get(janeDoe.getName(), true);
  UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress());
  jane.addProperty(janesMailerProperty);

  // initialize the git interface.
  gitDirPath = new FilePath(gitDir);
  git = Git.with(listener, envVars).in(gitDir).getClient();

  // finally: initialize the repo
  git.init();
}
 
@Test
public void unauthorizedAccessToContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketCloudScm.ID, "cloud", alice);

    StaplerRequest staplerRequest = mockStapler();

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new BitbucketCloudScmContentProvider().getContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
源代码8 项目: blueocean-plugin   文件: AnalyticsTest.java
@Test
public void track() {
    ImmutableMap<String, Object> props = ImmutableMap.<String, Object>of(
        "prop1", "value1",
        "prop2", 2,
        "jenkinsVersion", j.jenkins.getVersion().toString(),
        "blueoceanVersion", Jenkins.getInstance().getPlugin("blueocean-commons").getWrapper().getVersion()
    );
    analytics.track(new TrackRequest("test", props));

    Map<String, Object> expectedProps = Maps.newHashMap(props);
    expectedProps.put("jenkins", analytics.getServer());

    Assert.assertEquals("test", analytics.lastName);
    Assert.assertEquals( expectedProps, analytics.lastProps);

    // Ensure identify does not contain the username
    Assert.assertFalse(analytics.getIdentity().contains(User.current().getId()));
}
 
private MultiBranchProject mockMbp(String credentialId, User user) {
    MultiBranchProject mbp = mock(MultiBranchProject.class);
    when(mbp.getName()).thenReturn("pipeline1");
    when(mbp.getParent()).thenReturn(j.jenkins);
    BitbucketSCMSource scmSource = mock(BitbucketSCMSource.class);
    when(scmSource.getServerUrl()).thenReturn(apiUrl);
    when(scmSource.getCredentialsId()).thenReturn(credentialId);
    when(scmSource.getRepoOwner()).thenReturn("TESTP");
    when(scmSource.getRepository()).thenReturn("pipeline-demo-test");
    when(mbp.getSCMSources()).thenReturn(Lists.<SCMSource>newArrayList(scmSource));

    //mock blueocean credential provider stuff
    BlueOceanCredentialsProvider.FolderPropertyImpl folderProperty = mock(BlueOceanCredentialsProvider.FolderPropertyImpl.class);
    DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor> properties = new DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor>(mbp);
    properties.add(new BlueOceanCredentialsProvider.FolderPropertyImpl(
            user.getId(), credentialId,
            BlueOceanCredentialsProvider.createDomain(apiUrl)
    ));
    Domain domain = mock(Domain.class);
    when(domain.getName()).thenReturn(BitbucketServerScm.DOMAIN_NAME);
    when(folderProperty.getDomain()).thenReturn(domain);

    when(mbp.getProperties()).thenReturn(properties);
    return mbp;
}
 
@Test
public void shouldSucceedForAuthedUserWithCredentialCreatedAndCredentialIdMissing() throws Exception {
    // switch to bob and create a credential
    User user = login();
    createGithubCredential(user);

    String orgFolderName = "cloudbeers";
    Map resp = new RequestBuilder(baseUrl)
            .status(201)
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( this.crumb )
            .post("/organizations/"+getOrgName()+"/pipelines/")
            // since credentialId will default to 'github', it's okay to omit it in request
            .data(GithubTestUtils.buildRequestBody(GithubScm.ID, null, githubApiUrl, orgFolderName, "PR-demo"))
            .build(Map.class);
    assertNotNull(resp);
}
 
源代码11 项目: blueocean-plugin   文件: ChangeSetResourceTest.java
@Test
public void testChangeSet(){
    Reachable reachable = mock(Reachable.class);
    when(reachable.getLink()).thenReturn(new Link("/foo/bar"));
    User user = mock(User.class);
    when(user.getId()).thenReturn("vivek");
    ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class);
    when(entry.getAuthor()).thenReturn(user);
    when(entry.getTimestamp()).thenReturn(System.currentTimeMillis());
    when(entry.getCommitId()).thenReturn("12345");
    when(entry.getMsg()).thenReturn("test changeset");
    when(entry.getAffectedPaths()).thenReturn(Collections.singleton("/foo/bar"));
    ChangeSetResource changeSetResource = new ChangeSetResource(new OrganizationImpl("testorg", mock(Folder.class)), entry, reachable);
    assertEquals(user.getId(), changeSetResource.getAuthor().getId());
    assertEquals(entry.getCommitId(), changeSetResource.getCommitId());
    assertEquals(entry.getMsg(), changeSetResource.getMsg());
}
 
源代码12 项目: blueocean-plugin   文件: GitReadSaveRequest.java
@CheckForNull
StandardCredentials getCredential() {
    StandardCredentials credential = null;

    User user = User.current();
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Not authenticated");
    }

    // Get committer info and credentials
    if (GitUtils.isSshUrl(gitSource.getRemote()) || GitUtils.isLocalUnixFileUrl(gitSource.getRemote())) {
        credential = UserSSHKeyManager.getOrCreate(user);
    } else {
        String credentialId = GitScm.makeCredentialId(gitSource.getRemote());

        if (credentialId != null) {
            credential = CredentialsUtils.findCredential(credentialId,
                                                         StandardCredentials.class,
                                                         new BlueOceanDomainRequirement());
        }
    }
    return credential;
}
 
源代码13 项目: blueocean-plugin   文件: UserPublicKeyRoute.java
/**
 * Gets or creates the user's private Jenkins-managed key and returns the
 * public key to the user
 *
 * @return JSON response
 */
@GET
@WebMethod(name = "")
@TreeResponse
public UserKey getPublickey() {
    User authenticatedUser = User.current();
    if (authenticatedUser == null) {
        throw new ServiceException.UnauthorizedException("Not authorized");
    }
    if (!StringUtils.equals(user.getId(), authenticatedUser.getId())) {
        throw new ServiceException.ForbiddenException("Not authorized");
    }

    UserKey publicKey = UserSSHKeyManager.getPublicKey(authenticatedUser,
        UserSSHKeyManager.getOrCreate(authenticatedUser));

    return publicKey;
}
 
源代码14 项目: blueocean-plugin   文件: UserStatePreloader.java
/**
 * {@inheritDoc}
 */
@Override
public String getStateJson() {

    BlueOrganization organization = Iterables.getFirst(OrganizationFactory.getInstance().list(), null);

    try {
        User currentUser = User.current();
        if (currentUser != null && organization != null) {
            return Export.toJson(new UserImpl(organization, currentUser), true);
        } else {
            return ANONYMOUS;
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unexpected error serializing active User object and adding to page preload state.");
        return ANONYMOUS;
    }
}
 
@Test
public void createPipeline() throws UnirestException, IOException {
    User user = login("vivek", "Vivek Pandey", "[email protected]");
    Map r = new PipelineBaseTest.RequestBuilder(baseUrl)
        .status(201)
        .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
        .crumb( crumb )
        .post("/organizations/jenkins/pipelines/")
        .data(ImmutableMap.of("name", "pipeline1",
            "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
            "scmConfig", ImmutableMap.of("id", GitScm.ID, "uri", sampleRepo.toString())))
        .build(Map.class);
    assertNotNull(r);
    assertEquals("pipeline1", r.get("name"));

    MultiBranchProject mbp = (MultiBranchProject) j.getInstance().getItem("pipeline1");
    GitSCMSource source = (GitSCMSource) mbp.getSCMSources().get(0);
    List<SCMSourceTrait> traits = source.getTraits();

    Assert.assertNotNull(SCMTrait.find(traits, BranchDiscoveryTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, CleanAfterCheckoutTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, CleanBeforeCheckoutTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, LocalBranchTrait.class));
}
 
源代码16 项目: blueocean-plugin   文件: MultiBranchTest.java
@Test
public void multiBranchPipelineIndex() throws Exception {
    User user = login();
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
            new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    Map map = new RequestBuilder(baseUrl)
            .post("/organizations/jenkins/pipelines/p/runs/")
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( getCrumb( j.jenkins ) )
            .data(ImmutableMap.of())
            .status(200)
            .build(Map.class);

    assertNotNull(map);
}
 
源代码17 项目: blueocean-plugin   文件: GitScmTest.java
@Test
public void shouldFailOnValidation2() throws Exception {

    User user = login();
    this.jwtToken = getJwtToken(j.jenkins, user.getId(), user.getId());

    Map<String,Object> resp = post("/organizations/" + getOrgName() + "/pipelines/",
            ImmutableMap.of("name", "demo",
                    "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest"
            ), 400);

    assertEquals(resp.get("code"), 400);

    List<Map> errors = (List<Map>) resp.get("errors");

    assertEquals("scmConfig", errors.get(0).get("field"));
    assertEquals("MISSING", errors.get(0).get("code"));
    assertNull(getOrgRoot().getItem("demo"));
}
 
源代码18 项目: blueocean-plugin   文件: GitScmTest.java
@Test
public void shouldFailOnValidation5() throws Exception {

    User user = login();
    this.jwtToken = getJwtToken(j.jenkins, user.getId(), user.getId());

    Map<String,Object> resp = post("/organizations/" + getOrgName() + "/pipelines/",
            ImmutableMap.of("name", "demo",
                    "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
                    "scmConfig", ImmutableMap.of("uri", sampleRepo.fileUrl(), "credentialId", "sdsdsd")
            ), 400);
    List<Map<String,String>> errors = (List<Map<String,String>>) resp.get("errors");

    assertEquals("scmConfig.credentialId", errors.get(0).get("field"));
    assertEquals("NOT_FOUND", errors.get(0).get("code"));
    assertNull(getOrgRoot().getItem("demo"));
}
 
@Test
@ConfiguredWithCode("config.yml")
public void configurationImportTest() {
    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("admin"))) {
        assertTrue(j.jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("user1"))) {
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(j.jenkins.hasPermission(Jenkins.ADMINISTER));

        assertTrue(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.CONFIGURE));
        assertFalse(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.DELETE));
    }
}
 
@Test
public void stepExecutionWithCredentialsAndQueueItemAuthenticator() throws Exception {
    assumeNotWindows();

    r.getInstance().setSecurityRealm(r.createDummySecurityRealm());
    MockAuthorizationStrategy auth = new MockAuthorizationStrategy()
            .grant(Jenkins.READ).everywhere().to("alice", "bob")
            .grant(Computer.BUILD).everywhere().to("alice", "bob")
            // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById
            // uses when determining whether to include item-scope credentials in the search.
            .grant(Item.CONFIGURE).everywhere().to("alice");
    r.getInstance().setAuthorizationStrategy(auth);

    IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials);

    String script = "node {\n" +
            "  mockDockerLoginWithEcho {\n" +
            "    withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" +
            "    }\n" +
            "  }\n" +
            "}";
    WorkflowJob p1 = r.createProject(WorkflowJob.class, "prj1");
    p1.setDefinition(new CpsFlowDefinition(script, true));
    WorkflowJob p2 = r.createProject(WorkflowJob.class, "prj2");
    p2.setDefinition(new CpsFlowDefinition(script, true));

    Map<String, Authentication> jobsToAuths = new HashMap<>();
    jobsToAuths.put(p1.getFullName(), User.getById("alice", true).impersonate());
    jobsToAuths.put(p2.getFullName(), User.getById("bob", true).impersonate());
    QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(jobsToAuths));

    // Alice has Credentials.USE_ITEM permission and should be able to use the credential.
    WorkflowRun b1 = r.buildAndAssertSuccess(p1);
    r.assertLogContains("docker login -u me -p pass https://my-reg:1234", b1);

    // Bob does not have Credentials.USE_ITEM permission and should not be able to use the credential.
    r.assertBuildStatus(Result.FAILURE, p2.scheduleBuild2(0));
}
 
@Test
public void testOrgFolderIndexing() throws IOException, UnirestException {
    User user = login();
    OrganizationFolder orgFolder = j.jenkins.createProject(OrganizationFolder.class, "p");
    orgFolder.getSCMNavigators().add(new GitHubSCMNavigator("cloudbeers"));
    Map map = new RequestBuilder(baseUrl)
            .post("/organizations/jenkins/pipelines/p/runs/")
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( this.crumb )
            .data(ImmutableMap.of())
            .status(200)
            .build(Map.class);

    assertNotNull(map);
}
 
源代码22 项目: audit-log-plugin   文件: BuildListener.java
/**
 * Fired when a build is completed, event logged via Log4j-audit.
 *
 * @param run of type Run having the build information
 * @param listener of type TaskListener that the onCompleted method expects
 */
@Override
public void onCompleted(Run run, TaskListener listener) {
    BuildFinish buildFinish = LogEventFactory.getEvent(BuildFinish.class);

    List causeObjects = run.getCauses();
    List<String> causes = new ArrayList<>(causeObjects.size());
    for (Object cause: causeObjects) {
        Cause c = (Cause)cause;
        causes.add(c.getShortDescription());
    }
    buildFinish.setBuildNumber(run.getNumber());
    buildFinish.setCause(causes);
    buildFinish.setProjectName(run.getParent().getFullName());

    Instant start = Instant.ofEpochMilli(run.getStartTimeInMillis());
    Instant finish = start.plusMillis(run.getDuration());
    buildFinish.setTimestamp(formatDateISO(finish.toEpochMilli()));

    User user = User.current();
    if(user != null)
        buildFinish.setUserId(user.getId());
    else
        buildFinish.setUserId(null);

    buildFinish.logEvent();
}
 
源代码23 项目: audit-log-plugin   文件: RequestContextFilter.java
/**
 * The filter through which the flow passes is used to set the context level attributes
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    User user = User.current();
    if(user != null){
        RequestContext.setUserId(user.getId());
    }
    RequestContext.setIpAddress(request.getRemoteAddr());
    RequestContext.setNodeName(request.getLocalName());
    //RequestContext.setRequestUri(request.getRequestURI());
    chain.doFilter(request, response);
    RequestContext.clear();
}
 
@Issue("JENKINS-54088")
@Test
public void testUserCreationAndLoginFromRealm() throws Exception {
    assertEventCount(app.getEvents(), 0);

    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false, false, null);
    j.jenkins.setSecurityRealm(realm);

    User u1 = realm.createAccount("charlie", USERS.get("charlie"));
    u1.save();
    client.login("charlie", USERS.get("charlie"));

    // verify the audit event log messages as user creation and user login events
    StructuredDataMessage logMessageOne = (StructuredDataMessage) app.getEvents().get(0).getMessage();
    StructuredDataMessage logMessageTwo = (StructuredDataMessage) app.getEvents().get(1).getMessage();

    assertTrue(logMessageOne.toString().contains("createUser"));
    assertTrue(logMessageTwo.toString().contains("login"));

    // verify a login event occurred
    client.executeOnServer(() -> {
        Authentication a = Jenkins.getAuthentication();
        assertEquals("charlie", a.getName());

        return null;
    });

    assertEventCount(app.getEvents(), 2);
}
 
private static void setter(HudsonPrivateSecurityRealm target, Collection<UserWithPassword> value) throws IOException {
    for (UserWithPassword user : value) {
        User updatedUser = createAccount(target, user);
        updatedUser.setFullName(user.name);
        updatedUser.setDescription(user.description);
        if (user.getProperties() != null) {
            for (UserProperty property : user.getProperties()) {
                updatedUser.addProperty(property);
            }
        }
    }
}
 
@Test
public void unauthorizedSaveContentToOrgFolderShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);


    StaplerRequest staplerRequest = mockStapler();

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));
    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
private Optional<String> userResponsibleFor(InterruptedBuildAction details) {

        if (details.getCauses().size() == 1) {
            CauseOfInterruption cause = details.getCauses().get(0);

            if (cause instanceof CauseOfInterruption.UserInterruption) {
                User user = ((CauseOfInterruption.UserInterruption) cause).getUser();

                return Optional.of(user.getFullName());
            }
        }

        return Optional.absent();
    }
 
源代码28 项目: blueocean-plugin   文件: OrganizationApiTest.java
@Test
public void organizationUsers() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    List users = request().authAlice().get("/organizations/jenkins/users/").build(List.class);

    Assert.assertEquals(users.size(), 1);
    Map aliceMap = (Map) users.get(0);
    Assert.assertEquals(aliceMap.get("id"), "alice");
    Assert.assertEquals(aliceMap.get("fullName"), "Alice Cooper");
    Assert.assertEquals(aliceMap.get("email"), "[email protected]");
}
 
public String getUserName() {
	User current = User.current();
	if (current != null)
		return current.getFullName();
	else
		return null;
}
 
@Test
@ConfiguredWithReadme("embedded-userdatabase/README.md#0")
public void configure_local_security_and_admin_user() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm) jenkins.getSecurityRealm();
    assertFalse(securityRealm.allowsSignup());
    final User admin = User.getById("admin", false);
    assertNotNull(admin);
    final HudsonPrivateSecurityRealm.Details details = admin.getProperty(HudsonPrivateSecurityRealm.Details.class);
    assertTrue(details.isPasswordCorrect("somethingsecret"));

    final FullControlOnceLoggedInAuthorizationStrategy authorizationStrategy = (FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
    assertTrue(authorizationStrategy.isAllowAnonymousRead());
}
 
 类所在包
 同包方法