Merge branch 'jenkinsci:master' into master

This commit is contained in:
Dzmitry Rudnouski 2024-03-22 17:08:46 +03:00 committed by GitHub
commit a246a76298
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
240 changed files with 3804 additions and 3467 deletions

2
.git-blame-ignore-revs Normal file
View File

@ -0,0 +1,2 @@
# Enable spotless
b273e7be3888cd5279f5d328d119348e107669fb

View File

@ -1,11 +0,0 @@
version: 2
updates:
- package-ecosystem: maven
directory: "/"
schedule:
interval: weekly
open-pull-requests-limit: 10
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly

13
.github/renovate.json vendored Normal file
View File

@ -0,0 +1,13 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base",
":semanticCommitsDisabled",
"schedule:earlyMondays"
],
"automerge": true,
"labels": [
"dependencies"
],
"rebaseWhen": "conflicted"
}

View File

@ -17,15 +17,15 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
java: [11, 17]
os: [ubuntu-latest, windows-latest]
java: [17]
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java }}
distribution: 'temurin'
@ -35,6 +35,6 @@ jobs:
run: mvn -Pjacoco clean verify -B -V --no-transfer-progress ${{ matrix.flags }}
- name: Codecov coverage
uses: codecov/codecov-action@v3
uses: codecov/codecov-action@v4
with:
file: '*jacoco.xml'

View File

@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Install updatecli
uses: updatecli/updatecli-action@v2

View File

@ -10,9 +10,14 @@
<property name="message" value="Trailing spaces are not allowed."/>
</module>
<module name="TreeWalker">
<module name="ImportOrder">
<property name="separatedStaticGroups" value="true" />
<property name="option" value="bottom" />
<module name="CustomImportOrder">
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="separateLineBetweenGroups" value="true"/>
<property name="customImportOrderRules" value="STATIC###THIRD_PARTY_PACKAGE"/>
<property name="tokens" value="IMPORT, STATIC_IMPORT, PACKAGE_DEF"/>
</module>
<module name="NeedBraces">
<property name="tokens" value="LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE"/>
</module>
<module name="UnusedImports" />
<module name="AvoidStarImport" />

11
Jenkinsfile vendored
View File

@ -1,5 +1,6 @@
def configurations = [
[ platform: "linux", jdk: "11" ],
[ platform: 'linux', jdk: '17', jenkins: '2.342' ]
]
buildPlugin(configurations: configurations, timeout: 180, useContainerAgent: true)
// Windows controller tests crash with unexpected errors
buildPlugin(useContainerAgent: true, forkCount: '0.5C', timeout: 360, configurations: [
[platform: 'linux', jdk: 21],
// Windows fails on >11 https://github.com/jenkinsci/configuration-as-code-plugin/pull/2392#issuecomment-1826296308
[platform: 'windows', jdk: 11],
])

View File

@ -65,7 +65,7 @@ jenkins:
name: "static-agent"
remoteFS: "/home/jenkins"
launcher:
jnlp:
inbound:
workDirSettings:
disabled: true
failIfWorkDirIsMissing: false
@ -150,7 +150,7 @@ If set up correctly, you should be able to browse the Configuration as Code page
When configuring the first Jenkins instance, browse the examples shown in the [demos](demos)
directory of this repository. If you have a plugin that does not have an example, consult the reference
help document. Click the `Documentation` link at the bottom of the Configuration as Code page.
help document. Click the `Documentation` link at the bottom of the Configuration as Code page in your Jenkins instance.
![Reference Page](images/reference.png)
@ -192,7 +192,7 @@ Anchor keys must be prefixed with `x-` due to JCasC handling unknown root elemen
x-jenkins-linux-node: &jenkins_linux_node_anchor
remoteFS: "/home/jenkins"
launcher:
jnlp:
inbound:
workDirSettings:
disabled: true
failIfWorkDirIsMissing: false
@ -218,7 +218,7 @@ jenkins:
name: "static-agent1"
remoteFS: "/home/jenkins"
launcher:
jnlp:
inbound:
workDirSettings:
disabled: true
failIfWorkDirIsMissing: false
@ -228,7 +228,7 @@ jenkins:
name: "static-agent2"
remoteFS: "/home/jenkins"
launcher:
jnlp:
inbound:
workDirSettings:
disabled: true
failIfWorkDirIsMissing: false

View File

@ -19,8 +19,8 @@ If configuration requires additional files (like Kubernetes) add them too.
*All provided configurations in demo have to be tested:*
* create test class for your demo
* use `JenkinsConfiguredWithReadmeRule` to get configuration from your `README.md` file
* implement test cases for your demo to cover whole configuration
* use https://github.com/jenkinsci/configuration-as-code-plugin/blob/master/test-harness/src/main/java/io/jenkins/plugins/casc/misc/JenkinsConfiguredWithReadmeRule.java[`JenkinsConfiguredWithReadmeRule`] to get configuration from your `README.md` file
* implement https://github.com/jenkinsci/configuration-as-code-plugin/tree/master/test-harness/src/test/java/io/jenkins/plugins/casc[test cases] for your demo to cover whole configuration
* for example check `ArtifactoryTest` and others.
See also https://github.com/jenkinsci/configuration-as-code-plugin/pull/1055[PR #1055]

View File

@ -13,11 +13,13 @@ jenkins:
name: "utility-node"
remoteFS: "/home/user1"
launcher:
jnlp:
inbound:
webSocket: true
tunnel: some.proxy
workDirSettings:
disabled: true
failIfWorkDirIsMissing: false
internalDir: "remoting"
internalDir: "remoting2"
workDirPath: "/tmp"
- permanent:

View File

@ -1,15 +0,0 @@
# Configure Crowd2 plugin
Basic configuration of the [Crowd2 plugin](https://plugins.jenkins.io/crowd2)
## sample configuration
```yaml
jenkins:
securityRealm:
crowd:
applicationName: "jenkins"
group: "jenkins-users"
password: "${CROWD_PASSWORD}"
url: "http://crowd.company.io"
```

View File

@ -33,7 +33,7 @@ x-ec2_anchor: &ec2_anchor
jenkins:
clouds:
- amazonEC2:
cloudName: "ec2"
name: "ec2"
instanceCapStr: 20
# this shouldn't be needed, since without explicit creds this should already be used
# but let's be explicit to avoid issues.

View File

@ -0,0 +1,56 @@
# Configure Git client plugin
Basic configuration of a git tool to be used by the [Git client plugin](https://plugins.jenkins.io/git-client)
## Sample tool configuration
```yaml
tool:
git:
installations:
- name: git
home: /bin/git
- name: another_git
home: /usr/local/bin/git
```
## More detailed tool configuration
```yaml
tool:
git:
installations:
- home: "git"
name: "Default"
properties:
- installSource:
installers:
- command:
command: "true"
label: "!windows && !freebsd && !openbsd"
toolHome: "/usr/bin/git"
- command:
command: "true"
label: "freebsd || openbsd"
toolHome: "/usr/local/bin/git"
- batchFile:
command: "exit 0"
label: "windows"
toolHome: "C:\\tools\\MinGit-2.42.0.2\\mingw64\\bin\\git.exe"
```
## Sample ssh host key verification policy configuration
The [ssh host key verification policy](https://plugins.jenkins.io/git-client/#plugin-content-ssh-host-key-verification) can be configured with configuration as code.
Other ssh host key verification policy examples are available in the [git client plugin documentation](https://plugins.jenkins.io/git-client/#plugin-content-configuration-as-code-sample).
```yaml
security:
gitHostKeyVerificationConfiguration:
sshHostKeyVerificationStrategy:
manuallyProvidedKeyVerificationStrategy:
approvedHostKeys: |-
bitbucket.org ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIazEu89wgQZ4bqs3d63QSMzYVa0MuJ2e2gKTKqu+UUO
github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl
gitlab.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAfuCHKVTjquxvt6CM6tdG4SLp1Btn/nOeHHE5UOzRdf
```

View File

@ -1,25 +1,20 @@
# Configure git plugin
# Configure Git plugin
Basic configuration of the [Git Client plugin](https://plugins.jenkins.io/git-client)
Basic global configuration of the [Git plugin](https://plugins.jenkins.io/git).
Detailed descriptions of each option are available in the [git plugin documentation](https://plugins.jenkins.io/git/#plugin-content-global-configuration).
## sample configuration
```yaml
tool:
git:
installations:
- name: git
home: /bin/git
- name: another_git
home: /usr/local/bin/git
unclassified:
scmGit:
addGitTagAction: false
allowSecondFetch: false
createAccountBasedOnEmail: true
disableGitToolChooser: false
globalConfigEmail: jenkins@domain.local
globalConfigName: jenkins
hideCredentials: false
showEntireCommitSummaryInChanges: true
useExistingAccountWithSameEmail: false
```
## implementation note
Here we rely on `hudson.tools.ToolDescriptor.setInstallations`, so same applies to all ToolInstallations.
Unfortunately Java reflection makes it hack-ish to detect the parameter type of this method from derived concrete
class, so maybe there's some corner case we will need to polish this logic.
Also, YAML lists are converted into `ArrayLists` but `setInstallations(T ... installation)` varags method require
an array - blame Java to not just accept any `Iterable` - so we need to detect this scenario and do the type
conversion.

View File

@ -1,13 +0,0 @@
# Configure gitscm
Basic configuration of the [Git plugin](https://plugins.jenkins.io/git)
## sample configuration
```yaml
unclassified:
gitscm:
globalConfigName: jenkins
globalConfigEmail: jenkins@domain.local
createAccountBasedOnEmail: true
```

View File

@ -37,4 +37,4 @@ jenkins:
## implementation note
The example above is only a subset of commonly used settings. The full list is available in the generated documentation.
The example above is only a subset of commonly used settings. The full list is available in the generated documentation by clicking on the `Documentation` link at the bottom of the Configuration as Code page in your Jenkins instance.

View File

@ -1,22 +0,0 @@
# Configure Keycloak plugin
Basic configuration of the [Keycloak plugin](https://plugins.jenkins.io/keycloak)
## sample configuration
```yaml
jenkins:
securityRealm: keycloak
unclassified:
keycloakSecurityRealm:
keycloakJson: |-
{
"realm": "my-realm",
"auth-server-url": "https://my-keycloak-url/auth",
"ssl-required": "all",
"resource": "jenkins",
"public-client": true,
"confidential-port": 0
}
```

View File

@ -47,7 +47,7 @@ master:
# over SSH to reapply config when changes to the ConfigScripts are detected. The admin user (or account you specify in
# Master.AdminUser) will have a random SSH private key (RSA 4096) assigned unless you specify OwnSshKey: true. This will be saved to a k8s secret.
enabled: true
image: shadwell/k8s-sidecar:0.0.2
image: shadwell/k8s-sidecar:0.0.7
imagePullPolicy: IfNotPresent
resources:
# limits:

View File

@ -0,0 +1,23 @@
# Configuring Node Monitors
Node monitor configuration belongs under `jenkins` root element.
Requires at least Jenkins `2.433`.<br/>
Any monitor that is available but is not configured will be treated as ignored.
Some monitors are capable to take agents offline when they are not ignored. Ignored
monitors will still run and report data.
## sample configuration
```yaml
jenkins:
nodeMonitors:
- "architecture"
- diskSpace:
freeSpaceThreshold: "3GB"
- "swapSpace"
- tmpSpace:
freeSpaceThreshold: "3GB"
- responseTime:
ignored: true
```

View File

@ -16,15 +16,15 @@ jenkins:
description: "Jenkins administrators"
permissions:
- "Overall/Administer"
assignments:
- "admin"
entries:
- user: "admin"
- name: "readonly"
description: "Read-only users"
permissions:
- "Overall/Read"
- "Job/Read"
assignments:
- "authenticated"
entries:
- user: "authenticated"
items:
- name: "FolderA"
description: "Jobs in Folder A, but not the folder itself"
@ -33,25 +33,25 @@ jenkins:
- "Job/Configure"
- "Job/Build"
- "Job/Delete"
assignments:
- "user1"
- "user2"
entries:
- user: "user1"
- user: "user2"
- name: "FolderB"
description: "Jobs in Folder B, but not the folder itself"
pattern: "B.*"
permissions:
- "Job/Configure"
- "Job/Build"
assignments:
- "user2"
entries:
- user: "user2"
agents:
- name: "Agent1"
description: "Agent 1"
pattern: "agent1"
permissions:
- "Agent/Build"
assignments:
- "user1"
entries:
- user: "user1"
securityRealm:
local:

View File

@ -5,8 +5,8 @@ Basic configuration of the [Simple Theme plugin](https://plugins.jenkins.io/simp
## sample configuration
```yaml
unclassified:
simple-theme-plugin:
appearance:
simpleTheme:
elements:
- cssUrl:
url: "https://example.bogus/test.css"

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.plugins.active_directory.ActiveDirectoryDomain;
import hudson.plugins.active_directory.ActiveDirectorySecurityRealm;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
@ -10,18 +14,13 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
public class ActiveDirectoryTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("BIND_PASSWORD", "ADMIN123"))
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables().set("BIND_PASSWORD", "ADMIN123"))
.around(new JenkinsConfiguredWithReadmeRule());
@Test
@ -42,6 +41,5 @@ public class ActiveDirectoryTest {
assertNotNull(realm.getCache());
assertEquals(500, realm.getCache().getSize());
assertEquals(600, realm.getCache().getTtl());
}
}

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import hudson.DescriptorExtensionList;
import io.jenkins.plugins.artifact_manager_jclouds.s3.S3BlobStoreConfig;
import io.jenkins.plugins.aws.global_configuration.CredentialsAwsGlobalConfiguration;
@ -10,11 +15,6 @@ import jenkins.model.ArtifactManagerFactoryDescriptor;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
public class ArtifactManagerS3Test {
@Rule
@ -26,8 +26,8 @@ public class ArtifactManagerS3Test {
assertThat(CredentialsAwsGlobalConfiguration.get().getRegion(), is(equalTo("us-east-1")));
assertThat(S3BlobStoreConfig.get().getPrefix(), is(equalTo("jenkins_data/")));
final DescriptorExtensionList<ArtifactManagerFactory, ArtifactManagerFactoryDescriptor> artifactManagers = ArtifactManagerFactoryDescriptor.all();
final DescriptorExtensionList<ArtifactManagerFactory, ArtifactManagerFactoryDescriptor> artifactManagers =
ArtifactManagerFactoryDescriptor.all();
assertThat(artifactManagers, hasSize(1));
}
}

View File

@ -1,5 +1,11 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertTrue;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import java.util.List;
@ -11,24 +17,18 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertTrue;
public class ArtifactoryTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("ARTIFACTORY_PASSWORD", "password123"))
.around(new JenkinsConfiguredWithReadmeRule());
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables().set("ARTIFACTORY_PASSWORD", "password123"))
.around(new JenkinsConfiguredWithReadmeRule());
@Test
@ConfiguredWithReadme(value = "artifactory/README.md")
public void configure_artifactory() {
final Jenkins jenkins = Jenkins.get();
final ArtifactoryBuilder.DescriptorImpl descriptor = (ArtifactoryBuilder.DescriptorImpl) jenkins.getDescriptor(ArtifactoryBuilder.class);
final ArtifactoryBuilder.DescriptorImpl descriptor =
(ArtifactoryBuilder.DescriptorImpl) jenkins.getDescriptor(ArtifactoryBuilder.class);
assertTrue(descriptor.getUseCredentialsPlugin());
final List<JFrogPlatformInstance> jfrogInstances = descriptor.getJfrogInstances();
@ -39,7 +39,12 @@ public class ArtifactoryTest {
assertThat(jfrogInstances.get(0).getDistributionUrl(), is(equalTo("http://acme.com/distribution")));
assertThat(jfrogInstances.get(0).getDeployerCredentialsConfig().getCredentialsId(), is(equalTo("artifactory")));
assertThat(jfrogInstances.get(0).getResolverCredentialsConfig().getUsername(), is(equalTo("artifactory_user")));
assertThat(jfrogInstances.get(0).getResolverCredentialsConfig().getPassword().getPlainText(), is(equalTo("password123")));
assertThat(
jfrogInstances
.get(0)
.getResolverCredentialsConfig()
.getPassword()
.getPlainText(),
is(equalTo("password123")));
}
}

View File

@ -1,14 +1,14 @@
package io.jenkins.plugins.casc;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.junit.Rule;
import org.junit.Test;
import static io.jenkins.plugins.casc.misc.Util.convertYamlFileToJson;
import static io.jenkins.plugins.casc.misc.Util.validateSchema;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.junit.Rule;
import org.junit.Test;
public class AzureKeyVaultTest {
@Rule
@ -16,8 +16,6 @@ public class AzureKeyVaultTest {
@Test
public void validJsonSchema() throws Exception {
assertThat(
validateSchema(convertYamlFileToJson(this, "azureKeyVault.yml")),
empty());
assertThat(validateSchema(convertYamlFileToJson(this, "azureKeyVault.yml")), empty());
}
}

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import hudson.model.Node.Mode;
import hudson.model.Slave;
import hudson.plugins.sshslaves.SSHLauncher;
@ -9,11 +14,6 @@ import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BuildAgentsTest {
@Rule
@ -24,19 +24,21 @@ public class BuildAgentsTest {
public void configure_build_agents() {
assertThat(j.getInstance().getComputers().length, is(3));
Slave slave = (Slave)j.getInstance().getNode("utility-node");
Slave slave = (Slave) j.getInstance().getNode("utility-node");
assertThat(slave.getRemoteFS(), is("/home/user1"));
JNLPLauncher jnlpLauncher = ((JNLPLauncher)slave.getLauncher());
JNLPLauncher jnlpLauncher = ((JNLPLauncher) slave.getLauncher());
assertThat(jnlpLauncher.getWorkDirSettings().getWorkDirPath(), is("/tmp"));
assertThat(jnlpLauncher.getWorkDirSettings().getInternalDir(), is("remoting"));
assertThat(jnlpLauncher.getWorkDirSettings().getInternalDir(), is("remoting2"));
assertTrue(jnlpLauncher.getWorkDirSettings().isDisabled());
assertFalse(jnlpLauncher.getWorkDirSettings().isFailIfWorkDirIsMissing());
assertTrue(jnlpLauncher.isWebSocket());
assertThat(jnlpLauncher.tunnel, is("some.proxy"));
assertThat(j.getInstance().getNode("utility-node-2").getNumExecutors(), is(4));
assertThat(j.getInstance().getNode("utility-node-2").getMode(), is(Mode.NORMAL));
slave = (Slave)j.getInstance().getNode("utility-node-2");
slave = (Slave) j.getInstance().getNode("utility-node-2");
assertThat(slave.getRemoteFS(), is("/home/user2"));
SSHLauncher launcher = ((SSHLauncher)slave.getLauncher());
SSHLauncher launcher = ((SSHLauncher) slave.getLauncher());
assertThat(launcher.getHost(), is("192.168.1.1"));
assertThat(launcher.getPort(), is(22));
assertThat(launcher.getCredentialsId(), is("test"));

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.jenkinsci.lib.configprovider.model.Config;
@ -8,11 +13,6 @@ import org.jenkinsci.plugins.configfiles.maven.MavenSettingsConfig;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
/**
* @author <a href="mailto:VictorMartinezRubio@gmail.com">Victor Martinez</a>
*/
@ -41,7 +41,8 @@ public class ConfigFileProviderTest {
assertThat(config.comment, is("dummy xml config"));
assertThat(config.content, containsString("<root><dummy test=\"abc\"></dummy></root>"));
MavenSettingsConfig mavenSettings = (MavenSettingsConfig) GlobalConfigFiles.get().getById("maven-test");
MavenSettingsConfig mavenSettings =
(MavenSettingsConfig) GlobalConfigFiles.get().getById("maven-test");
assertThat(mavenSettings.name, is("DummySettings"));
assertThat(mavenSettings.comment, is("dummy settings"));
assertThat(mavenSettings.isReplaceAll, is(false));

View File

@ -1,5 +1,13 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.jvnet.hudson.test.JenkinsMatchers.hasPlainText;
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey;
import com.cloudbees.plugins.credentials.Credentials;
@ -30,32 +38,24 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.jvnet.hudson.test.JenkinsMatchers.hasPlainText;
public class CredentialsReadmeTest {
public static final String PASSPHRASE = "passphrase";
public static final String PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIICXgIBAAKBgQC2xOoDBS+RQiwYN+rY0YXYQ/WwmC9ICH7BCXfLUBSHAkF2Dvd0\n"
+ "cvM2Ph2nOPiHdntrvD8JkzIv+S1RIqlBrzK6NRQ0ojoCvyawzY3cgzfQ4dfaOqUF\n"
+ "2bn4PscioLlq+Pbi3KYYwWUFue2iagRIxp0+/3F5WqOWPPy1twW7ddWPLQIDAQAB\n"
+ "AoGBAKOX7DKZ4LLvfRKMcpxyJpCme/L+tUuPtw1IUT7dxhH2deubh+lmvsXtoZM9\n"
+ "jk+KQPz0+aOzanfAXMzD7qZJkGfQ91aG8OiD+YJnRqOc6C6vQBXiZgeHRqWH0VMG\n"
+ "rp9Xqd8MxEYScaJYMwoHiBCG/cb3c4kpEpZ03IzkekZdXlmhAkEA7iFEk5k1BZ1+\n"
+ "BnKN9LxLR0EOKoSFJjxBihRP6+UD9BF+/1AlKlLW4hSq4458ppV5Wt4glHTcAQi/\n"
+ "U+wOOz6DyQJBAMR8G0yjtmLjMBy870GaDxmwWjqSeYwPoHbvRTOml8Fz9fP4gBMi\n"
+ "PUEGJaEHMuPECIegZ93kwAGBT51Q7AZcukUCQGGmnNOWISsjUXndYh85U/ltURzY\n"
+ "aS2rygiQmdGXgY6F2jliqUr424ushAN6+9zoMPK1YlDetxVpe+QzSga7dRkCQQCB\n"
+ "+DI6rORdXziZGeUNuPGaJYxZyEA8hK25Xqag9ubVYXZlLpDRl0l7dKx5awCfpzGZ\n"
+ "PWLXZZQYqsfWIQwvXTEdAkEA2bziyReYAb9fi17alcvwZXGzyyMY8WOGns8NZKcq\n"
+ "INF8D3PDpcCyOvQI/TS3qHYmGyWdHiKCWsgBqE6kyjqpNQ==\n"
+ "-----END RSA PRIVATE KEY-----\n";
+ "MIICXgIBAAKBgQC2xOoDBS+RQiwYN+rY0YXYQ/WwmC9ICH7BCXfLUBSHAkF2Dvd0\n"
+ "cvM2Ph2nOPiHdntrvD8JkzIv+S1RIqlBrzK6NRQ0ojoCvyawzY3cgzfQ4dfaOqUF\n"
+ "2bn4PscioLlq+Pbi3KYYwWUFue2iagRIxp0+/3F5WqOWPPy1twW7ddWPLQIDAQAB\n"
+ "AoGBAKOX7DKZ4LLvfRKMcpxyJpCme/L+tUuPtw1IUT7dxhH2deubh+lmvsXtoZM9\n"
+ "jk+KQPz0+aOzanfAXMzD7qZJkGfQ91aG8OiD+YJnRqOc6C6vQBXiZgeHRqWH0VMG\n"
+ "rp9Xqd8MxEYScaJYMwoHiBCG/cb3c4kpEpZ03IzkekZdXlmhAkEA7iFEk5k1BZ1+\n"
+ "BnKN9LxLR0EOKoSFJjxBihRP6+UD9BF+/1AlKlLW4hSq4458ppV5Wt4glHTcAQi/\n"
+ "U+wOOz6DyQJBAMR8G0yjtmLjMBy870GaDxmwWjqSeYwPoHbvRTOml8Fz9fP4gBMi\n"
+ "PUEGJaEHMuPECIegZ93kwAGBT51Q7AZcukUCQGGmnNOWISsjUXndYh85U/ltURzY\n"
+ "aS2rygiQmdGXgY6F2jliqUr424ushAN6+9zoMPK1YlDetxVpe+QzSga7dRkCQQCB\n"
+ "+DI6rORdXziZGeUNuPGaJYxZyEA8hK25Xqag9ubVYXZlLpDRl0l7dKx5awCfpzGZ\n"
+ "PWLXZZQYqsfWIQwvXTEdAkEA2bziyReYAb9fi17alcvwZXGzyyMY8WOGns8NZKcq\n"
+ "INF8D3PDpcCyOvQI/TS3qHYmGyWdHiKCWsgBqE6kyjqpNQ==\n"
+ "-----END RSA PRIVATE KEY-----\n";
public static final String PASSWORD = "password";
public static final String TEXT = "text";
public static final String ACCESS_KEY = "access-key";
@ -67,19 +67,14 @@ public class CredentialsReadmeTest {
public EnvVarsRule environment = new EnvVarsRule();
@Rule
public RuleChain chain = RuleChain
.outerRule(environment)
.around(j);
public RuleChain chain = RuleChain.outerRule(environment).around(j);
@Test
@ConfiguredWithReadme("credentials/README.md#0")
@Envs({
@Env(name = "SUDO_PASSWORD", value = "SUDO")
})
@Envs({@Env(name = "SUDO_PASSWORD", value = "SUDO")})
public void testDomainScopedCredentials() {
List<StandardUsernamePasswordCredentials> creds = CredentialsProvider
.lookupCredentials(StandardUsernamePasswordCredentials.class,
Jenkins.getInstanceOrNull(), null, Collections.emptyList());
List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(
StandardUsernamePasswordCredentials.class, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertThat(creds.size(), is(1));
StandardUsernamePasswordCredentials cred = creds.get(0);
assertThat(cred.getId(), is("sudo_password"));
@ -102,17 +97,17 @@ public class CredentialsReadmeTest {
@Env(name = "SECRET_CERT_FILE_PATH", value = TEST_CERT),
})
public void testGlobalScopedCredentials() throws Exception {
List<Credentials> creds = CredentialsProvider.lookupCredentials(
Credentials.class, Jenkins.get(), null, Collections.emptyList());
List<Credentials> creds =
CredentialsProvider.lookupCredentials(Credentials.class, Jenkins.get(), null, Collections.emptyList());
assertThat(creds, hasSize(8));
for (Credentials credentials : creds) {
if (credentials instanceof BasicSSHUserPrivateKey) {
BasicSSHUserPrivateKey key = (BasicSSHUserPrivateKey) credentials;
assertThat(key.getPassphrase(), hasPlainText(PASSPHRASE));
assertThat(key.getPrivateKey(), equalTo(PRIVATE_KEY));
assertThat(key.getId(), anyOf(
is("ssh_with_passphrase_provided"),
is("ssh_with_passphrase_provided_via_file")));
assertThat(
key.getId(),
anyOf(is("ssh_with_passphrase_provided"), is("ssh_with_passphrase_provided_via_file")));
assertThat(key.getUsername(), is("ssh_root"));
assertThat(key.getScope(), is(CredentialsScope.SYSTEM));
} else if (credentials instanceof UsernamePasswordCredentials) {
@ -142,18 +137,20 @@ public class CredentialsReadmeTest {
CertificateCredentialsImpl cert = (CertificateCredentialsImpl) credentials;
assertThat(cert.getId(), is("secret-certificate"));
assertThat(cert.getPassword(), hasPlainText(PASSWORD));
byte[] fileContent = Files.readAllBytes(Paths.get(getClass().getResource(TEST_CERT).toURI()));
SecretBytes secretBytes = SecretBytes
.fromString(Base64.getEncoder().encodeToString(fileContent));
byte[] fileContent = Files.readAllBytes(
Paths.get(getClass().getResource(TEST_CERT).toURI()));
SecretBytes secretBytes =
SecretBytes.fromString(Base64.getEncoder().encodeToString(fileContent));
UploadedKeyStoreSource keyStoreSource = (UploadedKeyStoreSource) cert.getKeyStoreSource();
assertThat(keyStoreSource.getUploadedKeystore().getPlainData(),
is(secretBytes.getPlainData()));
assertThat(keyStoreSource.getUploadedKeystore().getPlainData(), is(secretBytes.getPlainData()));
assertThat(cert.getKeyStore().containsAlias("1"), is(true));
assertThat(cert.getKeyStore().getCertificate("1").getType(), is("X.509"));
assertThat(CredentialsNameProvider.name(cert), is("EMAILADDRESS=me@myhost.mydomain, CN=pkcs12, O=Fort-Funston, L=SanFrancisco, ST=CA, C=US (my secret cert)"));
assertThat(
CredentialsNameProvider.name(cert),
is(
"EMAILADDRESS=me@myhost.mydomain, CN=pkcs12, O=Fort-Funston, L=SanFrancisco, ST=CA, C=US (my secret cert)"));
assertThat(cert.getScope(), is(CredentialsScope.GLOBAL));
}
}
}
}

View File

@ -1,5 +1,13 @@
package io.jenkins.plugins.casc;
import static java.util.Objects.requireNonNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
@ -22,14 +30,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static java.util.Objects.requireNonNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class CredentialsTest {
@Rule
@ -38,29 +38,31 @@ public class CredentialsTest {
@ConfiguredWithCode("GlobalCredentials.yml")
@Test
public void testGlobalScopedCredentials() {
List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList());
List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(
StandardUsernamePasswordCredentials.class, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertThat(creds.size(), is(1));
assertEquals("user1", creds.get(0).getId());
assertEquals("Administrator", creds.get(0).getUsername());
assertEquals("secretPassword", creds.get(0).getPassword().getPlainText());
List<BasicSSHUserPrivateKey> creds2 = CredentialsProvider.lookupCredentials(BasicSSHUserPrivateKey.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList());
List<BasicSSHUserPrivateKey> creds2 = CredentialsProvider.lookupCredentials(
BasicSSHUserPrivateKey.class, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertThat(creds2.size(), is(1));
BasicSSHUserPrivateKey basicSSHUserPrivateKey = creds2.get(0);
assertEquals("agentuser", basicSSHUserPrivateKey.getUsername());
assertEquals("password", basicSSHUserPrivateKey.getPassphrase().getPlainText());
assertEquals("ssh private key used to connect ssh slaves", basicSSHUserPrivateKey.getDescription());
assertThat(basicSSHUserPrivateKey.getPrivateKeySource().getPrivateKeys().size(), is(1));
String directKey = basicSSHUserPrivateKey.getPrivateKeySource().getPrivateKeys().get(0);
String directKey =
basicSSHUserPrivateKey.getPrivateKeySource().getPrivateKeys().get(0);
assertThat(directKey, is("sp0ds9d+skkfjf"));
}
@ConfiguredWithCode("CredentialsWithDomain.yml")
@Test
public void testDomainScopedCredentials() {
List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList());
List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(
StandardUsernamePasswordCredentials.class, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertThat(creds.size(), is(1));
assertEquals("user1", creds.get(0).getId());
assertEquals("Administrator", creds.get(0).getUsername());
@ -79,12 +81,17 @@ public class CredentialsTest {
final Mapping mapping = node.asMapping();
Mapping fileCredential = mapping.get("system")
.asMapping()
.get("domainCredentials")
.asSequence().get(0)
.asMapping().get("credentials")
.asSequence().get(2)
.asMapping().get("file").asMapping();
.asMapping()
.get("domainCredentials")
.asSequence()
.get(0)
.asMapping()
.get("credentials")
.asSequence()
.get(2)
.asMapping()
.get("file")
.asMapping();
assertThat(fileCredential.getScalarValue("scope"), is("GLOBAL"));
assertThat(fileCredential.getScalarValue("id"), is("secret-file"));
@ -106,10 +113,15 @@ public class CredentialsTest {
Mapping sshCredential = mapping.get("system")
.asMapping()
.get("domainCredentials")
.asSequence().get(0)
.asMapping().get("credentials")
.asSequence().get(1)
.asMapping().get("basicSSHUserPrivateKey").asMapping();
.asSequence()
.get(0)
.asMapping()
.get("credentials")
.asSequence()
.get(1)
.asMapping()
.get("basicSSHUserPrivateKey")
.asMapping();
assertThat(sshCredential.getScalarValue("scope"), is("SYSTEM"));
assertThat(sshCredential.getScalarValue("id"), is("agent-private-key"));
@ -117,10 +129,13 @@ public class CredentialsTest {
String passphrase = sshCredential.getScalarValue("passphrase");
assertThat(passphrase, not("password"));
assertThat(requireNonNull(Secret.decrypt(passphrase), "Failed to decrypt the password from " + passphrase)
.getPlainText(), is("password"));
assertThat(
requireNonNull(Secret.decrypt(passphrase), "Failed to decrypt the password from " + passphrase)
.getPlainText(),
is("password"));
String sshKeyExported = sshCredential.get("privateKeySource")
String sshKeyExported = sshCredential
.get("privateKeySource")
.asMapping()
.get("directEntry")
.asMapping()
@ -136,20 +151,20 @@ public class CredentialsTest {
@Issue("SECURITY-1404")
public void checkUsernamePasswordIsSecret() {
Attribute a = getFromDatabound(UsernamePasswordCredentialsImpl.class, "password");
assertTrue("Attribute 'password' should be secret", a.isSecret(
new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "1", "2", "3", "4")));
assertTrue(
"Attribute 'password' should be secret",
a.isSecret(new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "1", "2", "3", "4")));
}
@NonNull
private <T> Attribute<T,?> getFromDatabound(Class<T> clazz, @NonNull String attributeName) {
private <T> Attribute<T, ?> getFromDatabound(Class<T> clazz, @NonNull String attributeName) {
DataBoundConfigurator<T> cfg = new DataBoundConfigurator<>(clazz);
Set<Attribute<T,?>> attributes = cfg.describe();
for (Attribute<T,?> a : attributes) {
if(attributeName.equals(a.getName())) {
Set<Attribute<T, ?>> attributes = cfg.describe();
for (Attribute<T, ?> a : attributes) {
if (attributeName.equals(a.getName())) {
return a;
}
}
throw new AssertionError("Cannot find databound attribute " + attributeName + " in " + clazz);
}
}

View File

@ -1,38 +0,0 @@
package io.jenkins.plugins.casc;
import de.theit.jenkins.crowd.CrowdSecurityRealm;
import hudson.security.SecurityRealm;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.jvnet.hudson.test.JenkinsMatchers.hasPlainText;
public class Crowd2Test {
public static final String PASSWORD_123 = "password123";
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("CROWD_PASSWORD", PASSWORD_123))
.around(new JenkinsConfiguredWithReadmeRule());
@Test
@ConfiguredWithReadme("crowd2/README.md")
public void configure_artifact_manager() {
SecurityRealm realm = Jenkins.get().getSecurityRealm();
assertThat(realm, instanceOf(CrowdSecurityRealm.class));
CrowdSecurityRealm securityRealm = (CrowdSecurityRealm) realm;
assertThat(securityRealm.applicationName, is("jenkins"));
assertThat(securityRealm.group, is("jenkins-users"));
assertThat(securityRealm.url, is("http://crowd.company.io"));
assertThat(securityRealm.password, hasPlainText(PASSWORD_123));
}
}

View File

@ -1,5 +1,8 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.cloudbees.jenkins.plugins.customtools.CustomTool;
import com.cloudbees.jenkins.plugins.customtools.CustomTool.DescriptorImpl;
import hudson.tools.CommandInstaller;
@ -11,9 +14,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -22,7 +22,9 @@ public class CustomToolsTest {
@Rule
public JenkinsConfiguredWithCodeRule j = new JenkinsConfiguredWithCodeRule();
@Test @Issue("#97") @Ignore
@Test
@Issue("#97")
@Ignore
@ConfiguredWithCode(value = "CustomToolsTest.yml")
public void configure_custom_tools() {
DescriptorImpl descriptor = (DescriptorImpl) j.jenkins.getDescriptorOrDie(CustomTool.class);

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.nirima.jenkins.plugins.docker.DockerCloud;
import com.nirima.jenkins.plugins.docker.DockerTemplate;
import com.nirima.jenkins.plugins.docker.strategy.DockerOnceRetentionStrategy;
@ -10,11 +15,6 @@ import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -30,11 +30,22 @@ public class DockerCloudTest {
assertNotNull(docker);
assertNotNull(docker.getDockerApi());
assertNotNull(docker.getDockerApi().getDockerHost());
assertEquals("unix:///var/run/docker.sock", docker.getDockerApi().getDockerHost().getUri());
assertEquals(
"unix:///var/run/docker.sock",
docker.getDockerApi().getDockerHost().getUri());
final DockerTemplate template = docker.getTemplate("jenkins/agent");
checkTemplate(template, "docker-agent", "jenkins", "/home/jenkins/agent", "10",
new String[] { "type=tmpfs,destination=/run", "type=bind,source=/var/run/docker.sock,destination=/var/run/docker.sock", "type=volume,src=hello,dst=/world" },
checkTemplate(
template,
"docker-agent",
"jenkins",
"/home/jenkins/agent",
"10",
new String[] {
"type=tmpfs,destination=/run",
"type=bind,source=/var/run/docker.sock,destination=/var/run/docker.sock",
"type=volume,src=hello,dst=/world"
},
"hello=world\nfoo=bar");
assertTrue(template.getRetentionStrategy() instanceof DockerOnceRetentionStrategy);
assertEquals(1, ((DockerOnceRetentionStrategy) template.getRetentionStrategy()).getIdleMinutes());
@ -47,34 +58,68 @@ public class DockerCloudTest {
assertNotNull(docker);
assertNotNull(docker.getDockerApi());
assertNotNull(docker.getDockerApi().getDockerHost());
assertEquals("unix:///var/run/docker.sock", docker.getDockerApi().getDockerHost().getUri());
assertEquals(
"unix:///var/run/docker.sock",
docker.getDockerApi().getDockerHost().getUri());
DockerTemplate template = docker.getTemplate(Label.get("docker-agent"));
checkTemplate(template, "docker-agent", "jenkins", "/home/jenkins/agent", "10",
new String[] { "type=tmpfs,destination=/run", "type=bind,source=/var/run/docker.sock,destination=/var/run/docker.sock", "type=volume,src=hello,dst=/world" },
checkTemplate(
template,
"docker-agent",
"jenkins",
"/home/jenkins/agent",
"10",
new String[] {
"type=tmpfs,destination=/run",
"type=bind,source=/var/run/docker.sock,destination=/var/run/docker.sock",
"type=volume,src=hello,dst=/world"
},
"hello=world\nfoo=bar");
ConfigurationAsCode.get().configure(getClass().getResource("DockerCloudTest2.yml").toExternalForm());
ConfigurationAsCode.get()
.configure(getClass().getResource("DockerCloudTest2.yml").toExternalForm());
docker = DockerCloud.getCloudByName("docker");
assertNotNull(docker);
assertNotNull(docker.getDockerApi());
assertNotNull(docker.getDockerApi().getDockerHost());
assertEquals("unix:///var/run/docker.sock", docker.getDockerApi().getDockerHost().getUri());
assertEquals(
"unix:///var/run/docker.sock",
docker.getDockerApi().getDockerHost().getUri());
template = docker.getTemplate(Label.get("docker-agent"));
checkTemplate(template, "docker-agent", "jenkins", "/home/jenkins/agent", "10",
new String[] { "type=volume,source=hello,destination=/hello", "type=volume,source=world,destination=/world"},
checkTemplate(
template,
"docker-agent",
"jenkins",
"/home/jenkins/agent",
"10",
new String[] {
"type=volume,source=hello,destination=/hello", "type=volume,source=world,destination=/world"
},
"hello=world\nfoo=bar");
template = docker.getTemplate(Label.get("generic"));
checkTemplate(template, "generic", "jenkins", "/home/jenkins/agent2", "5",
new String[] { "type=volume,source=hello,destination=/hello", "type=volume,source=world,destination=/world"},
checkTemplate(
template,
"generic",
"jenkins",
"/home/jenkins/agent2",
"5",
new String[] {
"type=volume,source=hello,destination=/hello", "type=volume,source=world,destination=/world"
},
"hello=world\nfoo=bar");
}
private void checkTemplate(DockerTemplate template, String labelString, String user, String remoteFs,
String instanceCapStr, String[] mounts, String environmentsString) {
private void checkTemplate(
DockerTemplate template,
String labelString,
String user,
String remoteFs,
String instanceCapStr,
String[] mounts,
String environmentsString) {
assertNotNull(template);
assertEquals(labelString, template.getLabelString());
assertEquals(user, ((DockerComputerAttachConnector) template.getConnector()).getUser());

View File

@ -1,13 +1,5 @@
package io.jenkins.plugins.casc;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import io.jenkins.plugins.casc.model.CNode;
import org.jenkinsci.plugins.docker.workflow.declarative.GlobalConfig;
import org.junit.ClassRule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static io.jenkins.plugins.casc.misc.Util.getUnclassifiedRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
@ -16,6 +8,14 @@ import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import io.jenkins.plugins.casc.model.CNode;
import org.jenkinsci.plugins.docker.workflow.declarative.GlobalConfig;
import org.junit.ClassRule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
public class DockerWorkflowSymbolTest {
@ClassRule
@ -46,5 +46,4 @@ public class DockerWorkflowSymbolTest {
assertThat(exported, is(expected));
}
}

View File

@ -1,14 +1,14 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.jenkinsci.plugins.docker.workflow.declarative.GlobalConfig;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class DockerWorkflowTest {
@Rule

View File

@ -1,5 +1,15 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.amazonaws.services.ec2.model.InstanceType;
import hudson.model.labels.LabelAtom;
import hudson.plugins.ec2.AMITypeData;
@ -13,16 +23,6 @@ import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class EC2CloudTest {
@Rule
@ -31,7 +31,7 @@ public class EC2CloudTest {
@Test
@ConfiguredWithReadme("ec2/README.md")
public void configure_ec2_cloud() {
final AmazonEC2Cloud ec2Cloud = (AmazonEC2Cloud) Jenkins.get().getCloud("ec2-ec2");
final AmazonEC2Cloud ec2Cloud = (AmazonEC2Cloud) Jenkins.get().getCloud("ec2");
assertNotNull(ec2Cloud);
assertTrue(ec2Cloud.isUseInstanceProfileForCredentials());
@ -69,7 +69,6 @@ public class EC2CloudTest {
assertThat(unixData.getSlaveCommandPrefix(), equalTo("sudo -u jenkins"));
assertThat(unixData.getSshPort(), equalTo("61120"));
slaveTemplate = templates.get(1);
assertThat(slaveTemplate.getDisplayName(), containsString("Auto configured EC2 Agent Large"));
assertFalse(slaveTemplate.getAssociatePublicIp());

View File

@ -1,5 +1,11 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import hudson.ExtensionList;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
@ -9,12 +15,6 @@ import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class EssentialsTest {
@Rule
public JenkinsConfiguredWithCodeRule j = new JenkinsConfiguredWithCodeRule();
@ -25,7 +25,8 @@ public class EssentialsTest {
final Jenkins jenkins = Jenkins.get();
assertEquals("Welcome to Jenkins Essentials!", jenkins.getSystemMessage());
final ExtensionList<MetricsAccessKey.DescriptorImpl> metricsDescriptors = ExtensionList.lookup(MetricsAccessKey.DescriptorImpl.class);
final ExtensionList<MetricsAccessKey.DescriptorImpl> metricsDescriptors =
ExtensionList.lookup(MetricsAccessKey.DescriptorImpl.class);
assertNotNull(metricsDescriptors);
assertThat(metricsDescriptors, hasSize(1));
@ -44,6 +45,6 @@ public class EssentialsTest {
assertThat(accessKey.isCanMetrics(), is(false));
assertThat(accessKey.getOrigins(), is("*"));
//metricsDescriptor.g
// metricsDescriptor.g
}
}

View File

@ -1,5 +1,8 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import hudson.ExtensionList;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -8,9 +11,6 @@ import org.jenkinsci.plugins.ewm.steps.ExwsStep;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
/**
* @author <a href="mailto:VictorMartinezRubio@gmail.com">Victor Martinez</a>
*/
@ -26,7 +26,8 @@ public class ExternalWorkspaceManagerTest {
// https://github.com/jenkinsci/external-workspace-manager-plugin/pull/68
// Let's run some basic validations
ExwsAllocateStep.DescriptorImpl descriptor = ExtensionList.lookupSingleton(ExwsAllocateStep.DescriptorImpl.class);
ExwsAllocateStep.DescriptorImpl descriptor =
ExtensionList.lookupSingleton(ExwsAllocateStep.DescriptorImpl.class);
assertThat(descriptor.getDiskPools(), hasSize(1));
ExwsStep.DescriptorImpl globalTemplateDescriptor = ExtensionList.lookupSingleton(ExwsStep.DescriptorImpl.class);

View File

@ -0,0 +1,34 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import jenkins.model.GlobalConfiguration;
import org.jenkinsci.plugins.gitclient.GitHostKeyVerificationConfiguration;
import org.jenkinsci.plugins.gitclient.verifier.ManuallyProvidedKeyVerificationStrategy;
import org.jenkinsci.plugins.gitclient.verifier.SshHostKeyVerificationStrategy;
import org.junit.ClassRule;
import org.junit.Test;
/**
* @author Mark Waite
*/
public class GitHostKeyVerificationTest {
@ClassRule
@ConfiguredWithReadme("git-client/README.md#2")
public static JenkinsConfiguredWithReadmeRule j = new JenkinsConfiguredWithReadmeRule();
@Test
public void git_client_host_key_verifier() {
final GitHostKeyVerificationConfiguration config =
GlobalConfiguration.all().get(GitHostKeyVerificationConfiguration.class);
SshHostKeyVerificationStrategy strategy = config.getSshHostKeyVerificationStrategy();
assertThat(strategy, instanceOf(ManuallyProvidedKeyVerificationStrategy.class));
ManuallyProvidedKeyVerificationStrategy manually = (ManuallyProvidedKeyVerificationStrategy) strategy;
assertThat(manually.getApprovedHostKeys(), startsWith("bitbucket.org ssh-ed25519 "));
}
}

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertTrue;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import jenkins.model.GlobalConfiguration;
@ -8,11 +13,6 @@ import org.jenkinsci.plugins.github.config.GitHubServerConfig;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertTrue;
/**
* @author v1v (Victor Martinez)
*/
@ -33,6 +33,5 @@ public class GitHubTest {
assertThat(config.getCredentialsId(), is("[GitHubEEUser]"));
assertThat(config.getName(), is("InHouse GitHub EE"));
assertTrue(config.isManageHooks());
}
}

View File

@ -1,5 +1,8 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.domains.DomainCredentials;
@ -15,18 +18,15 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="osdomin@yahoo.es">osdomin</a>
*/
public class GitLabConfigurationTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("BIND_TOKEN", "qwertyuiopasdfghjklzxcvbnm"))
.around(new JenkinsConfiguredWithReadmeRule());
public RuleChain chain = RuleChain.outerRule(
new EnvironmentVariables().set("BIND_TOKEN", "qwertyuiopasdfghjklzxcvbnm"))
.around(new JenkinsConfiguredWithReadmeRule());
@Test
@ConfiguredWithReadme("gitlab/README.md")
@ -37,18 +37,21 @@ public class GitLabConfigurationTest {
final DomainCredentials gitLabCredential = domainCredentials.get(0);
assertEquals(Domain.global(), gitLabCredential.getDomain());
assertEquals(1, gitLabCredential.getCredentials().size());
final GitLabApiToken apiToken = (GitLabApiToken)gitLabCredential.getCredentials().get(0);
final GitLabApiToken apiToken =
(GitLabApiToken) gitLabCredential.getCredentials().get(0);
assertEquals("gitlab_token", apiToken.getId());
assertEquals("qwertyuiopasdfghjklzxcvbnm", apiToken.getApiToken().getPlainText());
assertEquals("Gitlab Token", apiToken.getDescription());
}
@Test
@ConfiguredWithReadme("gitlab/README.md")
public void configure_gitlab_connection() {
final Jenkins jenkins = Jenkins.get();
final GitLabConnectionConfig gitLabConnections = jenkins.getDescriptorByType(GitLabConnectionConfig.class);
assertEquals(1, gitLabConnections.getConnections().size());
final GitLabConnection gitLabConnection = gitLabConnections.getConnections().get(0);
final GitLabConnection gitLabConnection =
gitLabConnections.getConnections().get(0);
assertEquals("gitlab_token", gitLabConnection.getApiTokenId());
assertEquals("my_gitlab_server", gitLabConnection.getName());
assertEquals("autodetect", gitLabConnection.getClientBuilderId());

View File

@ -1,5 +1,7 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.browser.AssemblaWeb;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
@ -18,8 +20,6 @@ import org.junit.rules.RuleChain;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.LoggerRule;
import static org.junit.Assert.assertEquals;
/**
* Tests for Git plugin global configurations.
*/
@ -29,8 +29,8 @@ public class GitTest {
public LoggerRule logging = new LoggerRule();
@Rule
public RuleChain chain= RuleChain
.outerRule(logging.record(Logger.getLogger(Attribute.class.getName()), Level.INFO).capture(2048))
public RuleChain chain = RuleChain.outerRule(logging.record(Logger.getLogger(Attribute.class.getName()), Level.INFO)
.capture(2048))
.around(j);
@After
@ -45,13 +45,13 @@ public class GitTest {
@ConfiguredWithCode("GitTest.yml")
public void checkAssemblaWebIsLoaded() {
final Jenkins jenkins = Jenkins.get();
final GlobalLibraries libs = jenkins.getExtensionList(GlobalConfiguration.class)
.get(GlobalLibraries.class);
final GlobalLibraries libs =
jenkins.getExtensionList(GlobalConfiguration.class).get(GlobalLibraries.class);
LibraryConfiguration lib = libs.getLibraries().get(0);
SCMRetriever retriever = (SCMRetriever) lib.getRetriever();
GitSCM scm = (GitSCM) retriever.getScm();
AssemblaWeb browser = (AssemblaWeb)scm.getBrowser();
AssemblaWeb browser = (AssemblaWeb) scm.getBrowser();
assertEquals("assembla.acmecorp.com", browser.getRepoUrl());
}
}

View File

@ -1,5 +1,12 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import hudson.plugins.git.GitTool;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -8,21 +15,13 @@ import jenkins.model.Jenkins;
import org.junit.ClassRule;
import org.junit.Test;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
public class GitToolInstallationTest {
@ClassRule
@ConfiguredWithReadme("git/README.md")
@ConfiguredWithReadme("git-client/README.md#0")
public static JenkinsConfiguredWithReadmeRule j = new JenkinsConfiguredWithReadmeRule();
@Test
@ -30,7 +29,8 @@ public class GitToolInstallationTest {
final Jenkins jenkins = Jenkins.get();
final GitTool.DescriptorImpl descriptor = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
assertEquals(2, descriptor.getInstallations().length);
assertEquals("/usr/local/bin/git", descriptor.getInstallation("another_git").getGitExe());
assertEquals(
"/usr/local/bin/git", descriptor.getInstallation("another_git").getGitExe());
assertEquals("/bin/git", descriptor.getInstallation("git").getGitExe());
}

View File

@ -1,5 +1,8 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import java.util.List;
@ -15,10 +18,6 @@ import org.jenkinsci.plugin.gitea.TagDiscoveryTrait;
import org.jenkinsci.plugin.gitea.WebhookRegistrationTrait;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.recipes.WithPlugin;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class GiteaOrganisationFolderTest {
@ -26,13 +25,13 @@ public class GiteaOrganisationFolderTest {
public JenkinsConfiguredWithCodeRule r = new JenkinsConfiguredWithCodeRule();
@Test
@WithPlugin({"branch-api.jpi", "cloudbees-folder.jpi", "scm-api.jpi", "structs.jpi"})
@ConfiguredWithCode("SeedJobTest_withGiteaOrganisation.yml")
public void configure_gitea_organisation_folder_seed_job() {
OrganizationFolder folder = (OrganizationFolder) r.jenkins.getItem("Gitea Organization Folder");
assertNotNull(folder);
GiteaSCMNavigator organization = (GiteaSCMNavigator) folder.getNavigators().get(0);
GiteaSCMNavigator organization =
(GiteaSCMNavigator) folder.getNavigators().get(0);
assertNotNull(organization);
assertEquals("gitea-token", organization.getCredentialsId());
@ -47,23 +46,25 @@ public class GiteaOrganisationFolderTest {
SCMTrait<?> trait2 = traits.get(2);
assertEquals(BranchDiscoveryTrait.class, trait2.getClass());
assertEquals(1, ((BranchDiscoveryTrait)trait2).getStrategyId());
assertEquals(1, ((BranchDiscoveryTrait) trait2).getStrategyId());
SCMTrait<?> trait3 = traits.get(3);
assertEquals(OriginPullRequestDiscoveryTrait.class, trait3.getClass());
assertEquals(2, ((OriginPullRequestDiscoveryTrait)trait3).getStrategyId());
assertEquals(2, ((OriginPullRequestDiscoveryTrait) trait3).getStrategyId());
SCMTrait<?> trait4 = traits.get(4);
assertEquals(ForkPullRequestDiscoveryTrait.class, trait4.getClass());
assertEquals(1, ((ForkPullRequestDiscoveryTrait)trait4).getStrategyId());
assertEquals(ForkPullRequestDiscoveryTrait.TrustContributors.class, ((ForkPullRequestDiscoveryTrait)trait4).getTrust().getClass());
assertEquals(1, ((ForkPullRequestDiscoveryTrait) trait4).getStrategyId());
assertEquals(
ForkPullRequestDiscoveryTrait.TrustContributors.class,
((ForkPullRequestDiscoveryTrait) trait4).getTrust().getClass());
SCMTrait<?> trait5 = traits.get(5);
assertEquals(WebhookRegistrationTrait.class, trait5.getClass());
assertEquals("ITEM", ((WebhookRegistrationTrait)trait5).getMode().name());
assertEquals("ITEM", ((WebhookRegistrationTrait) trait5).getMode().name());
SCMTrait<?> trait6 = traits.get(6);
assertEquals(SSHCheckoutTrait.class, trait6.getClass());
assertEquals("ssh-gitea", ((SSHCheckoutTrait)trait6).getCredentialsId());
assertEquals("ssh-gitea", ((SSHCheckoutTrait) trait6).getCredentialsId());
}
}

View File

@ -1,5 +1,8 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import jenkins.model.GlobalConfiguration;
@ -8,9 +11,6 @@ import org.jenkinsci.plugin.gitea.servers.GiteaServers;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class GiteaServerTest {
@Rule

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import hudson.security.SecurityRealm;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -10,11 +14,6 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
/**
* Purpose:
* Test that we can configure: <a href="https://plugins.jenkins.io/github-oauth"/>
@ -22,16 +21,15 @@ import static org.junit.Assert.assertEquals;
public class GithubOAuthTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("GITHUB_SECRET", "j985j8fhfhh377"))
.around(new JenkinsConfiguredWithReadmeRule());
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables().set("GITHUB_SECRET", "j985j8fhfhh377"))
.around(new JenkinsConfiguredWithReadmeRule());
@Test
@ConfiguredWithReadme("github-oauth/README.md")
public void testSampleVersionForOAuth() {
SecurityRealm realm = Jenkins.get().getSecurityRealm();
assertThat(realm, instanceOf(GithubSecurityRealm.class));
GithubSecurityRealm gsh = (GithubSecurityRealm)realm;
GithubSecurityRealm gsh = (GithubSecurityRealm) realm;
assertEquals("someId", gsh.getClientID());
assertEquals("https://api.github.com", gsh.getGithubApiUri());
assertEquals("https://github.com", gsh.getGithubWebUri());

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.model.TopLevelItem;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
@ -8,10 +12,6 @@ import jenkins.model.Jenkins;
import org.jenkinsci.plugins.github_branch_source.GitHubSCMNavigator;
import org.junit.Rule;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -20,7 +20,6 @@ public class GithubOrganisationFolderTest {
@Rule
public JenkinsConfiguredWithCodeRule j = new JenkinsConfiguredWithCodeRule();
// @Test
// Fails as Items do override submit() with manual data-binding implementation
@ConfiguredWithCode("GithubOrganisationFolderTest.yml")

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.ExtensionList;
import hudson.plugins.git.GitSCM;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
@ -7,10 +11,6 @@ import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author v1v (Victor Martinez)
*/
@ -20,7 +20,7 @@ public class GitscmTest {
public JenkinsConfiguredWithReadmeRule j = new JenkinsConfiguredWithReadmeRule();
@Test
@ConfiguredWithReadme("gitscm/README.md")
@ConfiguredWithReadme("git/README.md")
public void configure_git() {
final GitSCM.DescriptorImpl descriptor = ExtensionList.lookupSingleton(GitSCM.DescriptorImpl.class);
assertNotNull(descriptor);

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import org.jenkinsci.plugins.github_branch_source.BranchDiscoveryTrait;
@ -14,11 +18,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -32,7 +31,8 @@ public class GlobalLibrariesTest {
@ConfiguredWithCode("GlobalLibrariesGitHubTest.yml")
public void configure_global_library_using_github() {
assertEquals(1, GlobalLibraries.get().getLibraries().size());
final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0);
final LibraryConfiguration library =
GlobalLibraries.get().getLibraries().get(0);
assertEquals("jenkins-pipeline-lib", library.getName());
final SCMSourceRetriever retriever = (SCMSourceRetriever) library.getRetriever();
final GitHubSCMSource scm = (GitHubSCMSource) retriever.getScm();
@ -40,11 +40,14 @@ public class GlobalLibrariesTest {
assertEquals("jenkins-infra", scm.getRepoOwner());
assertEquals("pipeline-library", scm.getRepository());
assertEquals(3, scm.getTraits().size());
final BranchDiscoveryTrait branchDiscovery = (BranchDiscoveryTrait) scm.getTraits().get(0);
final BranchDiscoveryTrait branchDiscovery =
(BranchDiscoveryTrait) scm.getTraits().get(0);
assertEquals(1, branchDiscovery.getStrategyId());
final OriginPullRequestDiscoveryTrait prDiscovery = (OriginPullRequestDiscoveryTrait) scm.getTraits().get(1);
final OriginPullRequestDiscoveryTrait prDiscovery =
(OriginPullRequestDiscoveryTrait) scm.getTraits().get(1);
assertEquals(2, prDiscovery.getStrategyId());
final ForkPullRequestDiscoveryTrait forkDiscovery = (ForkPullRequestDiscoveryTrait) scm.getTraits().get(2);
final ForkPullRequestDiscoveryTrait forkDiscovery =
(ForkPullRequestDiscoveryTrait) scm.getTraits().get(2);
assertEquals(3, forkDiscovery.getStrategyId());
assertThat(forkDiscovery.getTrust(), instanceOf(TrustPermission.class));
}

View File

@ -1,5 +1,7 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import hudson.security.GlobalMatrixAuthorizationStrategy;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -9,8 +11,6 @@ import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Mads Nielsen
* @since 1.0
@ -23,13 +23,19 @@ public class GlobalMatrixAuthorizationTest {
@Test
@ConfiguredWithReadme("matrix-auth/README.md")
public void checkCorrectlyConfiguredPermissions() {
assertEquals("The configured instance must use the Global Matrix Authentication Strategy", GlobalMatrixAuthorizationStrategy.class, Jenkins.get().getAuthorizationStrategy().getClass());
GlobalMatrixAuthorizationStrategy gms = (GlobalMatrixAuthorizationStrategy) Jenkins.get().getAuthorizationStrategy();
assertEquals(
"The configured instance must use the Global Matrix Authentication Strategy",
GlobalMatrixAuthorizationStrategy.class,
Jenkins.get().getAuthorizationStrategy().getClass());
GlobalMatrixAuthorizationStrategy gms =
(GlobalMatrixAuthorizationStrategy) Jenkins.get().getAuthorizationStrategy();
List<String> adminPermission = new ArrayList<>(gms.getGrantedPermissions().get(Jenkins.ADMINISTER));
List<String> adminPermission =
new ArrayList<>(gms.getGrantedPermissions().get(Jenkins.ADMINISTER));
assertEquals("authenticated", adminPermission.get(0));
List<String> readPermission = new ArrayList<>(gms.getGrantedPermissions().get(Jenkins.READ));
List<String> readPermission =
new ArrayList<>(gms.getGrantedPermissions().get(Jenkins.READ));
assertEquals("anonymous", readPermission.get(0));
}
}

View File

@ -1,5 +1,12 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
@ -13,14 +20,6 @@ import jenkins.model.Jenkins;
import org.junit.ClassRule;
import org.junit.Test;
import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
public class GlobalNodePropertiesTest {
@ClassRule
@ -33,7 +32,9 @@ public class GlobalNodePropertiesTest {
DescribableList<NodeProperty<?>, NodePropertyDescriptor> nodeProperties = jenkins.getGlobalNodeProperties();
Set<Map.Entry<String, String>> entries = ((EnvironmentVariablesNodeProperty) nodeProperties.get(0)).getEnvVars().entrySet();
Set<Map.Entry<String, String>> entries = ((EnvironmentVariablesNodeProperty) nodeProperties.get(0))
.getEnvVars()
.entrySet();
assertEquals(1, entries.size());
Map.Entry<String, String> envVar = entries.iterator().next();

View File

@ -1,5 +1,12 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import hudson.ExtensionList;
import hudson.model.JDK;
import hudson.tools.InstallSourceProperty;
@ -10,13 +17,6 @@ import io.jenkins.plugins.casc.model.CNode;
import org.junit.ClassRule;
import org.junit.Test;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:vektory79@gmail.com">Viktor Verbitsky</a>
*/

View File

@ -1,5 +1,14 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.nirima.jenkins.plugins.docker.DockerCloud;
import hudson.model.Node.Mode;
import hudson.plugins.git.GitTool;
@ -18,57 +27,54 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author v1v (Victor Martinez)
*/
public class JenkinsDemoTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("ARTIFACTORY_PASSWORD", "password123"))
.around(new JenkinsConfiguredWithCodeRule());
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables().set("ARTIFACTORY_PASSWORD", "password123"))
.around(new JenkinsConfiguredWithCodeRule());
@Test
@ConfiguredWithCode("jenkins/jenkins.yaml")
public void configure_demo_yaml() {
final Jenkins jenkins = Jenkins.get();
assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
assertEquals(
"Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n",
jenkins.getSystemMessage());
assertEquals(5, jenkins.getNumExecutors());
assertEquals(2, jenkins.getScmCheckoutRetryCount());
assertEquals(Mode.NORMAL, jenkins.getMode());
assertEquals("https://ci.example.com/", jenkins.getRootUrl());
final FullControlOnceLoggedInAuthorizationStrategy strategy = (FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
final FullControlOnceLoggedInAuthorizationStrategy strategy =
(FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
assertFalse(strategy.isAllowAnonymousRead());
final DockerCloud docker = DockerCloud.getCloudByName("docker");
assertNotNull(docker);
assertNotNull(docker.getDockerApi());
assertNotNull(docker.getDockerApi().getDockerHost());
assertEquals("unix:///var/run/docker.sock", docker.getDockerApi().getDockerHost().getUri());
assertEquals(
"unix:///var/run/docker.sock",
docker.getDockerApi().getDockerHost().getUri());
final GitTool.DescriptorImpl gitTool = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
assertEquals(1, gitTool.getInstallations().length);
assertEquals(1, GlobalLibraries.get().getLibraries().size());
final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0);
final LibraryConfiguration library =
GlobalLibraries.get().getLibraries().get(0);
assertEquals("awesome-lib", library.getName());
final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
assertEquals("4441", descriptor.getSmtpPort());
assertEquals("do-not-reply@acme.org", descriptor.getReplyToAddress());
assertEquals("smtp.acme.org", descriptor.getSmtpHost() );
assertEquals("smtp.acme.org", descriptor.getSmtpHost());
final ArtifactoryBuilder.DescriptorImpl artifactory = (ArtifactoryBuilder.DescriptorImpl) jenkins.getDescriptor(ArtifactoryBuilder.class);
final ArtifactoryBuilder.DescriptorImpl artifactory =
(ArtifactoryBuilder.DescriptorImpl) jenkins.getDescriptor(ArtifactoryBuilder.class);
assertTrue(artifactory.getUseCredentialsPlugin());
final List<JFrogPlatformInstance> jfrogInstances = artifactory.getJfrogInstances();
@ -76,7 +82,12 @@ public class JenkinsDemoTest {
assertThat(jfrogInstances.get(0).getId(), is(equalTo("artifactory")));
assertThat(jfrogInstances.get(0).getUrl(), is(equalTo("http://acme.com/artifactory")));
assertThat(jfrogInstances.get(0).getResolverCredentialsConfig().getUsername(), is(equalTo("artifactory_user")));
assertThat(jfrogInstances.get(0).getResolverCredentialsConfig().getPassword().getPlainText(), is(equalTo("password123")));
assertThat(
jfrogInstances
.get(0)
.getResolverCredentialsConfig()
.getPassword()
.getPlainText(),
is(equalTo("password123")));
}
}

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import hudson.model.Node.Mode;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -7,11 +11,6 @@ import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
/**
* @author v1v (Victor Martinez)
*/
@ -24,7 +23,9 @@ public class JenkinsReadmeDemoTest {
@ConfiguredWithReadme("jenkins/README.md#0")
public void configure_demo_first_code_block() {
final Jenkins jenkins = Jenkins.get();
assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
assertEquals(
"Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n",
jenkins.getSystemMessage());
assertEquals(5, jenkins.getNumExecutors());
assertEquals(2, jenkins.getScmCheckoutRetryCount());
assertEquals(Mode.NORMAL, jenkins.getMode());

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import hudson.plugins.jira.JiraGlobalConfiguration;
import hudson.plugins.jira.JiraSite;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
@ -9,10 +13,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -32,5 +32,4 @@ public class JiraTest {
assertEquals("http://jira.codehaus.org/", sites.get(0).getUrl().toString());
assertEquals("http://issues.jenkins.io/", sites.get(1).getUrl().toString());
}
}

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import javaposse.jobdsl.plugin.GlobalJobDslSecurityConfiguration;
import jenkins.model.GlobalConfiguration;
import org.junit.Rule;
@ -8,11 +12,6 @@ import org.junit.runners.model.Statement;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.RestartableJenkinsRule;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
/**
* Created by odavid on 23/12/2017.
*/
@ -34,14 +33,17 @@ public class JobDslGlobalSecurityConfigurationTest {
}
private GlobalJobDslSecurityConfiguration getGlobalJobDslSecurityConfiguration() {
final GlobalJobDslSecurityConfiguration dslSecurity = GlobalConfiguration.all()
.get(GlobalJobDslSecurityConfiguration.class);
final GlobalJobDslSecurityConfiguration dslSecurity =
GlobalConfiguration.all().get(GlobalJobDslSecurityConfiguration.class);
assertNotNull(dslSecurity);
return dslSecurity;
}
private void configure() throws ConfiguratorException {
ConfigurationAsCode.get().configure(getClass().getResource("JobDslGlobalSecurityConfigurationTest.yml").toExternalForm());
ConfigurationAsCode.get()
.configure(getClass()
.getResource("JobDslGlobalSecurityConfigurationTest.yml")
.toExternalForm());
}
private Statement validateGlobalDSLSecurity = new Statement() {
@ -73,5 +75,4 @@ public class JobDslGlobalSecurityConfigurationTest {
assertThat("ScriptSecurity", dslSecurity.isUseScriptSecurity(), is(false));
}
};
}

View File

@ -1,30 +0,0 @@
package io.jenkins.plugins.casc;
import hudson.security.SecurityRealm;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.jenkinsci.plugins.KeycloakSecurityRealm;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
/**
* @author v1v (Victor Martinez)
*/
public class KeycloakTest {
@Rule
public JenkinsConfiguredWithReadmeRule j = new JenkinsConfiguredWithReadmeRule();
@Test
@ConfiguredWithReadme("keycloak/README.md")
public void configure_artifact_manager() {
SecurityRealm realm = j.jenkins.get().getSecurityRealm();
assertThat(realm, instanceOf(KeycloakSecurityRealm.class));
KeycloakSecurityRealm securityRealm = (KeycloakSecurityRealm)realm;
assertThat(securityRealm.getKeycloakJson(), containsString("\"auth-server-url\": \"https://my-keycloak-url/auth\""));
}
}

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.model.Node.Mode;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -13,10 +17,6 @@ import org.csanchez.jenkins.plugins.kubernetes.volumes.PodVolume;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -57,7 +57,7 @@ public class KubernetesCloudTest {
final PodVolume volume = volumes.get(0);
assertTrue(volume instanceof HostPathVolume);
assertEquals("mountPath", volume.getMountPath());
assertEquals("hostPath", ((HostPathVolume)volume).getHostPath());
assertEquals("hostPath", ((HostPathVolume) volume).getHostPath());
final List<TemplateEnvVar> envVars = template.getEnvVars();
assertEquals(1, envVars.size());
@ -71,4 +71,3 @@ public class KubernetesCloudTest {
assertEquals(Mode.EXCLUSIVE, template1.getNodeUsageMode());
}
}

View File

@ -1,17 +1,17 @@
package io.jenkins.plugins.casc;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import io.jenkins.plugins.casc.model.CNode;
import org.junit.Rule;
import org.junit.Test;
import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import io.jenkins.plugins.casc.model.CNode;
import org.junit.Rule;
import org.junit.Test;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -25,7 +25,8 @@ public class LDAPSecurityRealmTest {
public void export_ldap_no_secret() throws Exception {
ConfiguratorRegistry registry = ConfiguratorRegistry.get();
ConfigurationContext context = new ConfigurationContext(registry);
CNode yourAttribute = getJenkinsRoot(context).get("securityRealm").asMapping().get("ldap");
CNode yourAttribute =
getJenkinsRoot(context).get("securityRealm").asMapping().get("ldap");
String exported = toYamlString(yourAttribute);

View File

@ -1,5 +1,8 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import hudson.security.LDAPSecurityRealm;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -12,17 +15,13 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author v1v (Victor Martinez)
*/
public class LDAPTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("LDAP_PASSWORD", "SECRET"))
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables().set("LDAP_PASSWORD", "SECRET"))
.around(new JenkinsConfiguredWithReadmeRule());
@Test
@ -33,13 +32,15 @@ public class LDAPTest {
assertEquals(1, securityRealm.getConfigurations().size());
assertTrue(securityRealm.getUserIdStrategy() instanceof IdStrategy.CaseInsensitive);
assertTrue(securityRealm.getGroupIdStrategy() instanceof IdStrategy.CaseSensitive);
final LDAPConfiguration configuration = securityRealm.getConfigurations().get(0);
final LDAPConfiguration configuration =
securityRealm.getConfigurations().get(0);
assertEquals("ldap.acme.com", configuration.getServer());
assertEquals("SECRET", configuration.getManagerPassword());
assertEquals("manager", configuration.getManagerDN());
assertEquals("(&(objectCategory=User)(sAMAccountName={0}))", configuration.getUserSearch());
assertEquals("(&(cn={0})(objectclass=group))", configuration.getGroupSearchFilter());
final FromGroupSearchLDAPGroupMembershipStrategy strategy = ((FromGroupSearchLDAPGroupMembershipStrategy) configuration.getGroupMembershipStrategy());
final FromGroupSearchLDAPGroupMembershipStrategy strategy =
((FromGroupSearchLDAPGroupMembershipStrategy) configuration.getGroupMembershipStrategy());
assertEquals("(&(objectClass=group)(|(cn=GROUP_1)(cn=GROUP_2)))", strategy.getFilter());
}
}

View File

@ -1,5 +1,11 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import hudson.logging.LogRecorder;
import hudson.logging.LogRecorder.Target;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
@ -10,12 +16,6 @@ import java.util.logging.Level;
import org.junit.ClassRule;
import org.junit.Test;
import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class LogRecorderTest {
@ClassRule

View File

@ -1,5 +1,8 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import hudson.ExtensionList;
import hudson.plugins.msbuild.MsBuildInstallation;
import hudson.plugins.msbuild.MsBuildInstallation.DescriptorImpl;
@ -8,9 +11,6 @@ import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class MSBuildTest {
@Rule
public JenkinsConfiguredWithReadmeRule j = new JenkinsConfiguredWithReadmeRule();

View File

@ -1,5 +1,9 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.ExtensionList;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -8,10 +12,6 @@ import org.jenkinsci.plugins.MsTestInstallation.DescriptorImpl;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class MSTestRunnerTest {
@Rule
public JenkinsConfiguredWithReadmeRule j = new JenkinsConfiguredWithReadmeRule();
@ -23,9 +23,12 @@ public class MSTestRunnerTest {
assertNotNull(msTestRunnerDescriptor);
assertEquals(1, msTestRunnerDescriptor.getInstallations().length);
final MsTestInstallation msTestRunnerInstallation = msTestRunnerDescriptor.getInstallations()[0];
final MsTestInstallation msTestRunnerInstallation =
msTestRunnerDescriptor.getInstallations()[0];
assertEquals("MSTest test", msTestRunnerInstallation.getName());
assertEquals("C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\MSTest.exe", msTestRunnerInstallation.getHome());
assertEquals(
"C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\MSTest.exe",
msTestRunnerInstallation.getHome());
assertEquals("/category:SmokeTests", msTestRunnerInstallation.getDefaultArgs());
assertTrue(msTestRunnerInstallation.getOmitNoIsolation());
}

View File

@ -1,5 +1,13 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.assertLogContains;
import static io.jenkins.plugins.casc.misc.Util.assertNotInLog;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import hudson.plugins.emailext.ExtendedEmailPublisher;
import hudson.plugins.emailext.ExtendedEmailPublisherDescriptor;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
@ -14,23 +22,15 @@ import org.junit.rules.RuleChain;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.LoggerRule;
import static io.jenkins.plugins.casc.misc.Util.assertLogContains;
import static io.jenkins.plugins.casc.misc.Util.assertNotInLog;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
public class MailExtTest {
public JenkinsConfiguredWithCodeRule j = new JenkinsConfiguredWithCodeRule();
public LoggerRule logging = new LoggerRule();
@Rule
public RuleChain chain= RuleChain
.outerRule(logging.record(Logger.getLogger(Attribute.class.getName()), Level.FINER).capture(2048))
public RuleChain chain = RuleChain.outerRule(
logging.record(Logger.getLogger(Attribute.class.getName()), Level.FINER)
.capture(2048))
.around(j);
private static final String SMTP_PASSWORD = "myPassword";
@ -39,21 +39,26 @@ public class MailExtTest {
@ConfiguredWithCode("MailExtTest.yml")
@Issue("SECURITY-1404")
public void shouldNotExportOrLogCredentials() throws Exception {
assertEquals(SMTP_PASSWORD, ExtendedEmailPublisher.descriptor().getSmtpPassword().getPlainText());
assertEquals(
SMTP_PASSWORD,
ExtendedEmailPublisher.descriptor().getSmtpPassword().getPlainText());
assertLogContains(logging, "smtpPassword =");
assertNotInLog(logging, SMTP_PASSWORD);
// Verify that the password does not get exported
String exportedConfig = j.exportToString(false);
assertThat("SMTP credentials were migrated", exportedConfig, containsString("credentialsId"));
assertThat("There should be no SMTP password in the exported YAML", exportedConfig, not(containsString(SMTP_PASSWORD)));
assertThat(
"There should be no SMTP password in the exported YAML",
exportedConfig,
not(containsString(SMTP_PASSWORD)));
}
@Test
@Issue("SECURITY-1446")
public void shouldProperlyRoundTripTokenMacro() throws Exception {
final String defaultBody = "${PROJECT_NAME} - Build # ${BUILD_NUMBER} - ${BUILD_STATUS}:\n" +
"Check console output at $BUILD_URL to view the results.";
final String defaultBody = "${PROJECT_NAME} - Build # ${BUILD_NUMBER} - ${BUILD_STATUS}:\n"
+ "Check console output at $BUILD_URL to view the results.";
// This string contains extra escaping
final String defaultSubject = "^^^${PROJECT_NAME} - Build # ^^${BUILD_NUMBER} - ^${BUILD_STATUS}!";

View File

@ -1,5 +1,7 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import hudson.tasks.Mailer;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -7,8 +9,6 @@ import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -24,6 +24,6 @@ public class MailerTest {
final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
assertEquals("4441", descriptor.getSmtpPort());
assertEquals("do-not-reply@acme.org", descriptor.getReplyToAddress());
assertEquals("smtp.acme.org", descriptor.getSmtpHost() );
assertEquals("smtp.acme.org", descriptor.getSmtpHost());
}
}

View File

@ -1,5 +1,13 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertEquals;
import hudson.ExtensionList;
import hudson.tasks.Maven;
import hudson.tasks.Maven.MavenInstaller;
@ -16,14 +24,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertEquals;
@Issue("JENKINS-62446")
public class MavenConfiguratorTest {
@ -89,7 +89,8 @@ public class MavenConfiguratorTest {
final GlobalMavenConfig descriptor = ExtensionList.lookupSingleton(GlobalMavenConfig.class);
assertThat(descriptor.getGlobalSettingsProvider(), instanceOf(FilePathGlobalSettingsProvider.class));
FilePathGlobalSettingsProvider globalProvider = (FilePathGlobalSettingsProvider) descriptor.getGlobalSettingsProvider();
FilePathGlobalSettingsProvider globalProvider =
(FilePathGlobalSettingsProvider) descriptor.getGlobalSettingsProvider();
assertThat(globalProvider.getPath(), is("/conf/maven/global-settings.xml"));
assertThat(descriptor.getSettingsProvider(), instanceOf(FilePathSettingsProvider.class));

View File

@ -27,9 +27,8 @@ public class MercurialTest {
MercurialInstallation mercurial = ((MercurialInstallation.DescriptorImpl) descriptor).getInstallations()[0];
Assert.assertEquals("Mercurial 3", mercurial.getName());
Assert.assertEquals("/mercurial", mercurial.getHome());
Assert.assertEquals("[defaults]\n" +
"clone = --uncompressed\n" +
"bundle = --type none", mercurial.getConfig());
Assert.assertEquals(
"[defaults]\n" + "clone = --uncompressed\n" + "bundle = --type none", mercurial.getConfig());
Assert.assertEquals("INSTALLATION/bin/hg", mercurial.getExecutable());
Assert.assertTrue(mercurial.isUseCaches());
Assert.assertFalse(mercurial.getDebug());
@ -43,6 +42,8 @@ public class MercurialTest {
CommandInstaller installer = installSourceProperty.installers.get(CommandInstaller.class);
Assert.assertEquals("mercurial", installer.getToolHome());
Assert.assertEquals("SomeLabel", installer.getLabel());
Assert.assertEquals("[ -d mercurial ] || wget -q -O - http://www.archlinux.org/packages/extra/x86_64/mercurial/download/ | xzcat | tar xvf -", installer.getCommand());
Assert.assertEquals(
"[ -d mercurial ] || wget -q -O - http://www.archlinux.org/packages/extra/x86_64/mercurial/download/ | xzcat | tar xvf -",
installer.getCommand());
}
}

View File

@ -1,5 +1,13 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.model.Node.Mode;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -10,14 +18,6 @@ import org.jenkinsci.plugins.mesos.MesosSlaveInfo;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author v1v (Victor Martinez)
*/

View File

@ -1,5 +1,7 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import hudson.ExtensionList;
import hudson.tools.InstallSourceProperty;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
@ -9,8 +11,6 @@ import jenkins.plugins.nodejs.tools.NodeJSInstaller;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class NodeJSTest {
@Rule
@ -19,11 +19,13 @@ public class NodeJSTest {
@Test
@ConfiguredWithReadme("nodejs/README.md")
public void configure_nodejs() {
final NodeJSInstallation.DescriptorImpl descriptor = ExtensionList.lookupSingleton(NodeJSInstallation.DescriptorImpl.class);
final NodeJSInstallation.DescriptorImpl descriptor =
ExtensionList.lookupSingleton(NodeJSInstallation.DescriptorImpl.class);
assertEquals(1, descriptor.getInstallations().length);
final NodeJSInstallation nodejs = descriptor.getInstallations()[0];
final InstallSourceProperty installSourceProperty = nodejs.getProperties().get(InstallSourceProperty.class);
final InstallSourceProperty installSourceProperty =
nodejs.getProperties().get(InstallSourceProperty.class);
final NodeJSInstaller nodeJSInstaller = installSourceProperty.installers.get(NodeJSInstaller.class);
assertEquals("12.11.1", nodeJSInstaller.id);
assertEquals(48, nodeJSInstaller.getNpmPackagesRefreshHours().longValue());

View File

@ -21,54 +21,59 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import hudson.model.User;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
* Provides asserts for {@link hudson.security.Permission} checks.
* @author Oleg Nenashev
*/
public class PermissionAssert {
public static void assertHasPermission(User user, final Permission permission, final AccessControlled ... items) {
public static void assertHasPermission(User user, final Permission permission, final AccessControlled... items) {
for (AccessControlled item : items) {
assertPermission(user, item, permission);
}
}
public static void assertHasPermission(User user, final AccessControlled item, final Permission ... permissions) {
public static void assertHasPermission(User user, final AccessControlled item, final Permission... permissions) {
for (Permission permission : permissions) {
assertPermission(user, item, permission);
}
}
public static void assertHasNoPermission(User user, final Permission permission, final AccessControlled ... items) {
public static void assertHasNoPermission(User user, final Permission permission, final AccessControlled... items) {
for (AccessControlled item : items) {
assertNoPermission(user, item, permission);
}
}
public static void assertHasNoPermission(User user, final AccessControlled item, final Permission ... permissions) {
public static void assertHasNoPermission(User user, final AccessControlled item, final Permission... permissions) {
for (Permission permission : permissions) {
assertNoPermission(user, item, permission);
}
}
private static void assertPermission(User user, final AccessControlled item, final Permission p) {
assertThat("User '" + user + "' has no " + p.getId() + " permission for " + item + ", but it should according to security settings",
hasPermission(user, item, p), equalTo(true));
assertThat(
"User '" + user + "' has no " + p.getId() + " permission for " + item
+ ", but it should according to security settings",
hasPermission(user, item, p),
equalTo(true));
}
private static void assertNoPermission(User user, final AccessControlled item, final Permission p) {
assertThat("User '" + user + "' has the " + p.getId() + " permission for " + item + ", but it should not according to security settings",
hasPermission(user, item, p), equalTo(false));
assertThat(
"User '" + user + "' has the " + p.getId() + " permission for " + item
+ ", but it should not according to security settings",
hasPermission(user, item, p),
equalTo(false));
}
private static boolean hasPermission(User user, final AccessControlled item, final Permission p) {

View File

@ -1,5 +1,7 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import hudson.security.ProjectMatrixAuthorizationStrategy;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
@ -9,8 +11,6 @@ import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by mads on 2/22/18.
*/
@ -22,13 +22,19 @@ public class ProjectMatrixAuthorizationTest {
@Test
@ConfiguredWithCode("ProjectMatrixStrategy.yml")
public void checkCorrectlyConfiguredPermissions() {
assertEquals("The configured instance must use the Global Matrix Authentication Strategy", ProjectMatrixAuthorizationStrategy.class, Jenkins.get().getAuthorizationStrategy().getClass());
ProjectMatrixAuthorizationStrategy gms = (ProjectMatrixAuthorizationStrategy) Jenkins.get().getAuthorizationStrategy();
assertEquals(
"The configured instance must use the Global Matrix Authentication Strategy",
ProjectMatrixAuthorizationStrategy.class,
Jenkins.get().getAuthorizationStrategy().getClass());
ProjectMatrixAuthorizationStrategy gms =
(ProjectMatrixAuthorizationStrategy) Jenkins.get().getAuthorizationStrategy();
List<String> adminPermission = new ArrayList<>(gms.getGrantedPermissions().get(Jenkins.ADMINISTER));
List<String> adminPermission =
new ArrayList<>(gms.getGrantedPermissions().get(Jenkins.ADMINISTER));
assertEquals("authenticated", adminPermission.get(0));
List<String> readPermission = new ArrayList<>(gms.getGrantedPermissions().get(Jenkins.READ));
List<String> readPermission =
new ArrayList<>(gms.getGrantedPermissions().get(Jenkins.READ));
assertEquals("anonymous", readPermission.get(0));
}
}

View File

@ -1,5 +1,7 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
@ -17,23 +19,22 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.junit.Assert.assertEquals;
public class PropertiesSecretSourceTest {
private static final String USERNAME_SECRET = "ken";
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("SECRETS_FILE", getClass().getResource("secrets.properties").getFile()))
.around(new JenkinsConfiguredWithCodeRule());
.set(
"SECRETS_FILE",
getClass().getResource("secrets.properties").getFile()))
.around(new JenkinsConfiguredWithCodeRule());
@Test
@ConfiguredWithCode("PropertiesSecretSourceTest.yaml")
public void testReadingSecretsFromProperties() {
List<UsernamePasswordCredentials> credentialList = CredentialsProvider
.lookupCredentials(UsernamePasswordCredentials.class,
Jenkins.getInstanceOrNull(), null, Collections.emptyList());
List<UsernamePasswordCredentials> credentialList = CredentialsProvider.lookupCredentials(
UsernamePasswordCredentials.class, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertEquals(1, credentialList.size());
UsernamePasswordCredentials credentials = credentialList.get(0);
@ -46,7 +47,7 @@ public class PropertiesSecretSourceTest {
@Test
@ConfiguredWithCode("PropertiesSecretSourceTest.yaml")
public void testSecretsFromPropertiesAreUpdatedAfterReload() throws Exception {
File secretsFile = new File(getClass().getResource("secrets.properties").getFile());
File secretsFile = new File(getClass().getResource("secrets.properties").getFile());
Properties secrets = new Properties();
InputStream inputStream = Files.newInputStream(secretsFile.toPath());
secrets.load(inputStream);
@ -59,11 +60,13 @@ public class PropertiesSecretSourceTest {
try {
secrets.store(fileWriter, "store to properties file");
ConfigurationAsCode.get().configure(this.getClass().getResource("PropertiesSecretSourceTest.yaml").toString());
ConfigurationAsCode.get()
.configure(this.getClass()
.getResource("PropertiesSecretSourceTest.yaml")
.toString());
List<UsernamePasswordCredentials> credentialList = CredentialsProvider
.lookupCredentials(UsernamePasswordCredentials.class,
Jenkins.getInstanceOrNull(), null, Collections.emptyList());
List<UsernamePasswordCredentials> credentialList = CredentialsProvider.lookupCredentials(
UsernamePasswordCredentials.class, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertEquals(1, credentialList.size());
UsernamePasswordCredentials credentials = credentialList.get(0);

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.jvnet.hudson.test.JenkinsMatchers.hasPlainText;
import hudson.ProxyConfiguration;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -7,11 +12,6 @@ import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.jvnet.hudson.test.JenkinsMatchers.hasPlainText;
/**
* @author v1v (Victor Martinez)
*/

View File

@ -1,5 +1,15 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.PermissionAssert.assertHasNoPermission;
import static io.jenkins.plugins.casc.PermissionAssert.assertHasPermission;
import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import com.cloudbees.hudson.plugins.folder.Folder;
import com.michelin.cio.hudson.plugins.rolestrategy.Role;
import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy;
@ -19,17 +29,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static io.jenkins.plugins.casc.PermissionAssert.assertHasNoPermission;
import static io.jenkins.plugins.casc.PermissionAssert.assertHasPermission;
import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* @author Oleg Nenashev
* @since 1.0
@ -55,8 +54,10 @@ public class RoleStrategyTest {
folderB.createProject(FreeStyleProject.class, "2");
AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy();
assertThat("Authorization Strategy has been read incorrectly",
s, instanceOf(RoleBasedAuthorizationStrategy.class));
assertThat(
"Authorization Strategy has been read incorrectly",
s,
instanceOf(RoleBasedAuthorizationStrategy.class));
RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s;
Map<Role, Set<String>> globalRoles = rbas.getGrantedRoles(RoleType.Global);
@ -105,14 +106,15 @@ public class RoleStrategyTest {
assertThat(exported, is(expected));
}
@Test
@Issue("Issue #214")
@ConfiguredWithCode("RoleStrategy2.yml")
public void shouldHandleNullItemsAndAgentsCorrectly() {
AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy();
assertThat("Authorization Strategy has been read incorrectly",
s, instanceOf(RoleBasedAuthorizationStrategy.class));
assertThat(
"Authorization Strategy has been read incorrectly",
s,
instanceOf(RoleBasedAuthorizationStrategy.class));
RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s;
Map<Role, Set<String>> globalRoles = rbas.getGrantedRoles(RoleType.Global);

View File

@ -1,12 +1,12 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import hudson.tasks.Mailer;
import io.jenkins.plugins.casc.misc.RoundTripAbstractTest;
import jenkins.model.Jenkins;
import org.jvnet.hudson.test.RestartableJenkinsRule;
import static org.junit.Assert.assertEquals;
public class RoundTripMailerTest extends RoundTripAbstractTest {
@Override
protected void assertConfiguredAsExpected(RestartableJenkinsRule j, String configContent) {

View File

@ -1,38 +0,0 @@
package io.jenkins.plugins.casc;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.output.WriterOutputStream;
import org.jenkinsci.plugins.sge.BatchCloud;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
public class SGECloudTest {
@Rule
public JenkinsConfiguredWithCodeRule j = new JenkinsConfiguredWithCodeRule();
@Test
@Issue("SECURITY-1458")
public void shouldNotExportPassword() throws Exception {
ConfigurationAsCode casc = ConfigurationAsCode.get();
final String passwordText = "Hello, world!";
BatchCloud cloud = new BatchCloud("testBatchCloud", "whatever",
"sge", 5, "sge.acmecorp.com", 8080,
"username", passwordText);
j.jenkins.clouds.add(cloud);
StringWriter writer = new StringWriter();
casc.export(new WriterOutputStream(writer, StandardCharsets.UTF_8));
String exported = writer.toString();
assertThat("Password should not have been exported",
exported, not(containsString(passwordText)));
}
}

View File

@ -1,5 +1,12 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.assertNotInLog;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsProvider;
@ -18,14 +25,6 @@ import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.LoggerRule;
import org.jvnet.hudson.test.TestExtension;
import static io.jenkins.plugins.casc.misc.Util.assertNotInLog;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
/**
* Integration tests for the SSH Credentials Plugin.
*/
@ -35,8 +34,8 @@ public class SSHCredentialsTest {
public LoggerRule logging = new LoggerRule();
@Rule
public RuleChain chain= RuleChain
.outerRule(logging.record("io.jenkins.plugins.casc.Attribute", Level.INFO).capture(2048))
public RuleChain chain = RuleChain.outerRule(logging.record("io.jenkins.plugins.casc.Attribute", Level.INFO)
.capture(2048))
.around(j);
private static final String CREDENTIALS_PASSWORD = "password-of-userid";
@ -57,8 +56,14 @@ public class SSHCredentialsTest {
// Verify that the password does not get exported
String exportedConfig = j.exportToString(false);
assertThat("There should be no password in the exported YAML", exportedConfig, not(containsString(CREDENTIALS_PASSWORD)));
assertThat("There should be no private key in the exported YAML", exportedConfig, not(containsString(PRIVATE_KEY)));
assertThat(
"There should be no password in the exported YAML",
exportedConfig,
not(containsString(CREDENTIALS_PASSWORD)));
assertThat(
"There should be no private key in the exported YAML",
exportedConfig,
not(containsString(PRIVATE_KEY)));
}
@Test
@ -66,8 +71,10 @@ public class SSHCredentialsTest {
@Issue("https://github.com/jenkinsci/configuration-as-code-plugin/issues/1189")
public void shouldSupportMultilineCertificates() {
BasicSSHUserPrivateKey certKey = getCredentials(BasicSSHUserPrivateKey.class);
assertThat("Private key roundtrip failed",
certKey.getPrivateKey().trim(), equalTo(MySSHKeySecretSource.PRIVATE_SSH_KEY.trim()));
assertThat(
"Private key roundtrip failed",
certKey.getPrivateKey().trim(),
equalTo(MySSHKeySecretSource.PRIVATE_SSH_KEY.trim()));
}
@Test
@ -75,14 +82,15 @@ public class SSHCredentialsTest {
@Issue("https://github.com/jenkinsci/configuration-as-code-plugin/issues/1189")
public void shouldSupportSinglelineBase64Certificates() {
BasicSSHUserPrivateKey certKey = getCredentials(BasicSSHUserPrivateKey.class);
assertThat("Private key roundtrip failed",
certKey.getPrivateKey().trim().replace("\r\n", "\n"), equalTo(MySSHKeySecretSource.PRIVATE_SSH_KEY));
assertThat(
"Private key roundtrip failed",
certKey.getPrivateKey().trim().replace("\r\n", "\n"),
equalTo(MySSHKeySecretSource.PRIVATE_SSH_KEY));
}
private <T extends Credentials> T getCredentials(Class<T> clazz) {
List<T> creds = CredentialsProvider.lookupCredentials(
clazz, Jenkins.getInstanceOrNull(),
null, Collections.emptyList());
clazz, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertEquals("There should be only one credential", 1, creds.size());
return creds.get(0);
}
@ -90,17 +98,17 @@ public class SSHCredentialsTest {
@TestExtension
public static class MySSHKeySecretSource extends SecretSource {
private static final String PRIVATE_SSH_KEY =
"-----BEGIN OPENSSH PRIVATE KEY-----\n" +
"b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n" +
"QyNTUxOQAAACCYdvz4LdHg0G5KFS8PlauuOwVBms6Y70FaL4JY1YVahgAAAKCjJ1l+oydZ\n" +
"fgAAAAtzc2gtZWQyNTUxOQAAACCYdvz4LdHg0G5KFS8PlauuOwVBms6Y70FaL4JY1YVahg\n" +
"AAAEBWrtFZGX1yOg1/esgm34TPE5Zw8EXQ1OuxcgYGIaRRVph2/Pgt0eDQbkoVLw+Vq647\n" +
"BUGazpjvQVovgljVhVqGAAAAGW9uZW5hc2hldkBMQVBUT1AtMjVLNjVMT1MBAgME\n" +
"-----END OPENSSH PRIVATE KEY-----";
private static final String PRIVATE_SSH_KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\n"
+ "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\n"
+ "QyNTUxOQAAACCYdvz4LdHg0G5KFS8PlauuOwVBms6Y70FaL4JY1YVahgAAAKCjJ1l+oydZ\n"
+ "fgAAAAtzc2gtZWQyNTUxOQAAACCYdvz4LdHg0G5KFS8PlauuOwVBms6Y70FaL4JY1YVahg\n"
+ "AAAEBWrtFZGX1yOg1/esgm34TPE5Zw8EXQ1OuxcgYGIaRRVph2/Pgt0eDQbkoVLw+Vq647\n"
+ "BUGazpjvQVovgljVhVqGAAAAGW9uZW5hc2hldkBMQVBUT1AtMjVLNjVMT1MBAgME\n"
+ "-----END OPENSSH PRIVATE KEY-----";
// encoded with "base64 -w 0"
private static final String PRIVATE_SSH_KEY_BASE64 = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0NCmIzQmxibk56YUMxclpYa3RkakVBQUFBQUJHNXZibVVBQUFBRWJtOXVaUUFBQUFBQUFBQUJBQUFBTXdBQUFBdHpjMmd0WlcNClF5TlRVeE9RQUFBQ0NZZHZ6NExkSGcwRzVLRlM4UGxhdXVPd1ZCbXM2WTcwRmFMNEpZMVlWYWhnQUFBS0NqSjFsK295ZFoNCmZnQUFBQXR6YzJndFpXUXlOVFV4T1FBQUFDQ1lkdno0TGRIZzBHNUtGUzhQbGF1dU93VkJtczZZNzBGYUw0SlkxWVZhaGcNCkFBQUVCV3J0RlpHWDF5T2cxL2VzZ20zNFRQRTVadzhFWFExT3V4Y2dZR0lhUlJWcGgyL1BndDBlRFFia29WTHcrVnE2NDcNCkJVR2F6cGp2UVZvdmdsalZoVnFHQUFBQUdXOXVaVzVoYzJobGRrQk1RVkJVVDFBdE1qVkxOalZNVDFNQkFnTUUNCi0tLS0tRU5EIE9QRU5TU0ggUFJJVkFURSBLRVktLS0tLQ0K";
private static final String PRIVATE_SSH_KEY_BASE64 =
"LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0NCmIzQmxibk56YUMxclpYa3RkakVBQUFBQUJHNXZibVVBQUFBRWJtOXVaUUFBQUFBQUFBQUJBQUFBTXdBQUFBdHpjMmd0WlcNClF5TlRVeE9RQUFBQ0NZZHZ6NExkSGcwRzVLRlM4UGxhdXVPd1ZCbXM2WTcwRmFMNEpZMVlWYWhnQUFBS0NqSjFsK295ZFoNCmZnQUFBQXR6YzJndFpXUXlOVFV4T1FBQUFDQ1lkdno0TGRIZzBHNUtGUzhQbGF1dU93VkJtczZZNzBGYUw0SlkxWVZhaGcNCkFBQUVCV3J0RlpHWDF5T2cxL2VzZ20zNFRQRTVadzhFWFExT3V4Y2dZR0lhUlJWcGgyL1BndDBlRFFia29WTHcrVnE2NDcNCkJVR2F6cGp2UVZvdmdsalZoVnFHQUFBQUdXOXVaVzVoYzJobGRrQk1RVkJVVDFBdE1qVkxOalZNVDFNQkFnTUUNCi0tLS0tRU5EIE9QRU5TU0ggUFJJVkFURSBLRVktLS0tLQ0K";
@Override
public Optional<String> reveal(String secret) {

View File

@ -1,5 +1,12 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import hudson.ExtensionList;
import hudson.tools.InstallSourceProperty;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
@ -11,14 +18,6 @@ import org.jvnet.hudson.plugins.SbtPluginBuilder;
import org.jvnet.hudson.plugins.SbtPluginBuilder.SbtInstallation;
import org.jvnet.hudson.plugins.SbtPluginBuilder.SbtInstaller;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
/**
* @author v1v (Victor Martinez)
*/
@ -30,7 +29,8 @@ public class SbtTest {
@Test
public void configure_sbt_tool() {
final SbtPluginBuilder.DescriptorImpl descriptor = ExtensionList.lookupSingleton(SbtPluginBuilder.DescriptorImpl.class);
final SbtPluginBuilder.DescriptorImpl descriptor =
ExtensionList.lookupSingleton(SbtPluginBuilder.DescriptorImpl.class);
assertEquals(1, descriptor.getInstallations().length);
SbtInstallation sbt = descriptor.getInstallations()[0];

View File

@ -1,5 +1,11 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertTrue;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
@ -20,12 +26,6 @@ import org.jvnet.hudson.test.Issue;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.nodes.Node;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertTrue;
public class Security1446Test {
@Rule
@ -38,17 +38,25 @@ public class Security1446Test {
@Test
@Issue("SECURITY-1446")
public void testImportWithEnvVar() {
List<StandardUsernamePasswordCredentials> userPasswCred = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList());
List<StandardUsernamePasswordCredentials> userPasswCred = CredentialsProvider.lookupCredentials(
StandardUsernamePasswordCredentials.class, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertThat(userPasswCred.size(), is(1));
for (StandardUsernamePasswordCredentials cred : userPasswCred) {
assertTrue("The JAVA_HOME environment variable should not be resolved", cred.getUsername().matches(JAVA_HOME_PATTERN));
assertTrue("The PATH environment variable should not be resolved", cred.getDescription().matches(PATH_PATTERN));
assertTrue(
"The JAVA_HOME environment variable should not be resolved",
cred.getUsername().matches(JAVA_HOME_PATTERN));
assertTrue(
"The PATH environment variable should not be resolved",
cred.getDescription().matches(PATH_PATTERN));
}
List<StringCredentials> stringCred = CredentialsProvider.lookupCredentials(StringCredentials.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList());
List<StringCredentials> stringCred = CredentialsProvider.lookupCredentials(
StringCredentials.class, Jenkins.getInstanceOrNull(), null, Collections.emptyList());
assertThat(stringCred.size(), is(1));
for (StringCredentials cred : stringCred) {
assertTrue("The PATH environment variable should not be resolved", cred.getDescription().matches(PATH_PATTERN));
assertTrue(
"The PATH environment variable should not be resolved",
cred.getDescription().matches(PATH_PATTERN));
}
}
@ -59,9 +67,10 @@ public class Security1446Test {
ConfiguratorRegistry registry = ConfiguratorRegistry.get();
ConfigurationContext context = new ConfigurationContext(registry);
DataBoundConfigurator<UsernamePasswordCredentialsImpl> configurator = new DataBoundConfigurator<>(UsernamePasswordCredentialsImpl.class);
UsernamePasswordCredentialsImpl creds = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test",
message, "foo", "bar");
DataBoundConfigurator<UsernamePasswordCredentialsImpl> configurator =
new DataBoundConfigurator<>(UsernamePasswordCredentialsImpl.class);
UsernamePasswordCredentialsImpl creds =
new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test", message, "foo", "bar");
final CNode config = configurator.describe(creds, context);
final Node valueNode = ConfigurationAsCode.get().toYaml(config);
final String exported;
@ -76,5 +85,4 @@ public class Security1446Test {
assertThat("Improper masking for PATH", exported, containsString("^${PATH}"));
assertThat("Improper masking for JAVA_HOME", exported, containsString("^^${JAVA_HOME}"));
}
}

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
@ -15,11 +20,6 @@ import org.junit.Test;
import org.junit.rules.RuleChain;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -29,8 +29,8 @@ public class SeedJobTest {
@Rule
public RuleChain rc = RuleChain.outerRule(new EnvVarsRule()
.set("SEED_JOB_PATH", "./src/test/resources/io/jenkins/plugins/casc/testJob2.groovy")
.set("REPO_URL", "git://github.com/jenkinsci/configuration-as-code-plugin.git"))
.set("SEED_JOB_PATH", "./src/test/resources/io/jenkins/plugins/casc/testJob2.groovy")
.set("REPO_URL", "git://github.com/jenkinsci/configuration-as-code-plugin.git"))
.around(j = new JenkinsConfiguredWithCodeRule());
@Test
@ -57,14 +57,12 @@ public class SeedJobTest {
@Test
@ConfiguredWithCode("SeedJobTest_withSecurityConfig.yml")
@Envs(
@Env(name = "SEED_JOB_FOLDER_FILE_PATH", value = ".")
)
@Envs(@Env(name = "SEED_JOB_FOLDER_FILE_PATH", value = "."))
public void configure_seed_job_with_security_config() throws Exception {
final Jenkins jenkins = Jenkins.get();
final GlobalJobDslSecurityConfiguration dslSecurity = GlobalConfiguration.all()
.get(GlobalJobDslSecurityConfiguration.class);
final GlobalJobDslSecurityConfiguration dslSecurity =
GlobalConfiguration.all().get(GlobalJobDslSecurityConfiguration.class);
assertNotNull(dslSecurity);
assertThat("ScriptSecurity", dslSecurity.isUseScriptSecurity(), is(false));

View File

@ -1,5 +1,7 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertNotNull;
import hudson.ExtensionList;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -7,8 +9,6 @@ import org.codefirst.SimpleThemeDecorator;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
* @author v1v (Victor Martinez)
*/

View File

@ -1,5 +1,11 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.convertYamlFileToJson;
import static io.jenkins.plugins.casc.misc.Util.validateSchema;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertNotNull;
import hudson.ExtensionList;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
@ -9,22 +15,14 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static io.jenkins.plugins.casc.misc.Util.convertYamlFileToJson;
import static io.jenkins.plugins.casc.misc.Util.validateSchema;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertNotNull;
/**
* @author v1v (Victor Martinez)
*/
public class SlackTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("SLACK_TOKEN", "ADMIN123"))
.around(new JenkinsConfiguredWithReadmeRule());
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables().set("SLACK_TOKEN", "ADMIN123"))
.around(new JenkinsConfiguredWithReadmeRule());
@Test
@ConfiguredWithReadme("slack/README.md")
@ -37,8 +35,6 @@ public class SlackTest {
@Test
public void validJsonSchema() throws Exception {
assertThat(
validateSchema(convertYamlFileToJson(this, "slackSchema.yml")),
empty());
assertThat(validateSchema(convertYamlFileToJson(this, "slackSchema.yml")), empty());
}
}

View File

@ -1,5 +1,12 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.convertYamlFileToJson;
import static io.jenkins.plugins.casc.misc.Util.validateSchema;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import hudson.plugins.sonar.SonarGlobalConfiguration;
import hudson.plugins.sonar.SonarInstallation;
import hudson.plugins.sonar.model.TriggersConfig;
@ -10,13 +17,6 @@ import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import static io.jenkins.plugins.casc.misc.Util.convertYamlFileToJson;
import static io.jenkins.plugins.casc.misc.Util.validateSchema;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -45,16 +45,12 @@ public class SonarQubeTest {
@Test
public void validJsonSchema() throws Exception {
assertThat(
validateSchema(convertYamlFileToJson(this, "sonarSchema.yml")),
empty());
assertThat(validateSchema(convertYamlFileToJson(this, "sonarSchema.yml")), empty());
}
@Test
@Ignore
public void validFullJsonSchema() throws Exception {
assertThat(
validateSchema(convertYamlFileToJson(this, "sonarSchemaFull.yml")),
empty());
assertThat(validateSchema(convertYamlFileToJson(this, "sonarSchemaFull.yml")), empty());
}
}

View File

@ -1,17 +1,17 @@
package io.jenkins.plugins.casc;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.jenkins.plugins.statistics.gatherer.StatisticsConfiguration;
import org.junit.Rule;
import org.junit.Test;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import org.jenkins.plugins.statistics.gatherer.StatisticsConfiguration;
import org.junit.Rule;
import org.junit.Test;
public class StatisticsGathererTest {
@Rule

View File

@ -1,5 +1,11 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey.DirectEntryPrivateKeySource;
import com.cloudbees.plugins.credentials.CredentialsProvider;
@ -21,13 +27,6 @@ import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import org.jvnet.hudson.test.LoggerRule;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -35,26 +34,24 @@ public class SystemCredentialsTest {
@Rule
public LoggerRule log = new LoggerRule()
.recordPackage(DataBoundConfigurator.class, Level.INFO)
.capture(100);
.recordPackage(DataBoundConfigurator.class, Level.INFO)
.capture(100);
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("SUDO_PASSWORD", "1234")
.set("SSH_PRIVATE_KEY", "s3cr3t")
.set("SSH_KEY_PASSWORD", "ABCD"))
.set("SUDO_PASSWORD", "1234")
.set("SSH_PRIVATE_KEY", "s3cr3t")
.set("SSH_KEY_PASSWORD", "ABCD"))
.around(log)
.around(new JenkinsConfiguredWithCodeRule());
@Test
@ConfiguredWithCode("SystemCredentialsTest.yml")
public void configure_system_credentials() throws Exception {
Jenkins jenkins = Jenkins.get();
List<UsernamePasswordCredentials> ups = CredentialsProvider.lookupCredentials(
UsernamePasswordCredentials.class, jenkins, ACL.SYSTEM, Collections.emptyList()
);
UsernamePasswordCredentials.class, jenkins, ACL.SYSTEM, Collections.emptyList());
assertThat(ups, hasSize(1));
final UsernamePasswordCredentials up = ups.get(0);
assertThat(up.getPassword().getPlainText(), equalTo("1234"));
@ -64,32 +61,27 @@ public class SystemCredentialsTest {
final CNode node = context.lookup(up.getClass()).describe(up, context);
assertThat(node.asMapping().getScalarValue("password"), not(equals("1234")));
List<CertificateCredentials> certs = CredentialsProvider.lookupCredentials(
CertificateCredentials.class, jenkins, ACL.SYSTEM, Collections.emptyList()
);
CertificateCredentials.class, jenkins, ACL.SYSTEM, Collections.emptyList());
assertThat(certs, hasSize(0));
// TODO: add test for uploaded certificate
// assertThat(certs.get(0).getPassword().getPlainText(), equalTo("ABCD"));
// TODO: add test for uploaded certificate
// assertThat(certs.get(0).getPassword().getPlainText(), equalTo("ABCD"));
List<BasicSSHUserPrivateKey> sshPrivateKeys = CredentialsProvider.lookupCredentials(
BasicSSHUserPrivateKey.class, jenkins, ACL.SYSTEM, Collections.emptyList()
);
BasicSSHUserPrivateKey.class, jenkins, ACL.SYSTEM, Collections.emptyList());
assertThat(sshPrivateKeys, hasSize(1));
final BasicSSHUserPrivateKey ssh_with_passphrase = sshPrivateKeys.get(0);
assertThat(ssh_with_passphrase.getPassphrase().getPlainText(), equalTo("ABCD"));
final DirectEntryPrivateKeySource source = (DirectEntryPrivateKeySource) ssh_with_passphrase.getPrivateKeySource();
final DirectEntryPrivateKeySource source =
(DirectEntryPrivateKeySource) ssh_with_passphrase.getPrivateKeySource();
assertThat(source.getPrivateKey().getPlainText(), equalTo("s3cr3t"));
// credentials should not appear in plain text in log
for (LogRecord logRecord : log.getRecords()) {
assertThat(logRecord.getMessage(), not(containsString("1234")));
assertThat(logRecord.getMessage(), not(containsString("ABCD")));
}
}
}

View File

@ -1,5 +1,12 @@
package io.jenkins.plugins.casc;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import hudson.ExtensionList;
import hudson.tools.InstallSourceProperty;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
@ -10,14 +17,6 @@ import org.jenkinsci.plugins.terraform.TerraformInstaller;
import org.junit.ClassRule;
import org.junit.Test;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
/**
* @author v1v (Victor Martinez)
*/
@ -29,7 +28,8 @@ public class TerraformTest {
@Test
public void configure_terraform_tool() {
final TerraformInstallation.DescriptorImpl descriptor = ExtensionList.lookupSingleton(TerraformInstallation.DescriptorImpl.class);
final TerraformInstallation.DescriptorImpl descriptor =
ExtensionList.lookupSingleton(TerraformInstallation.DescriptorImpl.class);
assertEquals(1, descriptor.getInstallations().length);
TerraformInstallation terraform = descriptor.getInstallations()[0];

View File

@ -1,18 +1,17 @@
package io.jenkins.plugins.casc;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import io.jenkins.plugins.casc.model.CNode;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static io.jenkins.plugins.casc.misc.Util.getToolRoot;
import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile;
import static io.jenkins.plugins.casc.misc.Util.toYamlString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import io.jenkins.plugins.casc.model.CNode;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
public class ToolDefaultPropertiesExportIgnoreListTest {

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey.DirectEntryPrivateKeySource;
import com.cloudbees.plugins.credentials.CredentialsProvider;
@ -16,12 +21,6 @@ import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
/**
* @author v1v (Victor Martinez)
*/
@ -29,16 +28,18 @@ public class TopReadmeTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new EnvironmentVariables()
.set("SUDO_PASSWORD", "1234")
.set("SSH_PRIVATE_KEY", "s3cr3t")
.set("SSH_KEY_PASSWORD", "ABCD"))
.around(new JenkinsConfiguredWithReadmeRule());
.set("SUDO_PASSWORD", "1234")
.set("SSH_PRIVATE_KEY", "s3cr3t")
.set("SSH_KEY_PASSWORD", "ABCD"))
.around(new JenkinsConfiguredWithReadmeRule());
@Test
@ConfiguredWithReadme("README.md#0")
public void configure_demo_first_code_block() {
final Jenkins jenkins = Jenkins.get();
assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
assertEquals(
"Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n",
jenkins.getSystemMessage());
final LDAPSecurityRealm securityRealm = (LDAPSecurityRealm) jenkins.getSecurityRealm();
assertEquals(1, securityRealm.getConfigurations().size());
assertEquals(50000, jenkins.getSlaveAgentPort());
@ -50,14 +51,14 @@ public class TopReadmeTest {
assertEquals(1, gitTool.getInstallations().length);
List<BasicSSHUserPrivateKey> sshPrivateKeys = CredentialsProvider.lookupCredentials(
BasicSSHUserPrivateKey.class, jenkins, ACL.SYSTEM, Collections.emptyList()
);
BasicSSHUserPrivateKey.class, jenkins, ACL.SYSTEM, Collections.emptyList());
assertThat(sshPrivateKeys, hasSize(1));
final BasicSSHUserPrivateKey ssh_with_passphrase = sshPrivateKeys.get(0);
assertThat(ssh_with_passphrase.getPassphrase().getPlainText(), equalTo("ABCD"));
final DirectEntryPrivateKeySource source = (DirectEntryPrivateKeySource) ssh_with_passphrase.getPrivateKeySource();
final DirectEntryPrivateKeySource source =
(DirectEntryPrivateKeySource) ssh_with_passphrase.getPrivateKeySource();
assertThat(source.getPrivateKey().getPlainText(), equalTo("s3cr3t"));
}

View File

@ -1,5 +1,10 @@
package io.jenkins.plugins.casc;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import hudson.model.Descriptor;
import hudson.model.ListView;
import hudson.util.DescribableList;
@ -13,11 +18,6 @@ import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ViewJobFiltersTest {
@Rule

View File

@ -1,5 +1,7 @@
package io.jenkins.plugins.casc;
import static org.junit.Assert.assertEquals;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import jenkins.plugins.git.GitSCMSource;
@ -9,8 +11,6 @@ import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:VictorMartinezRubio@gmail.com">Victor Martinez</a>
*/
@ -23,7 +23,8 @@ public class WorkflowCpsGlobalLibTest {
@ConfiguredWithReadme("pipeline-groovy-lib/README.md")
public void configure_global_library() {
assertEquals(1, GlobalLibraries.get().getLibraries().size());
final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0);
final LibraryConfiguration library =
GlobalLibraries.get().getLibraries().get(0);
assertEquals("awesome-lib", library.getName());
final SCMSourceRetriever retriever = (SCMSourceRetriever) library.getRetriever();
final GitSCMSource scm = (GitSCMSource) retriever.getScm();

View File

@ -1,5 +1,11 @@
package io.jenkins.plugins.casc.core;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.model.TimeZoneProperty;
import hudson.model.User;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
@ -13,12 +19,6 @@ import org.jenkinsci.main.modules.cli.auth.ssh.UserPropertyImpl;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a>
*/
@ -38,7 +38,8 @@ public class HudsonPrivateSecurityRealmConfiguratorTest {
final HudsonPrivateSecurityRealm.Details details = admin.getProperty(HudsonPrivateSecurityRealm.Details.class);
assertTrue(details.isPasswordCorrect("somethingsecret"));
final FullControlOnceLoggedInAuthorizationStrategy authorizationStrategy = (FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
final FullControlOnceLoggedInAuthorizationStrategy authorizationStrategy =
(FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
assertTrue(authorizationStrategy.isAllowAnonymousRead());
}
@ -60,8 +61,7 @@ public class HudsonPrivateSecurityRealmConfiguratorTest {
assertThat(admin.getFullName(), is("Admin"));
assertThat(admin.getDescription(), is("Superwoman"));
SlackUserProperty slackUserProperty = admin
.getProperty(SlackUserProperty.class);
SlackUserProperty slackUserProperty = admin.getProperty(SlackUserProperty.class);
assertThat(slackUserProperty.getUserId(), is("ABCDEFGH"));
UserProperty mailerProperty = admin.getProperty(UserProperty.class);
@ -73,5 +73,4 @@ public class HudsonPrivateSecurityRealmConfiguratorTest {
UserPropertyImpl authorizedKeysProperty = admin.getProperty(UserPropertyImpl.class);
assertThat(authorizedKeysProperty.authorizedKeys, is("ssh-rsa some-key\n"));
}
}

View File

@ -0,0 +1,40 @@
package io.jenkins.plugins.casc.core;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import hudson.model.ComputerSet;
import hudson.node_monitors.ArchitectureMonitor;
import hudson.node_monitors.ClockMonitor;
import hudson.node_monitors.DiskSpaceMonitor;
import io.jenkins.plugins.casc.misc.ConfiguredWithReadme;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule;
import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
public class NodeMonitorsConfiguratorTest {
@Rule
public JenkinsConfiguredWithReadmeRule j = new JenkinsConfiguredWithReadmeRule();
@Test
@ConfiguredWithReadme("node-monitors/README.md")
public void should_configure_node_monitors() {
DiskSpaceMonitor dsm = (DiskSpaceMonitor) ComputerSet.getMonitors().get(DiskSpaceMonitor.DESCRIPTOR);
assertThat(dsm.freeSpaceThreshold, is("3GB"));
ArchitectureMonitor.DescriptorImpl amd =
(ArchitectureMonitor.DescriptorImpl) Jenkins.get().getDescriptorOrDie(ArchitectureMonitor.class);
ArchitectureMonitor am = (ArchitectureMonitor) ComputerSet.getMonitors().get(amd);
assertThat(am.isIgnored(), is(false));
}
@Test
@ConfiguredWithReadme("node-monitors/README.md")
public void not_configured_monitors_are_ignored() {
ClockMonitor.DescriptorImpl cmd =
(ClockMonitor.DescriptorImpl) Jenkins.get().getDescriptorOrDie(ClockMonitor.class);
ClockMonitor cm = (ClockMonitor) ComputerSet.getMonitors().get(cmd);
assertThat(cm.isIgnored(), is(true));
}
}

View File

@ -17,4 +17,4 @@ unclassified:
strategyId: 2
- gitHubForkDiscovery:
strategyId: 3
trust: "trustPermission"
trust: "gitHubTrustPermissions"

View File

@ -7,15 +7,15 @@ jenkins:
description: "Jenkins administrators"
permissions:
- "Overall/Administer"
assignments:
- "admin"
entries:
- user: "admin"
- name: "readonly"
description: "Read-only users"
permissions:
- "Overall/Read"
- "Job/Read"
assignments:
- "authenticated"
entries:
- group: "authenticated"
items:
- name: "FolderA"
description: "Jobs in Folder A, but not the folder itself"
@ -24,25 +24,25 @@ jenkins:
- "Job/Configure"
- "Job/Build"
- "Job/Delete"
assignments:
- "user1"
- "user2"
entries:
- user: "user1"
- user: "user2"
- name: "FolderB"
description: "Jobs in Folder B, but not the folder itself"
pattern: "B.*"
permissions:
- "Job/Configure"
- "Job/Build"
assignments:
- "user2"
entries:
- user: "user2"
agents:
- name: "Agent1"
description: "Agent 1"
pattern: "agent1"
permissions:
- "Agent/Build"
assignments:
- "user1"
entries:
- user: "user1"
# System for test
securityRealm:

View File

@ -1,43 +1,43 @@
roleBased:
roles:
agents:
- assignments:
- "user1"
description: "Agent 1"
- description: "Agent 1"
entries:
- user: "user1"
name: "Agent1"
pattern: "agent1"
permissions:
- "Agent/Build"
global:
- assignments:
- "admin"
description: "Jenkins administrators"
- description: "Jenkins administrators"
entries:
- user: "admin"
name: "admin"
pattern: ".*"
permissions:
- "Overall/Administer"
- assignments:
- "authenticated"
description: "Read-only users"
- description: "Read-only users"
entries:
- group: "authenticated"
name: "readonly"
pattern: ".*"
permissions:
- "Overall/Read"
- "Job/Read"
items:
- assignments:
- "user1"
- "user2"
description: "Jobs in Folder A, but not the folder itself"
- description: "Jobs in Folder A, but not the folder itself"
entries:
- user: "user1"
- user: "user2"
name: "FolderA"
pattern: "A/.*"
permissions:
- "Job/Build"
- "Job/Delete"
- "Job/Configure"
- assignments:
- "user2"
description: "Jobs in Folder B, but not the folder itself"
- description: "Jobs in Folder B, but not the folder itself"
entries:
- user: "user2"
name: "FolderB"
pattern: "B.*"
permissions:

View File

@ -7,15 +7,15 @@ jenkins:
description: "Jenkins administrators"
permissions:
- "Overall/Administer"
assignments:
- "admin"
entries:
- user: "admin"
- name: "readonly"
description: "Read-only users"
permissions:
- "Overall/Read"
- "Job/Read"
assignments:
- "authenticated"
entries:
- group: "authenticated"
# System for test
securityRealm:

View File

@ -26,7 +26,7 @@ x-ec2_anchor: &ec2_anchor
jenkins:
clouds:
- amazonEC2:
cloudName: "ec2"
name: "ec2"
instanceCapStr: 20
# this shouldn't be needed, since without explicit creds this should already be used
# but let's be explicit to avoid issues.

View File

@ -1,2 +0,0 @@
jenkins:
systemMessage: "Test '{key1}', '{key2}', '{key3}'"

View File

@ -1,15 +0,0 @@
path "secret/*" {
capabilities = ["create", "read", "list"]
}
path "kv-v1/*" {
capabilities = ["create", "read", "list"]
}
path "kv-v2/*" {
capabilities = ["create", "read", "list"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}

View File

@ -1 +0,0 @@
CASC_VAULT_URL=http://localhost:8200

Some files were not shown because too many files have changed in this diff Show More