Compare commits

...

112 Commits

Author SHA1 Message Date
Liam Newman
dbf6d3bf37 [maven-release-plugin] prepare release github-api-1.129 2021-05-24 05:08:42 -07:00
Liam Newman
081a454ec8 Merge pull request #1141 from hub4j/bitwiseman-patch-1
Only run coverage on code in this library
2021-05-17 14:47:00 -07:00
Liam Newman
543b643fdb Only run coverage on code in this library 2021-05-17 13:55:18 -07:00
Liam Newman
d02f194668 Update release-drafter.yml 2021-05-13 13:03:08 -07:00
Liam Newman
9c8c00b77c Update release-drafter.yml 2021-05-13 12:55:43 -07:00
Liam Newman
a23de4707b Create release-drafter.yml 2021-05-13 12:54:38 -07:00
Liam Newman
301303bd90 Merge pull request #1139 from akashRindhe/feature/1080
(feat) Add method to check if Organization has projects enabled
2021-05-13 11:26:07 -07:00
Akash Rindhe
4689b8f885 (feat) Add method to set projects enabled flag for Organization
[https://github.com/hub4j/github-api/issues/1080]
2021-05-14 00:36:55 +08:00
Akash Rindhe
c4de682493 (feat) Add method to check if Organization has projects enabled
[https://github.com/hub4j/github-api/issues/1080]
2021-05-14 00:35:22 +08:00
Liam Newman
b23934a5a1 Merge pull request #1134 from bitwiseman/task/atomic
Minimize locking for rate limit
2021-05-11 10:26:00 -07:00
Liam Newman
f2eecc3cc5 Update src/main/java/org/kohsuke/github/GHRateLimit.java 2021-05-06 14:37:11 -07:00
dependabot[bot]
f5310965dc Merge pull request #1114 from hub4j/dependabot/github_actions/actions/setup-java-v2 2021-05-04 21:38:47 +00:00
Tim Jacomb
47ffff3407 Update maven-build.yml 2021-05-04 22:33:24 +01:00
Liam Newman
f2a70a46ad Minimize locking for rate limit
Rather than locking to ensure ordered updates to rate limit, use AtomicReference. This reduces
the need for locking to only when rate limit has expired and we have to call getRateLimit().
2021-05-04 12:29:05 -07:00
dependabot[bot]
acd5c6baa6 Chore(deps): Bump actions/setup-java from v1 to v2
Bumps [actions/setup-java](https://github.com/actions/setup-java) from v1 to v2.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v1...8764a52df183aa0ccea74521dfd9d506ffc7a19a)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-04 19:25:01 +00:00
Liam Newman
06d02059cb Merge pull request #1131 from hub4j/dependabot/maven/org.apache.maven.plugins-maven-project-info-reports-plugin-3.1.2
Chore(deps): Bump maven-project-info-reports-plugin from 3.1.1 to 3.1.2
2021-05-04 12:24:38 -07:00
Liam Newman
603288c361 Merge pull request #1132 from hub4j/dependabot/maven/com.diffplug.spotless-spotless-maven-plugin-2.10.3
Chore(deps): Bump spotless-maven-plugin from 2.10.1 to 2.10.3
2021-05-04 12:24:24 -07:00
dependabot[bot]
09ee3168f9 Chore(deps): Bump spotless-maven-plugin from 2.10.1 to 2.10.3
Bumps [spotless-maven-plugin](https://github.com/diffplug/project) from 2.10.1 to 2.10.3.
- [Release notes](https://github.com/diffplug/project/releases)
- [Commits](https://github.com/diffplug/project/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-01 02:01:02 +00:00
dependabot[bot]
1559d063c7 Chore(deps): Bump maven-project-info-reports-plugin from 3.1.1 to 3.1.2
Bumps [maven-project-info-reports-plugin](https://github.com/apache/maven-project-info-reports-plugin) from 3.1.1 to 3.1.2.
- [Release notes](https://github.com/apache/maven-project-info-reports-plugin/releases)
- [Commits](https://github.com/apache/maven-project-info-reports-plugin/compare/maven-project-info-reports-plugin-3.1.1...maven-project-info-reports-plugin-3.1.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-01 02:00:57 +00:00
Liam Newman
cfdcb182a4 Merge pull request #1124 from alexanderkjall/upgrade-commons-io
upgrade commons-io due to CVE-2021-29425
2021-04-29 08:41:16 -07:00
Liam Newman
d526b13d7d Apply suggestions from code review
Co-authored-by: Guillaume Smet <guillaume.smet@gmail.com>
2021-04-28 13:33:13 -07:00
Liam Newman
fffe31220e Make apache commons restrictions more accurate and legible 2021-04-27 15:19:46 -07:00
Liam Newman
ce17396ea6 Merge branch 'main' into upgrade-commons-io 2021-04-27 02:33:44 -07:00
Liam Newman
d18e81dc74 More informative message 2021-04-26 21:13:09 -07:00
Liam Newman
6ae5acba5d Fix typo 2021-04-26 21:08:59 -07:00
Liam Newman
0a1c803f69 Test for approved Apache commons methods
This is an inaccurate way of verifying that we are calling only methods that are
compatible with older versions of commons, but it should be sufficient to deter
usage without careful consideration.
2021-04-26 20:39:27 -07:00
Liam Newman
fa0865b208 Fix assertThat arch test 2021-04-26 14:27:28 -07:00
Liam Newman
886887913c Merge pull request #1126 from akashRindhe/refactor/1099
(refactor) Replace complex parsing logic from GHEvent.type to GHEvent with static mapping
2021-04-21 23:53:10 -07:00
Liam Newman
5c64fec032 Streamline with EnumUtils 2021-04-21 16:57:37 -07:00
Liam Newman
892f60ea16 [maven-release-plugin] prepare for next development iteration 2021-04-21 11:05:58 -07:00
Liam Newman
f28f966040 [maven-release-plugin] prepare release github-api-1.128 2021-04-21 11:05:43 -07:00
Liam Newman
0e9cc90d31 Merge pull request #1125 from gsmet/remove-jdk-16-workaround
Remove now unnecessary JDK 16 specific workaround
2021-04-21 08:11:51 -07:00
Akash Rindhe
72dc5c5d18 (refactor) Replace complex parsing logic from GHEvent.type to GHEvent with static mapping
[https://github.com/hub4j/github-api/issues/1099]
2021-04-21 20:07:10 +08:00
Guillaume Smet
02e02d39b0 Remove now unnecessary JDK 16 specific workaround
Now that we are not using reflection anymore to push unsupported HTTP
methods, we can remove this workaround.
2021-04-21 13:29:33 +02:00
Alexander Kjäll
e629a23bd4 upgrade commons-io due to CVE-2021-29425, it's a vulnerability in FileNameUtils.normalize that isn't used in this project 2021-04-21 11:37:38 +02:00
Liam Newman
f6e8a2c7c6 Merge pull request #1123 from bitwiseman/task/assertThat
Move to using assertThat() exclusively
2021-04-20 13:59:24 -07:00
Liam Newman
76bea5174f Merge branch 'main' into task/assertThat 2021-04-20 13:43:04 -07:00
Liam Newman
2be27d1a41 Update maven-build.yml 2021-04-20 13:42:48 -07:00
Liam Newman
cd1454ac03 More assertThat matchers 2021-04-20 12:34:01 -07:00
Liam Newman
b550910f4c Streamline assertThat calls using appropriate matchers 2021-04-20 12:16:55 -07:00
Liam Newman
d13e490be2 Enforce use of assertThat
Assert.assert* methods other than assertThat() produce less clear tests.
This change enforces using assertThat() for all verifications.
While more verbose they are generally more consistent and easier to understand.
2021-04-20 00:46:43 -07:00
Liam Newman
3d451526ef Deprecate all asserts other than assertThat 2021-04-19 19:09:47 -07:00
Liam Newman
bd38897d48 Do not inherit from Assert 2021-04-19 15:58:33 -07:00
Liam Newman
63ccbaf064 Merge pull request #1116 from hub4j/dependabot/maven/spotbugs.version-4.2.3
Chore(deps): Bump spotbugs.version from 4.2.2 to 4.2.3
2021-04-19 13:44:18 -07:00
Liam Newman
2beb806b8a Merge pull request #1120 from hub4j/dependabot/maven/com.fasterxml.jackson.core-jackson-databind-2.12.3
Chore(deps): Bump jackson-databind from 2.12.1 to 2.12.3
2021-04-19 13:44:02 -07:00
dependabot[bot]
552ba6693e Chore(deps): Bump spotbugs.version from 4.2.2 to 4.2.3
Bumps `spotbugs.version` from 4.2.2 to 4.2.3.

Updates `spotbugs` from 4.2.2 to 4.2.3
- [Release notes](https://github.com/spotbugs/spotbugs/releases)
- [Changelog](https://github.com/spotbugs/spotbugs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/spotbugs/spotbugs/compare/4.2.2...4.2.3)

Updates `spotbugs-annotations` from 4.2.2 to 4.2.3
- [Release notes](https://github.com/spotbugs/spotbugs/releases)
- [Changelog](https://github.com/spotbugs/spotbugs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/spotbugs/spotbugs/compare/4.2.2...4.2.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:42:57 +00:00
dependabot[bot]
2452add4d7 Chore(deps): Bump jackson-databind from 2.12.1 to 2.12.3
Bumps [jackson-databind](https://github.com/FasterXML/jackson) from 2.12.1 to 2.12.3.
- [Release notes](https://github.com/FasterXML/jackson/releases)
- [Commits](https://github.com/FasterXML/jackson/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:42:56 +00:00
Liam Newman
0dc931ceed Merge pull request #1115 from hub4j/dependabot/github_actions/actions/cache-v2.1.5
Chore(deps): Bump actions/cache from v2.1.4 to v2.1.5
2021-04-19 13:42:48 -07:00
Liam Newman
1dfedc6a58 Merge pull request #1117 from hub4j/dependabot/maven/com.diffplug.spotless-spotless-maven-plugin-2.10.1
Chore(deps): Bump spotless-maven-plugin from 2.9.0 to 2.10.1
2021-04-19 13:42:32 -07:00
dependabot[bot]
e33046a624 Chore(deps): Bump actions/cache from v2.1.4 to v2.1.5
Bumps [actions/cache](https://github.com/actions/cache) from v2.1.4 to v2.1.5.
- [Release notes](https://github.com/actions/cache/releases)
- [Commits](https://github.com/actions/cache/compare/v2.1.4...1a9e2138d905efd099035b49d8b7a3888c653ca8)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:42:30 +00:00
dependabot[bot]
002b3f03da Chore(deps): Bump spotless-maven-plugin from 2.9.0 to 2.10.1
Bumps [spotless-maven-plugin](https://github.com/diffplug/project) from 2.9.0 to 2.10.1.
- [Release notes](https://github.com/diffplug/project/releases)
- [Commits](https://github.com/diffplug/project/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:42:26 +00:00
Liam Newman
fd1817d111 Merge pull request #1122 from hub4j/dependabot/maven/org.mockito-mockito-core-3.9.0
Chore(deps-dev): Bump mockito-core from 3.8.0 to 3.9.0
2021-04-19 13:42:20 -07:00
Liam Newman
7526b46f9d Merge pull request #1121 from hub4j/dependabot/maven/org.kohsuke.stapler-stapler-1.263
Chore(deps-dev): Bump stapler from 1.262 to 1.263
2021-04-19 13:42:07 -07:00
dependabot[bot]
169fd18a54 Chore(deps-dev): Bump mockito-core from 3.8.0 to 3.9.0
Bumps [mockito-core](https://github.com/mockito/mockito) from 3.8.0 to 3.9.0.
- [Release notes](https://github.com/mockito/mockito/releases)
- [Commits](https://github.com/mockito/mockito/compare/v3.8.0...v3.9.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:41:49 +00:00
Liam Newman
0708812456 Merge pull request #1113 from hub4j/dependabot/maven/com.github.spotbugs-spotbugs-maven-plugin-4.2.3
Chore(deps): Bump spotbugs-maven-plugin from 4.2.0 to 4.2.3
2021-04-19 13:41:26 -07:00
dependabot[bot]
7d86070ac8 Chore(deps-dev): Bump stapler from 1.262 to 1.263
Bumps [stapler](https://github.com/stapler/stapler) from 1.262 to 1.263.
- [Release notes](https://github.com/stapler/stapler/releases)
- [Changelog](https://github.com/stapler/stapler/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stapler/stapler/compare/stapler-parent-1.262...stapler-parent-1.263)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:41:24 +00:00
dependabot[bot]
713b85f9de Chore(deps): Bump spotbugs-maven-plugin from 4.2.0 to 4.2.3
Bumps [spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.2.0 to 4.2.3.
- [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases)
- [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.2.0...spotbugs-maven-plugin-4.2.3)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:41:20 +00:00
Liam Newman
4fef5bb1fc Merge pull request #1112 from hub4j/dependabot/github_actions/codecov/codecov-action-v1.4.0
Chore(deps): Bump codecov/codecov-action from v1.3.2 to v1.4.0
2021-04-19 13:41:14 -07:00
Liam Newman
f3eadcddb6 Merge pull request #1111 from hub4j/dependabot/maven/com.tngtech.archunit-archunit-0.18.0
Chore(deps-dev): Bump archunit from 0.17.0 to 0.18.0
2021-04-19 13:41:02 -07:00
Liam Newman
237171727d Merge pull request #1118 from hub4j/dependabot/maven/org.kohsuke-wordnet-random-name-1.5
Chore(deps-dev): Bump wordnet-random-name from 1.3 to 1.5
2021-04-19 13:40:40 -07:00
Liam Newman
31212d33ae Merge pull request #1119 from bitwiseman/task/main
Switch to 'main' as default branch
2021-04-19 13:40:13 -07:00
Liam Newman
8af66133d2 Switch to 'main' as default branch 2021-04-19 13:27:44 -07:00
dependabot[bot]
9578e027b1 Chore(deps-dev): Bump wordnet-random-name from 1.3 to 1.5
Bumps [wordnet-random-name](https://github.com/kohsuke/wordnet-random-name) from 1.3 to 1.5.
- [Release notes](https://github.com/kohsuke/wordnet-random-name/releases)
- [Commits](https://github.com/kohsuke/wordnet-random-name/compare/wordnet-random-name-1.3...wordnet-random-name-1.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:10:36 +00:00
dependabot[bot]
2c75b42b4e Chore(deps): Bump codecov/codecov-action from v1.3.2 to v1.4.0
Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from v1.3.2 to v1.4.0.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/codecov/codecov-action/compare/v1.3.2...0e28ff86a50029a44d10df6ed4c308711925a6a8)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:10:13 +00:00
dependabot[bot]
7854b30a76 Chore(deps-dev): Bump archunit from 0.17.0 to 0.18.0
Bumps [archunit](https://github.com/TNG/ArchUnit) from 0.17.0 to 0.18.0.
- [Release notes](https://github.com/TNG/ArchUnit/releases)
- [Commits](https://github.com/TNG/ArchUnit/compare/v0.17.0...v0.18.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-19 20:10:09 +00:00
Liam Newman
cf2571858c Merge pull request #1107 from akashRindhe/feat/1076
(refactor) Rename gitHubBeforeAfter to nonRecordingGitHub #1076
2021-04-19 10:08:35 -07:00
Akash Rindhe
092815747a (refactor) Rename gitHubBeforeAfter to nonRecordingGitHub #1076
[#1076]
2021-04-18 18:41:10 +08:00
Liam Newman
649d7ed87f Merge pull request #1106 from bitwiseman/issue/1103
GHRepository#listLanguages returns correct Map type
2021-04-16 16:04:57 -07:00
Liam Newman
684560ef67 GHRepository#listLanguages returns correct Map type
This is a less than perfect solution, but it is sufficient to solve the current issue
without risking further side-effects.

Fixes #1103
2021-04-16 14:25:28 -07:00
Liam Newman
adf054ba5d Merge pull request #1105 from akashRindhe/feature/1050
GHIssue.addLabels and removeLabels() should return List<GHLabel> not void [#1050]
2021-04-16 13:10:04 -07:00
Liam Newman
dcdfee67cd Cover more code paths using existing test 2021-04-16 13:00:42 -07:00
Akash Rindhe
9d7209ec62 Merge branch 'master' into feature/1050 2021-04-17 00:23:46 +08:00
Akash Rindhe
b97e8a2c38 (feat) Return GHLabel list instead of void on GHIssue#removeLabel(s) #1050
Includes BridgeMethod annotation to keep binary compatibility
(https://github.com/hub4j/github-api/issues/1050)
2021-04-17 00:22:52 +08:00
Akash Rindhe
8bd3f391da (feat) Return GHLabel list instead of void on GHIssue#addLabels #1050
Includes BridgeMethod annotation to keep binary compatibility
(https://github.com/hub4j/github-api/issues/1050)
2021-04-17 00:06:50 +08:00
Liam Newman
5d0dbf6e2f Merge pull request #1101 from breandan/breandan-patch
Add sort and order parameters to GHContentSearchBuilder
2021-04-15 23:26:47 -07:00
Liam Newman
38f3595552 Streamline code paths 2021-04-15 15:29:50 -07:00
Liam Newman
b72e7fa2ee Add BEST_MATCH and expand test 2021-04-15 14:49:23 -07:00
breandan
659b32f5ec update test data 2021-04-15 16:49:24 -04:00
breandan
d0c326bbf5 apply spotless formatting 2021-04-15 16:42:15 -04:00
breandan
4a5aceb1f9 add content and order parameters to GHContentSearchBuilder as per #1088 2021-04-15 16:29:23 -04:00
Liam Newman
884248930e Merge pull request #1096 from gsmet/add-event-schedule
Add SCHEDULE to GHEvent and add UNKNOWN handling to GHEvent
2021-04-14 15:58:52 -07:00
Liam Newman
530d524366 Merge pull request #1095 from gsmet/no-log-on-cancel
Log 202 message at the FINE level
2021-04-14 15:04:38 -07:00
Guillaume Smet
5957da3d6d Log 202 message at the FINE level 2021-04-14 18:43:52 +02:00
Guillaume Smet
6efe428f57 Log a warning when we have an unknown enum value
Can be useful to catch values we should add instead of simply ignoring
them.
2021-04-14 18:36:36 +02:00
Guillaume Smet
25b9a2ce33 Return GHEvent.UNKNOWN in GHEventInfo.getType() if unknown 2021-04-14 18:36:13 +02:00
Guillaume Smet
0ce78016cc Be more permissive about GHEvent parsing 2021-04-14 16:31:57 +02:00
Guillaume Smet
696dd90b23 Add SCHEDULE to GHEvent
This is a valid event for scheduled workflow runs.
2021-04-14 16:26:43 +02:00
Liam Newman
e66a72387e Merge pull request #1093 from bitwiseman/task/codecov
Ignore ObsoleteUrlFactory
2021-04-12 15:52:58 -07:00
Liam Newman
874ce23dd7 Improve coverage of GitHubClient 2021-04-12 15:19:48 -07:00
Liam Newman
7479cac9a7 Ignore more 2021-04-12 14:21:19 -07:00
Liam Newman
064ce1b0bc Test again 2021-04-12 14:12:26 -07:00
Liam Newman
941573af49 One more attempt to ignore obsolete code 2021-04-12 14:00:18 -07:00
Liam Newman
2f9ff32176 Update and rename .github/codecov.yml to codecov.yml 2021-04-12 11:49:38 -07:00
Liam Newman
b84d5a7c39 Ignore ObsoleteUrlFactory 2021-04-12 11:41:09 -07:00
Liam Newman
bd19f23b3f Merge pull request #1087 from gsmet/label-payload
Add label payload
2021-04-12 10:00:18 -07:00
Liam Newman
ee047ea9b5 Merge pull request #1092 from gsmet/attach-check-runs
Properly wrap the check runs with the repository when listing them
2021-04-12 10:00:01 -07:00
Liam Newman
601f18016a Merge branch 'master' into attach-check-runs 2021-04-12 09:42:56 -07:00
Liam Newman
93abb0ed36 Merge branch 'master' into label-payload 2021-04-12 09:42:11 -07:00
Liam Newman
6453e585a9 Merge pull request #1091 from hub4j/bitwiseman-patch-2
Use codecov.io to report coverage
2021-04-12 09:41:14 -07:00
Liam Newman
3a1ed5a5b7 Create codecov.yml 2021-04-12 09:28:21 -07:00
Liam Newman
c5b45523d6 Update pom.xml 2021-04-12 09:28:04 -07:00
Guillaume Smet
bf082f2a46 Properly wrap the check runs with the repository when listing them 2021-04-12 18:15:23 +02:00
Liam Newman
672febd88b Update pom.xml 2021-04-12 09:07:48 -07:00
Liam Newman
927843ea83 Exclude some files from coverage entirely 2021-04-12 08:54:38 -07:00
Liam Newman
8fac7d317e Use codecov.io to report coverage 2021-04-12 08:34:18 -07:00
Guillaume Smet
626574ae36 Add missing javadoc for GHEventPayload.WorkflowRun 2021-04-10 12:55:05 +02:00
Guillaume Smet
8c9eb3393b Add label payload 2021-04-10 12:55:05 +02:00
Liam Newman
0c4728f46a Create codeql-analysis.yml 2021-04-09 09:52:10 -07:00
Liam Newman
837526ce5d Merge pull request #1083 from bitwiseman/issue/754
Replace reflection with X-HTTP-Method-Override
2021-04-09 09:49:10 -07:00
Liam Newman
afcfa906b8 Merge branch 'master' into issue/754 2021-04-09 09:06:07 -07:00
Liam Newman
8b3f50d4d3 [maven-release-plugin] prepare for next development iteration 2021-04-09 01:26:09 -07:00
Liam Newman
8e20f4d9f5 Replace reflection with X-HTTP-Method-Override
Fixes #754
2021-04-08 14:36:40 -07:00
928 changed files with 10406 additions and 6735 deletions

View File

@@ -1,15 +1,16 @@
# Description # Description
** Describe your change here**
<!-- Describe your change here -->
# Before submitting a PR: # Before submitting a PR:
We love getting PRs, but we hate asking people for the same basic changes every time. We love getting PRs, but we hate asking people for the same basic changes every time.
- [ ] Push your changes to a branch other than `master`. Create your PR from that branch. - [ ] Push your changes to a branch other than `main`. Create your PR from that branch.
- [ ] Add JavaDocs and other comments - [ ] Add JavaDocs and other comments
- [ ] Write tests that run and pass in CI. See [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to capture snapshot data. - [ ] Write tests that run and pass in CI. See [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to capture snapshot data.
- [ ] Run `mvn -D enable-ci clean install site` locally. If this command doesn't succeed, your change will not pass CI. - [ ] Run `mvn -D enable-ci clean install site` locally. If this command doesn't succeed, your change will not pass CI.
# When creating a PR: # When creating a PR:
- [ ] Fill in the "Description" above. - [ ] Fill in the "Description" above.
- [ ] Enable "Allow edits from maintainers". - [ ] Enable "Allow edits from maintainers".

67
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@@ -0,0 +1,67 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ main, gh-pages ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
schedule:
- cron: '20 0 * * 6'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: [ 'java' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

View File

@@ -17,11 +17,12 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK - name: Set up JDK
uses: actions/setup-java@v1 uses: actions/setup-java@v2
with: with:
java-version: ${{ matrix.java }} java-version: ${{ matrix.java }}
distribution: 'adopt'
- name: Cached .m2 - name: Cached .m2
uses: actions/cache@v2.1.4 uses: actions/cache@v2.1.5
with: with:
path: ~/.m2/repository path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
@@ -41,10 +42,11 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK - name: Set up JDK
uses: actions/setup-java@v1 uses: actions/setup-java@v2
with: with:
java-version: ${{ matrix.java }} java-version: ${{ matrix.java }}
- uses: actions/cache@v2.1.4 distribution: 'adopt'
- uses: actions/cache@v2.1.5
with: with:
path: ~/.m2/repository path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
@@ -63,10 +65,11 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK - name: Set up JDK
uses: actions/setup-java@v1 uses: actions/setup-java@v2
with: with:
java-version: ${{ matrix.java }} java-version: ${{ matrix.java }}
- uses: actions/cache@v2.1.4 distribution: 'adopt'
- uses: actions/cache@v2.1.5
with: with:
path: ~/.m2/repository path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
@@ -79,6 +82,9 @@ jobs:
- name: Maven Install with Code Coverage - name: Maven Install with Code Coverage
if: matrix.os != 'windows' && matrix.java == '8' if: matrix.os != 'windows' && matrix.java == '8'
run: mvn -B install -D enable-ci --file pom.xml run: mvn -B install -D enable-ci --file pom.xml
- name: Codecov Report
if: matrix.os != 'windows' && matrix.java == '8'
uses: codecov/codecov-action@v1.4.1
# JDK 11+ # JDK 11+
- name: Maven Install without Code Coverage - name: Maven Install without Code Coverage
if: matrix.os == 'windows' && matrix.java != '8' if: matrix.os == 'windows' && matrix.java != '8'

11
.github/workflows/release-drafter.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
name: Release Drafter
on: push
jobs:
update_release_draft:
runs-on: ubuntu-latest
steps:
- name: Release Drafter
uses: release-drafter/release-drafter@v5.15.0

View File

@@ -41,7 +41,7 @@ Once you have credentials setup, you add new test classes and test methods as yo
Keep `useProxy` enabled and iterate on your tests as needed. With `useProxy` enabled your tests will interact with Keep `useProxy` enabled and iterate on your tests as needed. With `useProxy` enabled your tests will interact with
GitHub - you will need to clean up your server-state between runs. This can be done manually to start with. GitHub - you will need to clean up your server-state between runs. This can be done manually to start with.
Once your test code is somewhat stable, use `getGitHubBeforeAfter()` to get a `GitHub` instance for test setup and cleanup. Once your test code is somewhat stable, use `getNonRecordingGitHub()` to get a `GitHub` instance for test setup and cleanup.
Interactions with that `GitHub` instance will not be recorded as part of the test, keeping the test data files to a minimum. Interactions with that `GitHub` instance will not be recorded as part of the test, keeping the test data files to a minimum.
#### Running tests against your personal GitHub user account #### Running tests against your personal GitHub user account

View File

@@ -2,7 +2,7 @@
[![Sonatype Nexus (Releases)](https://img.shields.io/nexus/r/org.kohsuke/github-api?server=https%3A%2F%2Foss.sonatype.org)](https://mvnrepository.com/artifact/org.kohsuke/github-api) [![Sonatype Nexus (Releases)](https://img.shields.io/nexus/r/org.kohsuke/github-api?server=https%3A%2F%2Foss.sonatype.org)](https://mvnrepository.com/artifact/org.kohsuke/github-api)
[![Join the chat at https://gitter.im/hub4j/github-api](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/hub4j/github-api?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Join the chat at https://gitter.im/hub4j/github-api](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/hub4j/github-api?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
![CI](https://github.com/hub4j/github-api/workflows/CI/badge.svg?branch=master) ![CI](https://github.com/hub4j/github-api/workflows/CI/badge.svg?branch=main)

7
codecov.yml Normal file
View File

@@ -0,0 +1,7 @@
ignore:
- "**/extras/okhttp3/ObsoleteUrlFactory**"
- "**/extras/OkHttpConnector"
- "**/extras/OkHttp3Connector"
- "**/example/**"
- "**/github/EnforcementLevel"

38
pom.xml
View File

@@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.kohsuke</groupId> <groupId>org.kohsuke</groupId>
<artifactId>github-api</artifactId> <artifactId>github-api</artifactId>
<version>1.127</version> <version>1.129</version>
<name>GitHub API for Java</name> <name>GitHub API for Java</name>
<url>https://github-api.kohsuke.org/</url> <url>https://github-api.kohsuke.org/</url>
<description>GitHub API for Java</description> <description>GitHub API for Java</description>
@@ -11,7 +11,7 @@
<connection>scm:git:git@github.com/hub4j/${project.artifactId}.git</connection> <connection>scm:git:git@github.com/hub4j/${project.artifactId}.git</connection>
<developerConnection>scm:git:ssh://git@github.com/hub4j/${project.artifactId}.git</developerConnection> <developerConnection>scm:git:ssh://git@github.com/hub4j/${project.artifactId}.git</developerConnection>
<url>https://github.com/hub4j/github-api/</url> <url>https://github.com/hub4j/github-api/</url>
<tag>github-api-1.127</tag> <tag>github-api-1.129</tag>
</scm> </scm>
<distributionManagement> <distributionManagement>
@@ -33,8 +33,8 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spotbugs-maven-plugin.version>4.2.0</spotbugs-maven-plugin.version> <spotbugs-maven-plugin.version>4.2.3</spotbugs-maven-plugin.version>
<spotbugs.version>4.2.2</spotbugs.version> <spotbugs.version>4.2.3</spotbugs.version>
<spotbugs-maven-plugin.failOnError>true</spotbugs-maven-plugin.failOnError> <spotbugs-maven-plugin.failOnError>true</spotbugs-maven-plugin.failOnError>
<hamcrest.version>2.2</hamcrest.version> <hamcrest.version>2.2</hamcrest.version>
<okhttp3.version>4.4.1</okhttp3.version> <okhttp3.version>4.4.1</okhttp3.version>
@@ -110,6 +110,8 @@
</goals> </goals>
<configuration> <configuration>
<propertyName>jacoco.surefire.argLine</propertyName> <propertyName>jacoco.surefire.argLine</propertyName>
<!-- no need to get data about external code. It dramatically reduces performance of JaCoCo for nothing -->
<include>org.kohsuke.*</include>
</configuration> </configuration>
</execution> </execution>
<!-- attached to Maven test phase --> <!-- attached to Maven test phase -->
@@ -160,9 +162,11 @@
<!-- Deprecated --> <!-- Deprecated -->
<exclude>org.kohsuke.github.extras.OkHttpConnector</exclude>
<exclude>org.kohsuke.github.extras.OkHttp3Connector</exclude> <exclude>org.kohsuke.github.extras.OkHttp3Connector</exclude>
<exclude>org.kohsuke.github.EnforcementLevel</exclude> <exclude>org.kohsuke.github.EnforcementLevel</exclude>
<exclude>org.kohsuke.github.GHPerson.1</exclude> <exclude>org.kohsuke.github.GHPerson.1</exclude>
<!-- TODO: Some coverage, but more needed --> <!-- TODO: Some coverage, but more needed -->
<exclude>org.kohsuke.github.GHPullRequestReviewBuilder.DraftReviewComment</exclude> <exclude>org.kohsuke.github.GHPullRequestReviewBuilder.DraftReviewComment</exclude>
<exclude>org.kohsuke.github.GHIssue.PullRequest</exclude> <exclude>org.kohsuke.github.GHIssue.PullRequest</exclude>
@@ -246,7 +250,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId> <artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.1.1</version> <version>3.1.2</version>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.bcel</groupId> <groupId>org.apache.bcel</groupId>
@@ -319,7 +323,7 @@
<plugin> <plugin>
<groupId>com.diffplug.spotless</groupId> <groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId> <artifactId>spotless-maven-plugin</artifactId>
<version>2.9.0</version> <version>2.10.3</version>
<executions> <executions>
<execution> <execution>
<id>spotless-check</id> <id>spotless-check</id>
@@ -385,7 +389,7 @@
<dependency> <dependency>
<groupId>com.tngtech.archunit</groupId> <groupId>com.tngtech.archunit</groupId>
<artifactId>archunit</artifactId> <artifactId>archunit</artifactId>
<version>0.17.0</version> <version>0.18.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -422,12 +426,12 @@
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<version>2.12.1</version> <version>2.12.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.4</version> <version>2.8.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.infradna.tool</groupId> <groupId>com.infradna.tool</groupId>
@@ -453,7 +457,7 @@
<dependency> <dependency>
<groupId>org.kohsuke.stapler</groupId> <groupId>org.kohsuke.stapler</groupId>
<artifactId>stapler</artifactId> <artifactId>stapler</artifactId>
<version>1.262</version> <version>1.263</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -515,13 +519,13 @@
<dependency> <dependency>
<groupId>org.kohsuke</groupId> <groupId>org.kohsuke</groupId>
<artifactId>wordnet-random-name</artifactId> <artifactId>wordnet-random-name</artifactId>
<version>1.3</version> <version>1.5</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>
<version>3.8.0</version> <version>3.9.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -594,16 +598,6 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile>
<id>jdk11+</id>
<activation>
<jdk>[11,)</jdk>
</activation>
<properties>
<!-- this is required for GithubHttpUrlConnectionClient#setRequestMethod() to work with JDK 16+ -->
<surefire.argLine>--add-opens java.base/java.net=ALL-UNNAMED</surefire.argLine>
</properties>
</profile>
<profile> <profile>
<id>ci-non-windows</id> <id>ci-non-windows</id>
<activation> <activation>

View File

@@ -8,13 +8,13 @@ import javax.annotation.Nonnull;
* Iterable for check-runs listing. * Iterable for check-runs listing.
*/ */
class GHCheckRunsIterable extends PagedIterable<GHCheckRun> { class GHCheckRunsIterable extends PagedIterable<GHCheckRun> {
private final transient GitHub root; private final GHRepository owner;
private final GitHubRequest request; private final GitHubRequest request;
private GHCheckRunsPage result; private GHCheckRunsPage result;
public GHCheckRunsIterable(GitHub root, GitHubRequest request) { public GHCheckRunsIterable(GHRepository owner, GitHubRequest request) {
this.root = root; this.owner = owner;
this.request = request; this.request = request;
} }
@@ -22,7 +22,7 @@ class GHCheckRunsIterable extends PagedIterable<GHCheckRun> {
@Override @Override
public PagedIterator<GHCheckRun> _iterator(int pageSize) { public PagedIterator<GHCheckRun> _iterator(int pageSize) {
return new PagedIterator<>( return new PagedIterator<>(
adapt(GitHubPageIterator.create(root.getClient(), GHCheckRunsPage.class, request, pageSize)), adapt(GitHubPageIterator.create(owner.getRoot().getClient(), GHCheckRunsPage.class, request, pageSize)),
null); null);
} }
@@ -37,7 +37,7 @@ class GHCheckRunsIterable extends PagedIterable<GHCheckRun> {
if (result == null) { if (result == null) {
result = v; result = v;
} }
return v.getCheckRuns(root); return v.getCheckRuns(owner);
} }
}; };
} }

View File

@@ -11,9 +11,9 @@ class GHCheckRunsPage {
return total_count; return total_count;
} }
GHCheckRun[] getCheckRuns(GitHub root) { GHCheckRun[] getCheckRuns(GHRepository owner) {
for (GHCheckRun check_run : check_runs) { for (GHCheckRun check_run : check_runs) {
check_run.wrap(root); check_run.wrap(owner);
} }
return check_runs; return check_runs;
} }

View File

@@ -118,6 +118,41 @@ public class GHContentSearchBuilder extends GHSearchBuilder<GHContent> {
return q("repo:" + v); return q("repo:" + v);
} }
/**
* Order gh content search builder.
*
* @param v
* the v
* @return the gh content search builder
*/
public GHContentSearchBuilder order(GHDirection v) {
req.with("order", v);
return this;
}
/**
* Sort gh content search builder.
*
* @param sort
* the sort
* @return the gh content search builder
*/
public GHContentSearchBuilder sort(GHContentSearchBuilder.Sort sort) {
if (Sort.BEST_MATCH.equals(sort)) {
req.remove("sort");
} else {
req.with("sort", sort);
}
return this;
}
/**
* The enum Sort.
*/
public enum Sort {
BEST_MATCH, INDEXED
}
private static class ContentSearchResult extends SearchResult<GHContent> { private static class ContentSearchResult extends SearchResult<GHContent> {
private GHContent[] items; private GHContent[] items;

View File

@@ -1,7 +1,11 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.kohsuke.github.internal.EnumUtils;
import java.util.Locale; import java.util.Locale;
import javax.annotation.Nonnull;
/** /**
* Hook event type. * Hook event type.
* *
@@ -57,6 +61,7 @@ public enum GHEvent {
REPOSITORY, REPOSITORY,
REPOSITORY_IMPORT, REPOSITORY_IMPORT,
REPOSITORY_VULNERABILITY_ALERT, REPOSITORY_VULNERABILITY_ALERT,
SCHEDULE,
SECURITY_ADVISORY, SECURITY_ADVISORY,
STAR, STAR,
STATUS, STATUS,
@@ -66,6 +71,11 @@ public enum GHEvent {
WORKFLOW_DISPATCH, WORKFLOW_DISPATCH,
WORKFLOW_RUN, WORKFLOW_RUN,
/**
* Special event type that means we haven't found an enum value corresponding to the event.
*/
UNKNOWN,
/** /**
* Special event type that means "every possible event" * Special event type that means "every possible event"
*/ */
@@ -79,4 +89,46 @@ public enum GHEvent {
return "*"; return "*";
return name().toLowerCase(Locale.ENGLISH); return name().toLowerCase(Locale.ENGLISH);
} }
/**
* Representation of GitHub Event Type
*
* @see <a href="https://docs.github.com/en/developers/webhooks-and-events/github-event-types">GitHub event
* types</a>
*/
enum GitHubEventType {
CommitCommentEvent(COMMIT_COMMENT),
CreateEvent(CREATE),
DeleteEvent(DELETE),
ForkEvent(FORK),
GollumEvent(GOLLUM),
IssueCommentEvent(ISSUE_COMMENT),
IssuesEvent(ISSUES),
MemberEvent(MEMBER),
PublicEvent(PUBLIC),
PullRequestEvent(PULL_REQUEST),
PullRequestReviewEvent(PULL_REQUEST_REVIEW),
PullRequestReviewCommentEvent(PULL_REQUEST_REVIEW_COMMENT),
PushEvent(PUSH),
ReleaseEvent(RELEASE),
WatchEvent(WATCH),
UnknownEvent(UNKNOWN);
private final GHEvent event;
GitHubEventType(GHEvent event) {
this.event = event;
}
/**
* Required due to different naming conventions between different GitHub event names for Webhook events and
* GitHub events
*
* @param event
* the github event as a string to convert to Event enum
* @return GHEvent
*/
static GHEvent transformToGHEvent(@Nonnull String event) {
return EnumUtils.getEnumOrDefault(GitHubEventType.class, event, UnknownEvent).event;
}
}
} }

View File

@@ -2,6 +2,7 @@ package org.kohsuke.github;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.kohsuke.github.GHEvent.GitHubEventType;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
@@ -46,14 +47,7 @@ public class GHEventInfo extends GitHubInteractiveObject {
* @return the type * @return the type
*/ */
public GHEvent getType() { public GHEvent getType() {
String t = type; return GitHubEventType.transformToGHEvent(type);
if (t.endsWith("Event"))
t = t.substring(0, t.length() - 5);
for (GHEvent e : GHEvent.values()) {
if (e.name().replace("_", "").equalsIgnoreCase(t))
return e;
}
return null; // unknown event type
} }
GHEventInfo wrapUp(GitHub root) { GHEventInfo wrapUp(GitHub root) {

View File

@@ -711,9 +711,11 @@ public class GHEventPayload extends GitHubInteractiveObject {
} }
/** /**
* Gets master branch. * Gets default branch.
* *
* @return the master branch * Name is an artifact of when "master" was the most common default.
*
* @return the default branch
*/ */
@SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Comes from JSON deserialization") @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD", justification = "Comes from JSON deserialization")
public String getMasterBranch() { public String getMasterBranch() {
@@ -959,7 +961,7 @@ public class GHEventPayload extends GitHubInteractiveObject {
} }
/** /**
* The full Git ref that was pushed. Example: “refs/heads/master * The full Git ref that was pushed. Example: “refs/heads/main
* *
* @return the ref * @return the ref
*/ */
@@ -1384,10 +1386,20 @@ public class GHEventPayload extends GitHubInteractiveObject {
private GHWorkflowRun workflowRun; private GHWorkflowRun workflowRun;
private GHWorkflow workflow; private GHWorkflow workflow;
/**
* Gets the workflow run.
*
* @return the workflow run
*/
public GHWorkflowRun getWorkflowRun() { public GHWorkflowRun getWorkflowRun() {
return workflowRun; return workflowRun;
} }
/**
* Gets the associated workflow.
*
* @return the associated workflow
*/
public GHWorkflow getWorkflow() { public GHWorkflow getWorkflow() {
return workflow; return workflow;
} }
@@ -1407,4 +1419,35 @@ public class GHEventPayload extends GitHubInteractiveObject {
workflow.wrapUp(repository); workflow.wrapUp(repository);
} }
} }
/**
* A label was created, edited or deleted.
*
* @see <a href= "https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#label">
* label event</a>
*/
public static class Label extends GHEventPayload {
private GHLabel label;
private GHLabelChanges changes;
/**
* Gets the label.
*
* @return the label
*/
public GHLabel getLabel() {
return label;
}
/**
* Gets changes (for action="edited")
*
* @return changes
*/
public GHLabelChanges getChanges() {
return changes;
}
}
} }

View File

@@ -328,13 +328,15 @@ public class GHIssue extends GHObject implements Reactable {
* *
* Labels that are already present on the target are ignored. * Labels that are already present on the target are ignored.
* *
* @return the complete list of labels including the new additions
* @param names * @param names
* Names of the label * Names of the label
* @throws IOException * @throws IOException
* the io exception * the io exception
*/ */
public void addLabels(String... names) throws IOException { @WithBridgeMethods(void.class)
_addLabels(Arrays.asList(names)); public List<GHLabel> addLabels(String... names) throws IOException {
return _addLabels(Arrays.asList(names));
} }
/** /**
@@ -342,13 +344,15 @@ public class GHIssue extends GHObject implements Reactable {
* *
* Labels that are already present on the target are ignored. * Labels that are already present on the target are ignored.
* *
* @return the complete list of labels including the new additions
* @param labels * @param labels
* the labels * the labels
* @throws IOException * @throws IOException
* the io exception * the io exception
*/ */
public void addLabels(GHLabel... labels) throws IOException { @WithBridgeMethods(void.class)
addLabels(Arrays.asList(labels)); public List<GHLabel> addLabels(GHLabel... labels) throws IOException {
return addLabels(Arrays.asList(labels));
} }
/** /**
@@ -356,17 +360,23 @@ public class GHIssue extends GHObject implements Reactable {
* *
* Labels that are already present on the target are ignored. * Labels that are already present on the target are ignored.
* *
* @return the complete list of labels including the new additions
* @param labels * @param labels
* the labels * the labels
* @throws IOException * @throws IOException
* the io exception * the io exception
*/ */
public void addLabels(Collection<GHLabel> labels) throws IOException { @WithBridgeMethods(void.class)
_addLabels(GHLabel.toNames(labels)); public List<GHLabel> addLabels(Collection<GHLabel> labels) throws IOException {
return _addLabels(GHLabel.toNames(labels));
} }
private void _addLabels(Collection<String> names) throws IOException { private List<GHLabel> _addLabels(Collection<String> names) throws IOException {
root.createRequest().with("labels", names).method("POST").withUrlPath(getIssuesApiRoute() + "/labels").send(); return Arrays.asList(root.createRequest()
.with("labels", names)
.method("POST")
.withUrlPath(getIssuesApiRoute() + "/labels")
.fetch(GHLabel[].class));
} }
/** /**
@@ -374,13 +384,18 @@ public class GHIssue extends GHObject implements Reactable {
* *
* Attempting to remove a label that is not present throws {@link GHFileNotFoundException}. * Attempting to remove a label that is not present throws {@link GHFileNotFoundException}.
* *
* @return the remaining list of labels
* @param name * @param name
* the name * the name
* @throws IOException * @throws IOException
* the io exception, throws {@link GHFileNotFoundException} if label was not present. * the io exception, throws {@link GHFileNotFoundException} if label was not present.
*/ */
public void removeLabel(String name) throws IOException { @WithBridgeMethods(void.class)
root.createRequest().method("DELETE").withUrlPath(getIssuesApiRoute() + "/labels", name).send(); public List<GHLabel> removeLabel(String name) throws IOException {
return Arrays.asList(root.createRequest()
.method("DELETE")
.withUrlPath(getIssuesApiRoute() + "/labels", name)
.fetch(GHLabel[].class));
} }
/** /**
@@ -388,13 +403,15 @@ public class GHIssue extends GHObject implements Reactable {
* *
* Attempting to remove labels that are not present on the target are ignored. * Attempting to remove labels that are not present on the target are ignored.
* *
* @return the remaining list of labels
* @param names * @param names
* the names * the names
* @throws IOException * @throws IOException
* the io exception * the io exception
*/ */
public void removeLabels(String... names) throws IOException { @WithBridgeMethods(void.class)
_removeLabels(Arrays.asList(names)); public List<GHLabel> removeLabels(String... names) throws IOException {
return _removeLabels(Arrays.asList(names));
} }
/** /**
@@ -402,14 +419,16 @@ public class GHIssue extends GHObject implements Reactable {
* *
* Attempting to remove labels that are not present on the target are ignored. * Attempting to remove labels that are not present on the target are ignored.
* *
* @return the remaining list of labels
* @param labels * @param labels
* the labels * the labels
* @throws IOException * @throws IOException
* the io exception * the io exception
* @see #removeLabels(String...) #removeLabels(String...) * @see #removeLabels(String...) #removeLabels(String...)
*/ */
public void removeLabels(GHLabel... labels) throws IOException { @WithBridgeMethods(void.class)
removeLabels(Arrays.asList(labels)); public List<GHLabel> removeLabels(GHLabel... labels) throws IOException {
return removeLabels(Arrays.asList(labels));
} }
/** /**
@@ -417,23 +436,27 @@ public class GHIssue extends GHObject implements Reactable {
* *
* Attempting to remove labels that are not present on the target are ignored. * Attempting to remove labels that are not present on the target are ignored.
* *
* @return the remaining list of labels
* @param labels * @param labels
* the labels * the labels
* @throws IOException * @throws IOException
* the io exception * the io exception
*/ */
public void removeLabels(Collection<GHLabel> labels) throws IOException { @WithBridgeMethods(void.class)
_removeLabels(GHLabel.toNames(labels)); public List<GHLabel> removeLabels(Collection<GHLabel> labels) throws IOException {
return _removeLabels(GHLabel.toNames(labels));
} }
private void _removeLabels(Collection<String> names) throws IOException { private List<GHLabel> _removeLabels(Collection<String> names) throws IOException {
List<GHLabel> remainingLabels = Collections.emptyList();
for (String name : names) { for (String name : names) {
try { try {
removeLabel(name); remainingLabels = removeLabel(name);
} catch (GHFileNotFoundException e) { } catch (GHFileNotFoundException e) {
// when trying to remove multiple labels, we ignore already removed // when trying to remove multiple labels, we ignore already removed
} }
} }
return remainingLabels;
} }
/** /**

View File

@@ -0,0 +1,49 @@
package org.kohsuke.github;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Wrapper to define changed fields on label action="edited"
*
* @see GHEventPayload.Label
*/
@SuppressFBWarnings("UWF_UNWRITTEN_FIELD")
public class GHLabelChanges {
private GHFrom name;
private GHFrom color;
/**
* Old label name.
*
* @return old label name (or null if not changed)
*/
public GHFrom getName() {
return name;
}
/**
* Old label color.
*
* @return old label color (or null if not changed)
*/
public GHFrom getColor() {
return color;
}
/**
* Wrapper for changed values.
*/
public static class GHFrom {
private String from;
/**
* Previous value that was changed.
*
* @return previous value
*/
public String getFrom() {
return from;
}
}
}

View File

@@ -18,6 +18,9 @@ import static org.kohsuke.github.internal.Previews.INERTIA;
* @author Kohsuke Kawaguchi * @author Kohsuke Kawaguchi
*/ */
public class GHOrganization extends GHPerson { public class GHOrganization extends GHPerson {
private boolean has_organization_projects;
GHOrganization wrapUp(GitHub root) { GHOrganization wrapUp(GitHub root) {
return (GHOrganization) super.wrapUp(root); return (GHOrganization) super.wrapUp(root);
} }
@@ -367,6 +370,35 @@ public class GHOrganization extends GHPerson {
root.createRequest().method("DELETE").withUrlPath("/orgs/" + login + "/public_members/" + u.getLogin()).send(); root.createRequest().method("DELETE").withUrlPath("/orgs/" + login + "/public_members/" + u.getLogin()).send();
} }
/**
* Are projects enabled for organization boolean.
*
* @return the boolean
*/
public boolean areOrganizationProjectsEnabled() {
return has_organization_projects;
}
/**
* Sets organization projects enabled status boolean
*
* @param newStatus
* enable status
* @throws IOException
* the io exception
*/
public void enableOrganizationProjects(boolean newStatus) throws IOException {
edit("has_organization_projects", newStatus);
}
private void edit(String key, Object value) throws IOException {
root.createRequest()
.withUrlPath(String.format("/orgs/%s", login))
.method("PATCH")
.with(key, value)
.fetchInto(this);
}
/** /**
* Returns the projects for this organization. * Returns the projects for this organization.
* *

View File

@@ -12,6 +12,7 @@ import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException; import java.time.format.DateTimeParseException;
import java.util.Date; import java.util.Date;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.annotation.CheckForNull; import javax.annotation.CheckForNull;
@@ -344,7 +345,7 @@ public class GHRateLimit {
private static final UnknownLimitRecord DEFAULT = new UnknownLimitRecord(Long.MIN_VALUE); private static final UnknownLimitRecord DEFAULT = new UnknownLimitRecord(Long.MIN_VALUE);
// The starting current UnknownLimitRecord is an expired record. // The starting current UnknownLimitRecord is an expired record.
private static UnknownLimitRecord current = DEFAULT; private static final AtomicReference<UnknownLimitRecord> current = new AtomicReference<>(DEFAULT);
/** /**
* Create a new unknown record that resets at the specified time. * Create a new unknown record that resets at the specified time.
@@ -356,18 +357,20 @@ public class GHRateLimit {
super(unknownLimit, unknownRemaining, resetEpochSeconds); super(unknownLimit, unknownRemaining, resetEpochSeconds);
} }
static synchronized Record current() { static Record current() {
if (current.isExpired()) { Record result = current.get();
current = new UnknownLimitRecord(System.currentTimeMillis() / 1000L + unknownLimitResetSeconds); if (result.isExpired()) {
current.set(new UnknownLimitRecord(System.currentTimeMillis() / 1000L + unknownLimitResetSeconds));
result = current.get();
} }
return current; return result;
} }
/** /**
* Reset the current UnknownLimitRecord. For use during testing only. * Reset the current UnknownLimitRecord. For use during testing only.
*/ */
static synchronized void reset() { static void reset() {
current = DEFAULT; current.set(DEFAULT);
unknownLimitResetSeconds = defaultUnknownLimitResetSeconds; unknownLimitResetSeconds = defaultUnknownLimitResetSeconds;
} }
} }

View File

@@ -41,7 +41,7 @@ public class GHReleaseBuilder {
* Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. * Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA.
* *
* @param commitish * @param commitish
* Defaults to the repositorys default branch (usually "master"). Unused if the Git tag already exists. * Defaults to the repositorys default branch (usually "main"). Unused if the Git tag already exists.
* @return the gh release builder * @return the gh release builder
*/ */
public GHReleaseBuilder commitish(String commitish) { public GHReleaseBuilder commitish(String commitish) {

View File

@@ -45,7 +45,7 @@ public class GHReleaseUpdater {
* Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. * Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA.
* *
* @param commitish * @param commitish
* Defaults to the repositorys default branch (usually "master"). Unused if the Git tag already exists. * Defaults to the repositorys default branch (usually "main"). Unused if the Git tag already exists.
* @return the gh release updater * @return the gh release updater
*/ */
public GHReleaseUpdater commitish(String commitish) { public GHReleaseUpdater commitish(String commitish) {

View File

@@ -461,7 +461,7 @@ public class GHRepository extends GHObject {
* Creates a named ref, such as tag, branch, etc. * Creates a named ref, such as tag, branch, etc.
* *
* @param name * @param name
* The name of the fully qualified reference (ie: refs/heads/master). If it doesn't start with 'refs' and * The name of the fully qualified reference (ie: refs/heads/main). If it doesn't start with 'refs' and
* have at least two slashes, it will be rejected. * have at least two slashes, it will be rejected.
* @param sha * @param sha
* The SHA1 value to set this reference to * The SHA1 value to set this reference to
@@ -578,7 +578,15 @@ public class GHRepository extends GHObject {
* the io exception * the io exception
*/ */
public Map<String, Long> listLanguages() throws IOException { public Map<String, Long> listLanguages() throws IOException {
return root.createRequest().withUrlPath(getApiTailUrl("languages")).fetch(HashMap.class); HashMap<String, Long> result = new HashMap<>();
root.createRequest().withUrlPath(getApiTailUrl("languages")).fetch(HashMap.class).forEach((key, value) -> {
Long addValue = -1L;
if (value instanceof Integer) {
addValue = Long.valueOf((Integer) value);
}
result.put(key.toString(), addValue);
});
return result;
} }
/** /**
@@ -840,16 +848,18 @@ public class GHRepository extends GHObject {
/** /**
* Returns the primary branch you'll configure in the "Admin &gt; Options" config page. * Returns the primary branch you'll configure in the "Admin &gt; Options" config page.
* *
* @return This field is null until the user explicitly configures the master branch. * @return This field is null until the user explicitly configures the default branch.
*/ */
public String getDefaultBranch() { public String getDefaultBranch() {
return default_branch; return default_branch;
} }
/** /**
* Gets master branch. * Gets default branch.
* *
* @return the master branch * Name is an artifact of when "master" was the most common default.
*
* @return the default branch
* @deprecated Renamed to {@link #getDefaultBranch()} * @deprecated Renamed to {@link #getDefaultBranch()}
*/ */
@Deprecated @Deprecated
@@ -1767,7 +1777,7 @@ public class GHRepository extends GHObject {
* Retrive a tree of the given type for the current GitHub repository. * Retrive a tree of the given type for the current GitHub repository.
* *
* @param sha * @param sha
* sha number or branch name ex: "master" * sha number or branch name ex: "main"
* @return refs matching the request type * @return refs matching the request type
* @throws IOException * @throws IOException
* on failure communicating with GitHub, potentially due to an invalid tree type being requested * on failure communicating with GitHub, potentially due to an invalid tree type being requested
@@ -1791,7 +1801,7 @@ public class GHRepository extends GHObject {
* https://developer.github.com/v3/git/trees/#get-a-tree-recursively * https://developer.github.com/v3/git/trees/#get-a-tree-recursively
* *
* @param sha * @param sha
* sha number or branch name ex: "master" * sha number or branch name ex: "main"
* @param recursive * @param recursive
* use 1 * use 1
* @return the tree recursive * @return the tree recursive
@@ -2010,7 +2020,7 @@ public class GHRepository extends GHObject {
.withUrlPath(String.format("/repos/%s/%s/commits/%s/check-runs", getOwnerName(), name, ref)) .withUrlPath(String.format("/repos/%s/%s/commits/%s/check-runs", getOwnerName(), name, ref))
.withPreview(ANTIOPE) .withPreview(ANTIOPE)
.build(); .build();
return new GHCheckRunsIterable(root, request); return new GHCheckRunsIterable(this, request);
} }
/** /**
@@ -3142,7 +3152,7 @@ public class GHRepository extends GHObject {
* @param streamFunction * @param streamFunction
* The {@link InputStreamFunction} that will process the stream * The {@link InputStreamFunction} that will process the stream
* @param ref * @param ref
* if <code>null</code> the repository's default branch, usually <code>master</code>, * if <code>null</code> the repository's default branch, usually <code>main</code>,
* @throws IOException * @throws IOException
* The IO exception. * The IO exception.
* @return the result of reading the stream. * @return the result of reading the stream.
@@ -3159,7 +3169,7 @@ public class GHRepository extends GHObject {
* @param streamFunction * @param streamFunction
* The {@link InputStreamFunction} that will process the stream * The {@link InputStreamFunction} that will process the stream
* @param ref * @param ref
* if <code>null</code> the repository's default branch, usually <code>master</code>, * if <code>null</code> the repository's default branch, usually <code>main</code>,
* @throws IOException * @throws IOException
* The IO exception. * The IO exception.
* @return the result of reading the stream. * @return the result of reading the stream.

View File

@@ -188,7 +188,7 @@ public class GHWorkflowRun extends GHObject {
* @return type of event * @return type of event
*/ */
public GHEvent getEvent() { public GHEvent getEvent() {
return Enum.valueOf(GHEvent.class, event.toUpperCase(Locale.ROOT)); return EnumUtils.getNullableEnumOrDefault(GHEvent.class, event, GHEvent.UNKNOWN);
} }
/** /**

View File

@@ -14,6 +14,7 @@ import java.time.Instant;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.*; import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -52,10 +53,8 @@ abstract class GitHubClient {
private HttpConnector connector; private HttpConnector connector;
private final Object rateLimitLock = new Object();
@Nonnull @Nonnull
private GHRateLimit rateLimit = GHRateLimit.DEFAULT; private final AtomicReference<GHRateLimit> rateLimit = new AtomicReference<>(GHRateLimit.DEFAULT);
private static final Logger LOGGER = Logger.getLogger(GitHubClient.class.getName()); private static final Logger LOGGER = Logger.getLogger(GitHubClient.class.getName());
@@ -141,10 +140,9 @@ abstract class GitHubClient {
getRateLimit(); getRateLimit();
return true; return true;
} catch (IOException e) { } catch (IOException e) {
if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE,
LOGGER.log(FINE, "Exception validating credentials on " + getApiUrl() + " with login '" + login + "' " + e,
"Exception validating credentials on " + getApiUrl() + " with login '" + login + "' " + e, e);
e);
return false; return false;
} }
} }
@@ -256,9 +254,7 @@ abstract class GitHubClient {
@Nonnull @Nonnull
@Deprecated @Deprecated
GHRateLimit lastRateLimit() { GHRateLimit lastRateLimit() {
synchronized (rateLimitLock) { return rateLimit.get();
return rateLimit;
}
} }
/** /**
@@ -278,12 +274,19 @@ abstract class GitHubClient {
*/ */
@Nonnull @Nonnull
GHRateLimit rateLimit(@Nonnull RateLimitTarget rateLimitTarget) throws IOException { GHRateLimit rateLimit(@Nonnull RateLimitTarget rateLimitTarget) throws IOException {
synchronized (rateLimitLock) { GHRateLimit result = rateLimit.get();
if (rateLimit.getRecord(rateLimitTarget).isExpired()) { // Most of the time rate limit is not expired, so try to avoid locking.
getRateLimit(rateLimitTarget); if (result.getRecord(rateLimitTarget).isExpired()) {
// if the rate limit is expired, synchronize to ensure
// only one call to getRateLimit() is made to refresh it.
synchronized (this) {
if (rateLimit.get().getRecord(rateLimitTarget).isExpired()) {
getRateLimit(rateLimitTarget);
}
} }
return rateLimit; result = rateLimit.get();
} }
return result;
} }
/** /**
@@ -296,15 +299,9 @@ abstract class GitHubClient {
* {@link GHRateLimit.Record} constructed from the response header information * {@link GHRateLimit.Record} constructed from the response header information
*/ */
private GHRateLimit updateRateLimit(@Nonnull GHRateLimit observed) { private GHRateLimit updateRateLimit(@Nonnull GHRateLimit observed) {
synchronized (rateLimitLock) { GHRateLimit result = rateLimit.accumulateAndGet(observed, (current, x) -> current.getMergedRateLimit(x));
observed = rateLimit.getMergedRateLimit(observed); LOGGER.log(FINEST, "Rate limit now: {0}", rateLimit.get());
return result;
if (rateLimit != observed) {
rateLimit = observed;
LOGGER.log(FINE, "Rate limit now: {0}", rateLimit);
}
return rateLimit;
}
} }
/** /**
@@ -384,11 +381,7 @@ abstract class GitHubClient {
GitHubResponse.ResponseInfo responseInfo = null; GitHubResponse.ResponseInfo responseInfo = null;
try { try {
try { try {
if (LOGGER.isLoggable(FINE)) { logRequest(request);
LOGGER.log(FINE,
"GitHub API request [" + (login == null ? "anonymous" : login) + "]: "
+ request.method() + " " + request.url().toString());
}
rateLimitChecker.checkRateLimit(this, request); rateLimitChecker.checkRateLimit(this, request);
responseInfo = getResponseInfo(request); responseInfo = getResponseInfo(request);
@@ -424,6 +417,12 @@ abstract class GitHubClient {
throw new GHIOException("Ran out of retries for URL: " + request.url().toString()); throw new GHIOException("Ran out of retries for URL: " + request.url().toString());
} }
private void logRequest(@Nonnull final GitHubRequest request) {
LOGGER.log(FINE,
() -> "GitHub API request [" + (login == null ? "anonymous" : login) + "]: " + request.method() + " "
+ request.url().toString());
}
@Nonnull @Nonnull
protected abstract GitHubResponse.ResponseInfo getResponseInfo(GitHubRequest request) throws IOException; protected abstract GitHubResponse.ResponseInfo getResponseInfo(GitHubRequest request) throws IOException;
@@ -437,20 +436,15 @@ abstract class GitHubClient {
// special case handling for 304 unmodified, as the content will be "" // special case handling for 304 unmodified, as the content will be ""
} else if (responseInfo.statusCode() == HttpURLConnection.HTTP_ACCEPTED) { } else if (responseInfo.statusCode() == HttpURLConnection.HTTP_ACCEPTED) {
// Response code 202 means data is being generated. // Response code 202 means data is being generated or an action that can require some time is triggered.
// This happens in specific cases: // This happens in specific cases:
// statistics - See https://developer.github.com/v3/repos/statistics/#a-word-about-caching // statistics - See https://developer.github.com/v3/repos/statistics/#a-word-about-caching
// fork creation - See https://developer.github.com/v3/repos/forks/#create-a-fork // fork creation - See https://developer.github.com/v3/repos/forks/#create-a-fork
// workflow run cancellation - See https://docs.github.com/en/rest/reference/actions#cancel-a-workflow-run
if (responseInfo.url().toString().endsWith("/forks")) { LOGGER.log(FINE,
LOGGER.log(INFO, "The fork is being created. Please try again in 5 seconds."); "Received HTTP_ACCEPTED(202) from " + responseInfo.url().toString()
} else if (responseInfo.url().toString().endsWith("/statistics")) { + " . Please try again in 5 seconds.");
LOGGER.log(INFO, "The statistics are being generated. Please try again in 5 seconds.");
} else {
LOGGER.log(INFO,
"Received 202 from " + responseInfo.url().toString() + " . Please try again in 5 seconds.");
}
// Maybe throw an exception instead?
} else if (handler != null) { } else if (handler != null) {
body = handler.apply(responseInfo); body = handler.apply(responseInfo);
} }
@@ -562,9 +556,7 @@ abstract class GitHubClient {
GHRateLimit.Record observed = new GHRateLimit.Record(limit, remaining, reset, responseInfo); GHRateLimit.Record observed = new GHRateLimit.Record(limit, remaining, reset, responseInfo);
updateRateLimit(GHRateLimit.fromRecord(observed, responseInfo.request().rateLimitTarget())); updateRateLimit(GHRateLimit.fromRecord(observed, responseInfo.request().rateLimitTarget()));
} catch (NumberFormatException | NullPointerException e) { } catch (NumberFormatException | NullPointerException e) {
if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Missing or malformed X-RateLimit header: ", e);
LOGGER.log(FINEST, "Missing or malformed X-RateLimit header: ", e);
}
} }
} }

View File

@@ -5,7 +5,6 @@ import org.kohsuke.github.authorization.AuthorizationProvider;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.ProtocolException; import java.net.ProtocolException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -163,30 +162,9 @@ class GitHubHttpUrlConnectionClient extends GitHubClient {
connection.setRequestMethod(method); connection.setRequestMethod(method);
} catch (ProtocolException e) { } catch (ProtocolException e) {
// JDK only allows one of the fixed set of verbs. Try to override that // JDK only allows one of the fixed set of verbs. Try to override that
try { connection.setRequestProperty("X-HTTP-Method-Override", method);
Field $method = HttpURLConnection.class.getDeclaredField("method"); connection.setRequestMethod("POST");
$method.setAccessible(true);
$method.set(connection, method);
} catch (Exception x) {
throw (IOException) new IOException("Failed to set the custom verb").initCause(x);
}
// sun.net.www.protocol.https.DelegatingHttpsURLConnection delegates to another HttpURLConnection
try {
Field $delegate = connection.getClass().getDeclaredField("delegate");
$delegate.setAccessible(true);
Object delegate = $delegate.get(connection);
if (delegate instanceof HttpURLConnection) {
HttpURLConnection nested = (HttpURLConnection) delegate;
setRequestMethod(method, nested);
}
} catch (NoSuchFieldException x) {
// no problem
} catch (IllegalAccessException x) {
throw (IOException) new IOException("Failed to set the custom verb").initCause(x);
}
} }
if (!connection.getRequestMethod().equals(method))
throw new IllegalStateException("Failed to set the request method to " + method);
} }
/** /**

View File

@@ -602,13 +602,27 @@ class GitHubRequest {
* @return the request builder * @return the request builder
*/ */
public B set(String key, Object value) { public B set(String key, Object value) {
for (int index = 0; index < args.size(); index++) { remove(key);
return with(key, value);
}
/**
* Removes all arg entries for a specific key.
*
* @param key
* the key
* @return the request builder
*/
public B remove(String key) {
for (int index = 0; index < args.size();) {
if (args.get(index).key.equals(key)) { if (args.get(index).key.equals(key)) {
args.set(index, new Entry(key, value)); args.remove(index);
return (B) this; } else {
index++;
} }
} }
return with(key, value); return (B) this;
} }
/** /**

View File

@@ -1,12 +1,15 @@
package org.kohsuke.github.internal; package org.kohsuke.github.internal;
import java.util.Locale; import java.util.Locale;
import java.util.logging.Logger;
/** /**
* Utils for Enums. * Utils for Enums.
*/ */
public final class EnumUtils { public final class EnumUtils {
private static final Logger LOGGER = Logger.getLogger(EnumUtils.class.getName());
/** /**
* Returns an enum value matching the value if found, null if the value is null and {@code defaultEnum} if the value * Returns an enum value matching the value if found, null if the value is null and {@code defaultEnum} if the value
* cannot be matched to a value of the enum. * cannot be matched to a value of the enum.
@@ -27,9 +30,29 @@ public final class EnumUtils {
if (value == null) { if (value == null) {
return null; return null;
} }
return getEnumOrDefault(enumClass, value.toUpperCase(Locale.ROOT), defaultEnum);
}
/**
* Returns an enum value matching the value if found, {@code defaultEnum} if the value is null or cannot be matched
* to a value of the enum.
*
* @param <E>
* the type of the enum
* @param enumClass
* the type of the enum
* @param value
* the value to interpret
* @param defaultEnum
* the default enum value if the value doesn't match one of the enum value
* @return an enum value
*/
public static <E extends Enum<E>> E getEnumOrDefault(Class<E> enumClass, String value, E defaultEnum) {
try { try {
return Enum.valueOf(enumClass, value.toUpperCase(Locale.ROOT)); return Enum.valueOf(enumClass, value);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
LOGGER.warning("Unknown value " + value + " for enum class " + enumClass.getName() + ", defaulting to "
+ defaultEnum.name());
return defaultEnum; return defaultEnum;
} }
} }

View File

@@ -4,10 +4,9 @@ import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer; import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.HandlebarsCurrentDateHelper; import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.HandlebarsCurrentDateHelper;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.hamcrest.Description;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.hamcrest.StringDescription;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@@ -21,13 +20,14 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
/** /**
* @author Liam Newman * @author Liam Newman
*/ */
public abstract class AbstractGitHubWireMockTest extends Assert { public abstract class AbstractGitHubWireMockTest {
private final GitHubBuilder githubBuilder = createGitHubBuilder(); private final GitHubBuilder githubBuilder = createGitHubBuilder();
@@ -45,7 +45,7 @@ public abstract class AbstractGitHubWireMockTest extends Assert {
*/ */
protected GitHub gitHub; protected GitHub gitHub;
private GitHub gitHubBeforeAfter; private GitHub nonRecordingGitHub;
protected final String baseFilesClassPath = this.getClass().getName().replace('.', '/'); protected final String baseFilesClassPath = this.getClass().getName().replace('.', '/');
protected final String baseRecordPath = "src/test/resources/" + baseFilesClassPath + "/wiremock"; protected final String baseRecordPath = "src/test/resources/" + baseFilesClassPath + "/wiremock";
@@ -115,9 +115,9 @@ public abstract class AbstractGitHubWireMockTest extends Assert {
} }
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
gitHubBeforeAfter = getGitHubBuilder().withEndpoint("https://api.github.com/").build(); nonRecordingGitHub = getGitHubBuilder().withEndpoint("https://api.github.com/").build();
} else { } else {
gitHubBeforeAfter = null; nonRecordingGitHub = null;
} }
} }
@@ -210,7 +210,7 @@ public abstract class AbstractGitHubWireMockTest extends Assert {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
tempGitHubRepositories.add(fullName); tempGitHubRepositories.add(fullName);
try { try {
GHRepository repository = getGitHubBeforeAfter().getRepository(fullName); GHRepository repository = getNonRecordingGitHub().getRepository(fullName);
if (repository != null) { if (repository != null) {
repository.delete(); repository.delete();
} }
@@ -227,22 +227,22 @@ public abstract class AbstractGitHubWireMockTest extends Assert {
* *
* @return a github instance after checking Authentication * @return a github instance after checking Authentication
*/ */
public GitHub getGitHubBeforeAfter() { public GitHub getNonRecordingGitHub() {
verifyAuthenticated(gitHubBeforeAfter); verifyAuthenticated(nonRecordingGitHub);
return gitHubBeforeAfter; return nonRecordingGitHub;
} }
protected void kohsuke() { protected void kohsuke() {
// No-op for now // No-op for now
// Generally this means the test is doing something that requires additional access rights // Generally this means the test is doing something that requires additional access rights
// Not always clear which ones. // Not always clear which ones.
// TODO: Add helpers that assert the expected rights using gitHubBeforeAfter and only when proxy is enabled // TODO: Add helpers that assert the expected rights using nonRecordingGitHub and only when proxy is enabled
// String login = getUserTest().getLogin(); // String login = getUserTest().getLogin();
// assumeTrue(login.equals("kohsuke") || login.equals("kohsuke2")); // assumeTrue(login.equals("kohsuke") || login.equals("kohsuke2"));
} }
private GHCreateRepositoryBuilder getCreateBuilder(String name) throws IOException { private GHCreateRepositoryBuilder getCreateBuilder(String name) throws IOException {
GitHub github = getGitHubBeforeAfter(); GitHub github = getNonRecordingGitHub();
if (mockGitHub.isTestWithOrg()) { if (mockGitHub.isTestWithOrg()) {
return github.getOrganization(GITHUB_API_TEST_ORG).createRepository(name); return github.getOrganization(GITHUB_API_TEST_ORG).createRepository(name);
@@ -255,52 +255,23 @@ public abstract class AbstractGitHubWireMockTest extends Assert {
return mockGitHub.isTestWithOrg() ? GITHUB_API_TEST_ORG : gitHub.getMyself().getLogin(); return mockGitHub.isTestWithOrg() ? GITHUB_API_TEST_ORG : gitHub.getMyself().getLogin();
} }
public static void fail() {
Assert.fail();
}
public static void fail(String reason) {
Assert.fail(reason);
}
public static <T> void assertThat(T actual, Matcher<? super T> matcher) { public static <T> void assertThat(T actual, Matcher<? super T> matcher) {
assertThat("", actual, matcher); MatcherAssert.assertThat("", actual, matcher);
} }
public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher) { public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher) {
if (!matcher.matches(actual)) { MatcherAssert.assertThat(reason, actual, matcher);
Description description = new StringDescription();
description.appendText(reason)
.appendText(System.lineSeparator())
.appendText("Expected: ")
.appendDescriptionOf(matcher)
.appendText(System.lineSeparator())
.appendText(" but: ");
matcher.describeMismatch(actual, description);
throw new AssertionError(description.toString());
}
} }
public static void assertThat(String reason, boolean assertion) { public static void assertThat(String reason, boolean assertion) {
if (!assertion) { MatcherAssert.assertThat(reason, assertion);
throw new AssertionError(reason);
}
}
public static void assertEquals(Object expected, Object actual) {
assertThat(actual, Matchers.equalTo(expected));
}
public static void assertNotEquals(Object expected, Object actual) {
assertThat(actual, Matchers.not(expected));
}
public static void assertNotNull(Object actual) {
assertThat(actual, Matchers.notNullValue());
}
public static void assertNull(Object actual) {
assertThat(actual, Matchers.nullValue());
}
public static void assertTrue(Boolean condition) {
assertThat(condition, Matchers.is(true));
}
public static void assertFalse(Boolean condition) {
assertThat(condition, Matchers.is(false));
} }
protected static class TemplatingHelper { protected static class TemplatingHelper {

View File

@@ -17,7 +17,6 @@ import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.regex.Pattern;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
@@ -84,20 +83,20 @@ public class AppTest extends AbstractGitHubWireMockTest {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
Thread.sleep(3000); Thread.sleep(3000);
} }
assertNotNull(r.getReadme()); assertThat(r.getReadme(), notNullValue());
r.delete(); r.delete();
} }
private void cleanupUserRepository(final String name) throws IOException { private void cleanupUserRepository(final String name) throws IOException {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
cleanupRepository(getUser(getGitHubBeforeAfter()).getLogin() + "/" + name); cleanupRepository(getUser(getNonRecordingGitHub()).getLogin() + "/" + name);
} }
} }
@Test @Test
public void testCredentialValid() throws IOException { public void testCredentialValid() throws IOException {
assertTrue(gitHub.isCredentialValid()); assertThat(gitHub.isCredentialValid(), is(true));
assertThat(gitHub.lastRateLimit().getCore(), not(instanceOf(GHRateLimit.UnknownLimitRecord.class))); assertThat(gitHub.lastRateLimit().getCore(), not(instanceOf(GHRateLimit.UnknownLimitRecord.class)));
assertThat(gitHub.lastRateLimit().getCore().getLimit(), equalTo(5000)); assertThat(gitHub.lastRateLimit().getCore().getLimit(), equalTo(5000));
@@ -105,7 +104,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
.withEndpoint(mockGitHub.apiServer().baseUrl()) .withEndpoint(mockGitHub.apiServer().baseUrl())
.build(); .build();
assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT)); assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT));
assertFalse(gitHub.isCredentialValid()); assertThat(gitHub.isCredentialValid(), is(false));
// For invalid credentials, we get a 401 but it includes anonymous rate limit headers // For invalid credentials, we get a 401 but it includes anonymous rate limit headers
assertThat(gitHub.lastRateLimit().getCore(), not(instanceOf(GHRateLimit.UnknownLimitRecord.class))); assertThat(gitHub.lastRateLimit().getCore(), not(instanceOf(GHRateLimit.UnknownLimitRecord.class)));
assertThat(gitHub.lastRateLimit().getCore().getLimit(), equalTo(60)); assertThat(gitHub.lastRateLimit().getCore().getLimit(), equalTo(60));
@@ -116,7 +115,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
// Simulated GHE: getRateLimit returns 404 // Simulated GHE: getRateLimit returns 404
assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT)); assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT));
assertThat(gitHub.lastRateLimit().getCore().isExpired(), is(true)); assertThat(gitHub.lastRateLimit().getCore().isExpired(), is(true));
assertTrue(gitHub.isCredentialValid()); assertThat(gitHub.isCredentialValid(), is(true));
// lastRateLimitUpdates because 404 still includes header rate limit info // lastRateLimitUpdates because 404 still includes header rate limit info
assertThat(gitHub.lastRateLimit(), notNullValue()); assertThat(gitHub.lastRateLimit(), notNullValue());
@@ -127,7 +126,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
.withEndpoint(mockGitHub.apiServer().baseUrl()) .withEndpoint(mockGitHub.apiServer().baseUrl())
.build(); .build();
assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT)); assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT));
assertFalse(gitHub.isCredentialValid()); assertThat(gitHub.isCredentialValid(), is(false));
// Simulated GHE: For invalid credentials, we get a 401 that does not include ratelimit info // Simulated GHE: For invalid credentials, we get a 401 that does not include ratelimit info
assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT)); assertThat(gitHub.lastRateLimit(), sameInstance(GHRateLimit.DEFAULT));
} }
@@ -138,7 +137,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHIssue i = repository.getIssue(4); GHIssue i = repository.getIssue(4);
List<GHIssueComment> v = i.getComments(); List<GHIssueComment> v = i.getComments();
// System.out.println(v); // System.out.println(v);
assertTrue(v.isEmpty()); assertThat(v, is(empty()));
i = repository.getIssue(3); i = repository.getIssue(3);
v = i.getComments(); v = i.getComments();
@@ -151,7 +150,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
assertThat(v.get(0).getParent().getNumber(), equalTo(3)); assertThat(v.get(0).getParent().getNumber(), equalTo(3));
assertThat(v.get(0).getParent().getId(), equalTo(6863845L)); assertThat(v.get(0).getParent().getId(), equalTo(6863845L));
assertThat(v.get(0).getUser().getLogin(), equalTo("kohsuke")); assertThat(v.get(0).getUser().getLogin(), equalTo("kohsuke"));
assertThat(v.get(0).listReactions().toList().size(), equalTo(0)); assertThat(v.get(0).listReactions().toList(), is(empty()));
assertThat(v.get(1).getHtmlUrl().toString(), assertThat(v.get(1).getHtmlUrl().toString(),
equalTo("https://github.com/kohsuke/test/issues/3#issuecomment-8547251")); equalTo("https://github.com/kohsuke/test/issues/3#issuecomment-8547251"));
@@ -179,7 +178,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
.label("question") .label("question")
.milestone(milestone) .milestone(milestone)
.create(); .create();
assertNotNull(o); assertThat(o, notNullValue());
o.close(); o.close();
} }
@@ -192,17 +191,17 @@ public class AppTest extends AbstractGitHubWireMockTest {
.environment("unittest") .environment("unittest")
.create(); .create();
try { try {
assertNotNull(deployment.getCreator()); assertThat(deployment.getCreator(), notNullValue());
assertNotNull(deployment.getId()); assertThat(deployment.getId(), notNullValue());
List<GHDeployment> deployments = repository.listDeployments(null, "main", null, "unittest").toList(); List<GHDeployment> deployments = repository.listDeployments(null, "main", null, "unittest").toList();
assertNotNull(deployments); assertThat(deployments, notNullValue());
assertFalse(Iterables.isEmpty(deployments)); assertThat(deployments, is(not(emptyIterable())));
GHDeployment unitTestDeployment = deployments.get(0); GHDeployment unitTestDeployment = deployments.get(0);
assertEquals("unittest", unitTestDeployment.getEnvironment()); assertThat(unitTestDeployment.getEnvironment(), equalTo("unittest"));
assertEquals("unittest", unitTestDeployment.getOriginalEnvironment()); assertThat(unitTestDeployment.getOriginalEnvironment(), equalTo("unittest"));
assertEquals(false, unitTestDeployment.isProductionEnvironment()); assertThat(unitTestDeployment.isProductionEnvironment(), equalTo(false));
assertEquals(false, unitTestDeployment.isTransientEnvironment()); assertThat(unitTestDeployment.isTransientEnvironment(), equalTo(false));
assertEquals("main", unitTestDeployment.getRef()); assertThat(unitTestDeployment.getRef(), equalTo("main"));
} finally { } finally {
// deployment.delete(); // deployment.delete();
assert true; assert true;
@@ -225,15 +224,15 @@ public class AppTest extends AbstractGitHubWireMockTest {
.environment("new-ci-env") .environment("new-ci-env")
.create(); .create();
Iterable<GHDeploymentStatus> deploymentStatuses = deployment.listStatuses(); Iterable<GHDeploymentStatus> deploymentStatuses = deployment.listStatuses();
assertNotNull(deploymentStatuses); assertThat(deploymentStatuses, notNullValue());
assertEquals(1, Iterables.size(deploymentStatuses)); assertThat(Iterables.size(deploymentStatuses), equalTo(1));
GHDeploymentStatus actualStatus = Iterables.get(deploymentStatuses, 0); GHDeploymentStatus actualStatus = Iterables.get(deploymentStatuses, 0);
assertEquals(ghDeploymentStatus.getId(), actualStatus.getId()); assertThat(actualStatus.getId(), equalTo(ghDeploymentStatus.getId()));
assertEquals(ghDeploymentStatus.getState(), actualStatus.getState()); assertThat(actualStatus.getState(), equalTo(ghDeploymentStatus.getState()));
assertEquals(ghDeploymentStatus.getLogUrl(), actualStatus.getLogUrl()); assertThat(actualStatus.getLogUrl(), equalTo(ghDeploymentStatus.getLogUrl()));
// Target url was deprecated and replaced with log url. The gh api will // Target url was deprecated and replaced with log url. The gh api will
// prefer the log url value and return it in place of target url. // prefer the log url value and return it in place of target url.
assertEquals(ghDeploymentStatus.getTargetUrl(), actualStatus.getLogUrl()); assertThat(actualStatus.getLogUrl(), equalTo(ghDeploymentStatus.getTargetUrl()));
assertThat(ghDeploymentStatus.getDeploymentUrl(), equalTo(deployment.getUrl())); assertThat(ghDeploymentStatus.getDeploymentUrl(), equalTo(deployment.getUrl()));
assertThat(ghDeploymentStatus.getRepositoryUrl(), equalTo(repository.getUrl())); assertThat(ghDeploymentStatus.getRepositoryUrl(), equalTo(repository.getUrl()));
} finally { } finally {
@@ -248,7 +247,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
.getRepository("github-api") .getRepository("github-api")
.getIssues(GHIssueState.CLOSED); .getIssues(GHIssueState.CLOSED);
// prior to using PagedIterable GHRepository.getIssues(GHIssueState) would only retrieve 30 issues // prior to using PagedIterable GHRepository.getIssues(GHIssueState) would only retrieve 30 issues
assertTrue(closedIssues.size() > 150); assertThat(closedIssues.size(), greaterThan(150));
String readRepoString = GitHub.getMappingObjectWriter().writeValueAsString(closedIssues.get(0)); String readRepoString = GitHub.getMappingObjectWriter().writeValueAsString(closedIssues.get(0));
} }
@@ -264,11 +263,11 @@ public class AppTest extends AbstractGitHubWireMockTest {
int x = 0; int x = 0;
for (GHIssue issue : closedIssues) { for (GHIssue issue : closedIssues) {
assertNotNull(issue); assertThat(issue, notNullValue());
x++; x++;
} }
assertTrue(x > 150); assertThat(x, greaterThan(150));
} }
@Test @Test
@@ -279,7 +278,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testMyOrganizations() throws IOException { public void testMyOrganizations() throws IOException {
Map<String, GHOrganization> org = gitHub.getMyOrganizations(); Map<String, GHOrganization> org = gitHub.getMyOrganizations();
assertFalse(org.keySet().contains(null)); assertThat(org.containsKey(null), is(false));
// System.out.println(org); // System.out.println(org);
} }
@@ -289,7 +288,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
Map<String, GHOrganization> myOrganizations = gitHub.getMyOrganizations(); Map<String, GHOrganization> myOrganizations = gitHub.getMyOrganizations();
// GitHub no longer has default 'owners' team, so there may be organization memberships without a team // GitHub no longer has default 'owners' team, so there may be organization memberships without a team
// https://help.github.com/articles/about-improved-organization-permissions/ // https://help.github.com/articles/about-improved-organization-permissions/
assertTrue(myOrganizations.keySet().containsAll(teams.keySet())); assertThat(myOrganizations.keySet().containsAll(teams.keySet()), is(true));
} }
@Test @Test
@@ -299,7 +298,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
String organizationName = teamsPerOrg.getKey(); String organizationName = teamsPerOrg.getKey();
for (GHTeam team : teamsPerOrg.getValue()) { for (GHTeam team : teamsPerOrg.getValue()) {
String teamName = team.getName(); String teamName = team.getName();
assertTrue("Team " + teamName + " in organization " + organizationName + " does not contain myself", assertThat("Team " + teamName + " in organization " + organizationName + " does not contain myself",
shouldBelongToTeam(organizationName, teamName)); shouldBelongToTeam(organizationName, teamName));
} }
} }
@@ -312,7 +311,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
user.login = "kohsuke"; user.login = "kohsuke";
Map<String, GHOrganization> orgs = gitHub.getUserPublicOrganizations(user); Map<String, GHOrganization> orgs = gitHub.getUserPublicOrganizations(user);
assertFalse(orgs.isEmpty()); assertThat(orgs.size(), greaterThan(0));
} }
@Test @Test
@@ -322,14 +321,14 @@ public class AppTest extends AbstractGitHubWireMockTest {
user.login = "bitwiseman"; user.login = "bitwiseman";
Map<String, GHOrganization> orgs = gitHub.getUserPublicOrganizations(user); Map<String, GHOrganization> orgs = gitHub.getUserPublicOrganizations(user);
assertTrue(orgs.isEmpty()); assertThat(orgs.size(), equalTo(0));
} }
private boolean shouldBelongToTeam(String organizationName, String teamName) throws IOException { private boolean shouldBelongToTeam(String organizationName, String teamName) throws IOException {
GHOrganization org = gitHub.getOrganization(organizationName); GHOrganization org = gitHub.getOrganization(organizationName);
assertNotNull(org); assertThat(org, notNullValue());
GHTeam team = org.getTeamByName(teamName); GHTeam team = org.getTeamByName(teamName);
assertNotNull(team); assertThat(team, notNullValue());
return team.hasMember(gitHub.getMyself()); return team.hasMember(gitHub.getMyself());
} }
@@ -339,10 +338,10 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHTeam teamByName = organization.getTeams().get("Core Developers"); GHTeam teamByName = organization.getTeams().get("Core Developers");
GHTeam teamById = gitHub.getTeam((int) teamByName.getId()); GHTeam teamById = gitHub.getTeam((int) teamByName.getId());
assertNotNull(teamById); assertThat(teamById, notNullValue());
assertEquals(teamByName.getId(), teamById.getId()); assertThat(teamById.getId(), equalTo(teamByName.getId()));
assertEquals(teamByName.getDescription(), teamById.getDescription()); assertThat(teamById.getDescription(), equalTo(teamByName.getDescription()));
} }
@Test @Test
@@ -351,16 +350,16 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHTeam teamByName = organization.getTeams().get("Core Developers"); GHTeam teamByName = organization.getTeams().get("Core Developers");
GHTeam teamById = organization.getTeam(teamByName.getId()); GHTeam teamById = organization.getTeam(teamByName.getId());
assertNotNull(teamById); assertThat(teamById, notNullValue());
assertEquals(teamByName.getId(), teamById.getId()); assertThat(teamById.getId(), equalTo(teamByName.getId()));
assertEquals(teamByName.getDescription(), teamById.getDescription()); assertThat(teamById.getDescription(), equalTo(teamByName.getDescription()));
GHTeam teamById2 = organization.getTeam(teamByName.getId()); GHTeam teamById2 = organization.getTeam(teamByName.getId());
assertNotNull(teamById2); assertThat(teamById2, notNullValue());
assertEquals(teamByName.getId(), teamById2.getId()); assertThat(teamById2.getId(), equalTo(teamByName.getId()));
assertEquals(teamByName.getDescription(), teamById2.getDescription()); assertThat(teamById2.getDescription(), equalTo(teamByName.getDescription()));
} }
@@ -368,7 +367,8 @@ public class AppTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testFetchPullRequest() throws Exception { public void testFetchPullRequest() throws Exception {
GHRepository r = gitHub.getOrganization("jenkinsci").getRepository("jenkins"); GHRepository r = gitHub.getOrganization("jenkinsci").getRepository("jenkins");
assertEquals("master", r.getMasterBranch()); assertThat(r.getMasterBranch(), equalTo("main"));
assertThat(r.getDefaultBranch(), equalTo("main"));
r.getPullRequest(1); r.getPullRequest(1);
r.getPullRequests(GHIssueState.OPEN); r.getPullRequests(GHIssueState.OPEN);
} }
@@ -377,11 +377,11 @@ public class AppTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testFetchPullRequestAsList() throws Exception { public void testFetchPullRequestAsList() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
assertEquals("master", r.getMasterBranch()); assertThat(r.getMasterBranch(), equalTo("main"));
PagedIterable<GHPullRequest> i = r.listPullRequests(GHIssueState.CLOSED); PagedIterable<GHPullRequest> i = r.listPullRequests(GHIssueState.CLOSED);
List<GHPullRequest> prs = i.toList(); List<GHPullRequest> prs = i.toList();
assertNotNull(prs); assertThat(prs, notNullValue());
assertTrue(prs.size() > 0); assertThat(prs, is(not(empty())));
} }
@Ignore("Needs mocking check") @Ignore("Needs mocking check")
@@ -390,26 +390,26 @@ public class AppTest extends AbstractGitHubWireMockTest {
kohsuke(); kohsuke();
GHRepository r = gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository("github-api"); GHRepository r = gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository("github-api");
assertTrue(r.hasPullAccess()); assertThat(r.hasPullAccess(), is(true));
r = gitHub.getOrganization("github").getRepository("hub"); r = gitHub.getOrganization("github").getRepository("hub");
assertFalse(r.hasAdminAccess()); assertThat(r.hasAdminAccess(), is(false));
} }
@Test @Test
public void testGetMyself() throws Exception { public void testGetMyself() throws Exception {
GHMyself me = gitHub.getMyself(); GHMyself me = gitHub.getMyself();
assertNotNull(me); assertThat(me, notNullValue());
assertNotNull(gitHub.getUser("bitwiseman")); assertThat(gitHub.getUser("bitwiseman"), notNullValue());
PagedIterable<GHRepository> ghRepositories = me.listRepositories(); PagedIterable<GHRepository> ghRepositories = me.listRepositories();
assertTrue(ghRepositories.iterator().hasNext()); assertThat(ghRepositories, is(not(emptyIterable())));
} }
@Ignore("Needs mocking check") @Ignore("Needs mocking check")
@Test @Test
public void testPublicKeys() throws Exception { public void testPublicKeys() throws Exception {
List<GHKey> keys = gitHub.getMyself().getPublicKeys(); List<GHKey> keys = gitHub.getMyself().getPublicKeys();
assertFalse(keys.isEmpty()); assertThat(keys, is(not(empty())));
} }
@Test @Test
@@ -422,8 +422,8 @@ public class AppTest extends AbstractGitHubWireMockTest {
public void testGetTeamsForRepo() throws Exception { public void testGetTeamsForRepo() throws Exception {
kohsuke(); kohsuke();
// 'Core Developers' and 'Owners' // 'Core Developers' and 'Owners'
assertEquals(2, assertThat(gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository("testGetTeamsForRepo").getTeams().size(),
gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository("testGetTeamsForRepo").getTeams().size()); equalTo(2));
} }
@Test @Test
@@ -445,24 +445,24 @@ public class AppTest extends AbstractGitHubWireMockTest {
kohsuke(); kohsuke();
int sz = 0; int sz = 0;
for (GHTeam t : gitHub.getOrganization(GITHUB_API_TEST_ORG).listTeams()) { for (GHTeam t : gitHub.getOrganization(GITHUB_API_TEST_ORG).listTeams()) {
assertNotNull(t.getName()); assertThat(t.getName(), notNullValue());
sz++; sz++;
} }
assertTrue(sz < 100); assertThat(sz, lessThan(100));
} }
@Test @Test
public void testOrgTeamByName() throws Exception { public void testOrgTeamByName() throws Exception {
kohsuke(); kohsuke();
GHTeam e = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamByName("Core Developers"); GHTeam e = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamByName("Core Developers");
assertNotNull(e); assertThat(e, notNullValue());
} }
@Test @Test
public void testOrgTeamBySlug() throws Exception { public void testOrgTeamBySlug() throws Exception {
kohsuke(); kohsuke();
GHTeam e = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug("core-developers"); GHTeam e = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug("core-developers");
assertNotNull(e); assertThat(e, notNullValue());
} }
@Test @Test
@@ -470,13 +470,13 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHCommit commit = gitHub.getUser("jenkinsci") GHCommit commit = gitHub.getUser("jenkinsci")
.getRepository("jenkins") .getRepository("jenkins")
.getCommit("08c1c9970af4d609ae754fbe803e06186e3206f7"); .getCommit("08c1c9970af4d609ae754fbe803e06186e3206f7");
assertEquals(1, commit.getParents().size()); assertThat(commit.getParents().size(), equalTo(1));
assertEquals(1, commit.getFiles().size()); assertThat(commit.getFiles().size(), equalTo(1));
assertEquals("https://github.com/jenkinsci/jenkins/commit/08c1c9970af4d609ae754fbe803e06186e3206f7", assertThat(commit.getHtmlUrl().toString(),
commit.getHtmlUrl().toString()); equalTo("https://github.com/jenkinsci/jenkins/commit/08c1c9970af4d609ae754fbe803e06186e3206f7"));
File f = commit.getFiles().get(0); File f = commit.getFiles().get(0);
assertEquals(48, f.getLinesChanged()); assertThat(f.getLinesChanged(), equalTo(48));
assertThat(f.getLinesAdded(), equalTo(40)); assertThat(f.getLinesAdded(), equalTo(40));
assertThat(f.getLinesDeleted(), equalTo(8)); assertThat(f.getLinesDeleted(), equalTo(8));
assertThat(f.getPreviousFilename(), nullValue()); assertThat(f.getPreviousFilename(), nullValue());
@@ -487,13 +487,13 @@ public class AppTest extends AbstractGitHubWireMockTest {
assertThat(f.getRawUrl().toString(), assertThat(f.getRawUrl().toString(),
equalTo("https://github.com/jenkinsci/jenkins/raw/08c1c9970af4d609ae754fbe803e06186e3206f7/changelog.html")); equalTo("https://github.com/jenkinsci/jenkins/raw/08c1c9970af4d609ae754fbe803e06186e3206f7/changelog.html"));
assertEquals("modified", f.getStatus()); assertThat(f.getStatus(), equalTo("modified"));
assertEquals("changelog.html", f.getFileName()); assertThat(f.getFileName(), equalTo("changelog.html"));
// walk the tree // walk the tree
GHTree t = commit.getTree(); GHTree t = commit.getTree();
assertThat(IOUtils.toString(t.getEntry("todo.txt").readAsBlob()), containsString("executor rendering")); assertThat(IOUtils.toString(t.getEntry("todo.txt").readAsBlob()), containsString("executor rendering"));
assertNotNull(t.getEntry("war").asTree()); assertThat(t.getEntry("war").asTree(), notNullValue());
} }
@Test @Test
@@ -502,8 +502,8 @@ public class AppTest extends AbstractGitHubWireMockTest {
for (GHCommit c : gitHub.getUser("kohsuke").getRepository("empty-commit").listCommits()) { for (GHCommit c : gitHub.getUser("kohsuke").getRepository("empty-commit").listCommits()) {
sha1.add(c.getSHA1()); sha1.add(c.getSHA1());
} }
assertEquals("fdfad6be4db6f96faea1f153fb447b479a7a9cb7", sha1.get(0)); assertThat(sha1.get(0), equalTo("fdfad6be4db6f96faea1f153fb447b479a7a9cb7"));
assertEquals(1, sha1.size()); assertThat(sha1.size(), equalTo(1));
} }
@Ignore("Needs mocking check") @Ignore("Needs mocking check")
@@ -520,7 +520,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
List<GHCommitComment> batch = comments.iterator().nextPage(); List<GHCommitComment> batch = comments.iterator().nextPage();
for (GHCommitComment comment : batch) { for (GHCommitComment comment : batch) {
// System.out.println(comment.getBody()); // System.out.println(comment.getBody());
assertSame(comment.getOwner(), r); assertThat(r, sameInstance(comment.getOwner()));
} }
} }
@@ -585,7 +585,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
// System.out.println(hook); // System.out.println(hook);
} finally { } finally {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
r = getGitHubBeforeAfter().getOrganization(GITHUB_API_TEST_ORG).getRepository("github-api"); r = getNonRecordingGitHub().getOrganization(GITHUB_API_TEST_ORG).getRepository("github-api");
for (GHHook h : r.getHooks()) { for (GHHook h : r.getHooks()) {
h.delete(); h.delete();
} }
@@ -719,7 +719,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHOrganization j = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHOrganization j = gitHub.getOrganization(GITHUB_API_TEST_ORG);
GHTeam t = j.getTeams().get("Core Developers"); GHTeam t = j.getTeams().get("Core Developers");
assertNotNull(j.getRepository("jenkins")); assertThat(j.getRepository("jenkins"), notNullValue());
// t.add(labs.getRepository("xyz")); // t.add(labs.getRepository("xyz"));
} }
@@ -736,18 +736,18 @@ public class AppTest extends AbstractGitHubWireMockTest {
List<GHCommitStatus> lst = r.listCommitStatuses("ecbfdd7315ef2cf04b2be7f11a072ce0bd00c396").toList(); List<GHCommitStatus> lst = r.listCommitStatuses("ecbfdd7315ef2cf04b2be7f11a072ce0bd00c396").toList();
state = lst.get(0); state = lst.get(0);
// System.out.println(state); // System.out.println(state);
assertEquals("testing!", state.getDescription()); assertThat(state.getDescription(), equalTo("testing!"));
assertEquals("http://kohsuke.org/", state.getTargetUrl()); assertThat(state.getTargetUrl(), equalTo("http://kohsuke.org/"));
} }
@Test @Test
public void testCommitShortInfo() throws Exception { public void testCommitShortInfo() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f23"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f23");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Kohsuke Kawaguchi"); assertThat("Kohsuke Kawaguchi", equalTo(commit.getCommitShortInfo().getAuthor().getName()));
assertEquals(commit.getCommitShortInfo().getMessage(), "doc"); assertThat("doc", equalTo(commit.getCommitShortInfo().getMessage()));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.UNSIGNED); assertThat(GHVerification.Reason.UNSIGNED, equalTo(commit.getCommitShortInfo().getVerification().getReason()));
assertThat(commit.getCommitShortInfo().getAuthor().getDate().toInstant().getEpochSecond(), assertThat(commit.getCommitShortInfo().getAuthor().getDate().toInstant().getEpochSecond(),
equalTo(1271650361L)); equalTo(1271650361L));
assertThat(commit.getCommitShortInfo().getCommitter().getDate().toInstant().getEpochSecond(), assertThat(commit.getCommitShortInfo().getCommitter().getDate().toInstant().getEpochSecond(),
@@ -760,7 +760,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHRepository r = gitHub.getUser("kohsuke").getRepository("github-api"); GHRepository r = gitHub.getUser("kohsuke").getRepository("github-api");
GHPullRequest p = r.getPullRequest(17); GHPullRequest p = r.getPullRequest(17);
GHUser u = p.getUser(); GHUser u = p.getUser();
assertNotNull(u.getName()); assertThat(u.getName(), notNullValue());
} }
@Test @Test
@@ -770,11 +770,11 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHUser kohsuke = gitHub.getUser("kohsuke"); GHUser kohsuke = gitHub.getUser("kohsuke");
GHUser b = gitHub.getUser("b"); GHUser b = gitHub.getUser("b");
assertTrue(j.hasMember(kohsuke)); assertThat(j.hasMember(kohsuke), is(true));
assertFalse(j.hasMember(b)); assertThat(j.hasMember(b), is(false));
assertTrue(j.hasPublicMember(kohsuke)); assertThat(j.hasPublicMember(kohsuke), is(true));
assertFalse(j.hasPublicMember(b)); assertThat(j.hasPublicMember(b), is(false));
} }
@Ignore("Needs mocking check") @Ignore("Needs mocking check")
@@ -797,7 +797,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
if (tagName.equals(tag.getName())) { if (tagName.equals(tag.getName())) {
String ash = tag.getCommit().getSHA1(); String ash = tag.getCommit().getSHA1();
GHRef ref = r.createRef("refs/heads/" + releaseName, ash); GHRef ref = r.createRef("refs/heads/" + releaseName, ash);
assertEquals(ref.getRef(), "refs/heads/" + releaseName); assertThat(("refs/heads/" + releaseName), equalTo(ref.getRef()));
for (Map.Entry<String, GHBranch> entry : r.getBranches().entrySet()) { for (Map.Entry<String, GHBranch> entry : r.getBranches().entrySet()) {
// System.out.println(entry.getKey() + "/" + entry.getValue()); // System.out.println(entry.getKey() + "/" + entry.getValue());
@@ -816,9 +816,9 @@ public class AppTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testRef() throws IOException { public void testRef() throws IOException {
GHRef masterRef = gitHub.getRepository("jenkinsci/jenkins").getRef("heads/master"); GHRef mainRef = gitHub.getRepository("jenkinsci/jenkins").getRef("heads/main");
assertEquals(mockGitHub.apiServer().baseUrl() + "/repos/jenkinsci/jenkins/git/refs/heads/master", assertThat(mainRef.getUrl().toString(),
masterRef.getUrl().toString()); equalTo(mockGitHub.apiServer().baseUrl() + "/repos/jenkinsci/jenkins/git/refs/heads/main"));
} }
@Test @Test
@@ -841,14 +841,14 @@ public class AppTest extends AbstractGitHubWireMockTest {
final GHDeployKey newDeployKey = myRepository.addDeployKey("test", final GHDeployKey newDeployKey = myRepository.addDeployKey("test",
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDUt0RAycC5cS42JKh6SecfFZBR1RrF+2hYMctz4mk74/arBE+wFb7fnSHGzdGKX2h5CFOWODifRCJVhB7hlVxodxe+QkQQYAEL/x1WVCJnGgTGQGOrhOMj95V3UE5pQKhsKD608C+u5tSofcWXLToP1/wZ7U4/AHjqYi08OLsWToHCax55TZkvdt2jo0hbIoYU+XI9Q8Uv4ONDN1oabiOdgeKi8+crvHAuvNleiBhWVBzFh8KdfzaH5uNdw7ihhFjEd1vzqACsjCINCjdMfzl6jD9ExuWuE92nZJnucls2cEoNC6k2aPmrZDg9hA32FXVpyseY+bDUWFU6LO2LG6PB kohsuke@atlas"); "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDUt0RAycC5cS42JKh6SecfFZBR1RrF+2hYMctz4mk74/arBE+wFb7fnSHGzdGKX2h5CFOWODifRCJVhB7hlVxodxe+QkQQYAEL/x1WVCJnGgTGQGOrhOMj95V3UE5pQKhsKD608C+u5tSofcWXLToP1/wZ7U4/AHjqYi08OLsWToHCax55TZkvdt2jo0hbIoYU+XI9Q8Uv4ONDN1oabiOdgeKi8+crvHAuvNleiBhWVBzFh8KdfzaH5uNdw7ihhFjEd1vzqACsjCINCjdMfzl6jD9ExuWuE92nZJnucls2cEoNC6k2aPmrZDg9hA32FXVpyseY+bDUWFU6LO2LG6PB kohsuke@atlas");
try { try {
assertNotNull(newDeployKey.getId()); assertThat(newDeployKey.getId(), notNullValue());
GHDeployKey k = Iterables.find(myRepository.getDeployKeys(), new Predicate<GHDeployKey>() { GHDeployKey k = Iterables.find(myRepository.getDeployKeys(), new Predicate<GHDeployKey>() {
public boolean apply(GHDeployKey deployKey) { public boolean apply(GHDeployKey deployKey) {
return newDeployKey.getId() == deployKey.getId(); return newDeployKey.getId() == deployKey.getId();
} }
}); });
assertNotNull(k); assertThat(k, notNullValue());
} finally { } finally {
newDeployKey.delete(); newDeployKey.delete();
} }
@@ -858,10 +858,10 @@ public class AppTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testCommitStatusContext() throws IOException { public void testCommitStatusContext() throws IOException {
GHRepository myRepository = getTestRepository(); GHRepository myRepository = getTestRepository();
GHRef masterRef = myRepository.getRef("heads/master"); GHRef mainRef = myRepository.getRef("heads/main");
GHCommitStatus commitStatus = myRepository.createCommitStatus(masterRef.getObject() GHCommitStatus commitStatus = myRepository.createCommitStatus(mainRef.getObject()
.getSha(), GHCommitState.SUCCESS, "http://www.example.com", "test", "test/context"); .getSha(), GHCommitState.SUCCESS, "http://www.example.com", "test", "test/context");
assertEquals("test/context", commitStatus.getContext()); assertThat(commitStatus.getContext(), equalTo("test/context"));
} }
@@ -873,7 +873,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
// System.out.println(u.getLogin()); // System.out.println(u.getLogin());
all.add(u); all.add(u);
} }
assertFalse(all.isEmpty()); assertThat(all, is(not(empty())));
} }
@Test @Test
@@ -884,10 +884,10 @@ public class AppTest extends AbstractGitHubWireMockTest {
.author("kohsuke") .author("kohsuke")
.sort(GHCommitSearchBuilder.Sort.COMMITTER_DATE) .sort(GHCommitSearchBuilder.Sort.COMMITTER_DATE)
.list(); .list();
assertTrue(r.getTotalCount() > 0); assertThat(r.getTotalCount(), greaterThan(0));
GHCommit firstCommit = r.iterator().next(); GHCommit firstCommit = r.iterator().next();
assertTrue(firstCommit.getFiles().size() > 0); assertThat(firstCommit.getFiles(), is(not(empty())));
} }
@Test @Test
@@ -897,7 +897,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
.isOpen() .isOpen()
.sort(GHIssueSearchBuilder.Sort.UPDATED) .sort(GHIssueSearchBuilder.Sort.UPDATED)
.list(); .list();
assertTrue(r.getTotalCount() > 0); assertThat(r.getTotalCount(), greaterThan(0));
for (GHIssue issue : r) { for (GHIssue issue : r) {
assertThat(issue.getTitle(), notNullValue()); assertThat(issue.getTitle(), notNullValue());
PagedIterable<GHIssueComment> comments = issue.listComments(); PagedIterable<GHIssueComment> comments = issue.listComments();
@@ -910,29 +910,29 @@ public class AppTest extends AbstractGitHubWireMockTest {
@Test // issue #99 @Test // issue #99
public void testReadme() throws IOException { public void testReadme() throws IOException {
GHContent readme = gitHub.getRepository("hub4j-test-org/test-readme").getReadme(); GHContent readme = gitHub.getRepository("hub4j-test-org/test-readme").getReadme();
assertEquals(readme.getName(), "README.md"); assertThat("README.md", equalTo(readme.getName()));
assertEquals(readme.getContent(), "This is a markdown readme.\n"); assertThat("This is a markdown readme.\n", equalTo(readme.getContent()));
} }
@Ignore("Needs mocking check") @Ignore("Needs mocking check")
@Test @Test
public void testTrees() throws IOException { public void testTrees() throws IOException {
GHTree masterTree = gitHub.getRepository("hub4j/github-api").getTree("master"); GHTree mainTree = gitHub.getRepository("hub4j/github-api").getTree("main");
boolean foundReadme = false; boolean foundReadme = false;
for (GHTreeEntry e : masterTree.getTree()) { for (GHTreeEntry e : mainTree.getTree()) {
if ("readme".equalsIgnoreCase(e.getPath().replaceAll("\\.md", ""))) { if ("readme".equalsIgnoreCase(e.getPath().replaceAll("\\.md", ""))) {
foundReadme = true; foundReadme = true;
break; break;
} }
} }
assertTrue(foundReadme); assertThat(foundReadme, is(true));
} }
@Test @Test
public void testTreesRecursive() throws IOException { public void testTreesRecursive() throws IOException {
GHTree masterTree = gitHub.getRepository("hub4j/github-api").getTreeRecursive("master", 1); GHTree mainTree = gitHub.getRepository("hub4j/github-api").getTreeRecursive("main", 1);
boolean foundThisFile = false; boolean foundThisFile = false;
for (GHTreeEntry e : masterTree.getTree()) { for (GHTreeEntry e : mainTree.getTree()) {
if (e.getPath().endsWith(AppTest.class.getSimpleName() + ".java")) { if (e.getPath().endsWith(AppTest.class.getSimpleName() + ".java")) {
foundThisFile = true; foundThisFile = true;
assertThat(e.getPath(), equalTo("src/test/java/org/kohsuke/github/AppTest.java")); assertThat(e.getPath(), equalTo("src/test/java/org/kohsuke/github/AppTest.java"));
@@ -948,7 +948,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
} }
} }
assertTrue(foundThisFile); assertThat(foundThisFile, is(true));
} }
@Test @Test
@@ -961,14 +961,14 @@ public class AppTest extends AbstractGitHubWireMockTest {
for (GHLabel l : lst) { for (GHLabel l : lst) {
assertThat(l.getUrl(), containsString(l.getName().replace(" ", "%20"))); assertThat(l.getUrl(), containsString(l.getName().replace(" ", "%20")));
} }
assertTrue(lst.size() > 5); assertThat(lst.size(), greaterThan(5));
GHLabel e = r.getLabel("enhancement"); GHLabel e = r.getLabel("enhancement");
assertEquals("enhancement", e.getName()); assertThat(e.getName(), equalTo("enhancement"));
assertNotNull(e.getUrl()); assertThat(e.getUrl(), notNullValue());
assertEquals(177339106, e.getId()); assertThat(e.getId(), equalTo(177339106L));
assertEquals("MDU6TGFiZWwxNzczMzkxMDY=", e.getNodeId()); assertThat(e.getNodeId(), equalTo("MDU6TGFiZWwxNzczMzkxMDY="));
assertTrue(e.isDefault()); assertThat(e.isDefault(), is(true));
assertTrue(Pattern.matches("[0-9a-fA-F]{6}", e.getColor())); assertThat(e.getColor(), matchesPattern("[0-9a-fA-F]{6}"));
GHLabel t = null; GHLabel t = null;
GHLabel t2 = null; GHLabel t2 = null;
@@ -979,17 +979,17 @@ public class AppTest extends AbstractGitHubWireMockTest {
assertThat(t, not(sameInstance(t2))); assertThat(t, not(sameInstance(t2)));
assertThat(t, equalTo(t2)); assertThat(t, equalTo(t2));
assertFalse(t2.isDefault()); assertThat(t2.isDefault(), is(false));
assertEquals(t.getId(), t2.getId()); assertThat(t2.getId(), equalTo(t.getId()));
assertEquals(t.getNodeId(), t2.getNodeId()); assertThat(t2.getNodeId(), equalTo(t.getNodeId()));
assertEquals(t.getName(), t2.getName()); assertThat(t2.getName(), equalTo(t.getName()));
assertEquals(t.getColor(), "123456"); assertThat("123456", equalTo(t.getColor()));
assertEquals(t.getColor(), t2.getColor()); assertThat(t2.getColor(), equalTo(t.getColor()));
assertEquals(t.getDescription(), ""); assertThat("", equalTo(t.getDescription()));
assertEquals(t.getDescription(), t2.getDescription()); assertThat(t2.getDescription(), equalTo(t.getDescription()));
assertEquals(t.getUrl(), t2.getUrl()); assertThat(t2.getUrl(), equalTo(t.getUrl()));
assertEquals(t.isDefault(), t2.isDefault()); assertThat(t2.isDefault(), equalTo(t.isDefault()));
// update works on multiple changes in one call // update works on multiple changes in one call
t3 = t.update().color("000000").description("It is dark!").done(); t3 = t.update().color("000000").description("It is dark!").done();
@@ -1001,10 +1001,10 @@ public class AppTest extends AbstractGitHubWireMockTest {
assertThat(t, not(sameInstance(t3))); assertThat(t, not(sameInstance(t3)));
assertThat(t, not(equalTo(t3))); assertThat(t, not(equalTo(t3)));
assertEquals(t.getColor(), "123456"); assertThat("123456", equalTo(t.getColor()));
assertEquals(t.getDescription(), ""); assertThat("", equalTo(t.getDescription()));
assertEquals(t3.getColor(), "000000"); assertThat("000000", equalTo(t3.getColor()));
assertEquals(t3.getDescription(), "It is dark!"); assertThat("It is dark!", equalTo(t3.getDescription()));
// Test deprecated methods // Test deprecated methods
t.setDescription("Deprecated"); t.setDescription("Deprecated");
@@ -1012,13 +1012,13 @@ public class AppTest extends AbstractGitHubWireMockTest {
// By using the old instance t when calling setDescription it also sets color to the old value // By using the old instance t when calling setDescription it also sets color to the old value
// this is a bad behavior, but it is expected // this is a bad behavior, but it is expected
assertEquals(t.getColor(), "123456"); assertThat("123456", equalTo(t.getColor()));
assertEquals(t.getDescription(), "Deprecated"); assertThat("Deprecated", equalTo(t.getDescription()));
t.setColor("000000"); t.setColor("000000");
t = r.getLabel("test"); t = r.getLabel("test");
assertEquals(t.getColor(), "000000"); assertThat("000000", equalTo(t.getColor()));
assertEquals(t.getDescription(), "Deprecated"); assertThat("Deprecated", equalTo(t.getDescription()));
// set() makes a single change // set() makes a single change
t3 = t.set().description("this is also a test"); t3 = t.set().description("this is also a test");
@@ -1027,8 +1027,8 @@ public class AppTest extends AbstractGitHubWireMockTest {
assertThat(t, not(sameInstance(t3))); assertThat(t, not(sameInstance(t3)));
assertThat(t, not(equalTo(t3))); assertThat(t, not(equalTo(t3)));
assertEquals(t3.getColor(), "000000"); assertThat("000000", equalTo(t3.getColor()));
assertEquals(t3.getDescription(), "this is also a test"); assertThat("this is also a test", equalTo(t3.getDescription()));
t.delete(); t.delete();
try { try {
@@ -1041,12 +1041,12 @@ public class AppTest extends AbstractGitHubWireMockTest {
t = r.createLabel("test2", "123457", "this is a different test"); t = r.createLabel("test2", "123457", "this is a different test");
t2 = r.getLabel("test2"); t2 = r.getLabel("test2");
assertEquals(t.getName(), t2.getName()); assertThat(t2.getName(), equalTo(t.getName()));
assertEquals(t.getColor(), "123457"); assertThat("123457", equalTo(t.getColor()));
assertEquals(t.getColor(), t2.getColor()); assertThat(t2.getColor(), equalTo(t.getColor()));
assertEquals(t.getDescription(), "this is a different test"); assertThat("this is a different test", equalTo(t.getDescription()));
assertEquals(t.getDescription(), t2.getDescription()); assertThat(t2.getDescription(), equalTo(t.getDescription()));
assertEquals(t.getUrl(), t2.getUrl()); assertThat(t2.getUrl(), equalTo(t.getUrl()));
t.delete(); t.delete();
// Allow null description // Allow null description
@@ -1063,7 +1063,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
void cleanupLabel(String name) { void cleanupLabel(String name) {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
try { try {
GHLabel t = getGitHubBeforeAfter().getRepository("hub4j-test-org/test-labels").getLabel(name); GHLabel t = getNonRecordingGitHub().getRepository("hub4j-test-org/test-labels").getLabel(name);
t.delete(); t.delete();
} catch (IOException e) { } catch (IOException e) {
@@ -1078,13 +1078,13 @@ public class AppTest extends AbstractGitHubWireMockTest {
for (GHUser u : mr.listSubscribers()) { for (GHUser u : mr.listSubscribers()) {
bitwiseman |= u.getLogin().equals("bitwiseman"); bitwiseman |= u.getLogin().equals("bitwiseman");
} }
assertTrue(bitwiseman); assertThat(bitwiseman, is(true));
boolean githubApiFound = false; boolean githubApiFound = false;
for (GHRepository r : gitHub.getUser("bitwiseman").listRepositories()) { for (GHRepository r : gitHub.getUser("bitwiseman").listRepositories()) {
githubApiFound |= r.equals(mr); githubApiFound |= r.equals(mr);
} }
assertTrue(githubApiFound); assertThat(githubApiFound, is(true));
} }
@Test @Test
@@ -1115,7 +1115,7 @@ public class AppTest extends AbstractGitHubWireMockTest {
assertThat(t.getCreatedAt(), nullValue()); assertThat(t.getCreatedAt(), nullValue());
} }
assertTrue(found); assertThat(found, is(true));
gitHub.listNotifications().markAsRead(); gitHub.listNotifications().markAsRead();
} }
@@ -1195,8 +1195,8 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHMyself me = gitHub.getMyself(); GHMyself me = gitHub.getMyself();
for (GHMembership m : me.listOrgMemberships()) { for (GHMembership m : me.listOrgMemberships()) {
assertThat(m.getUser(), is((GHUser) me)); assertThat(m.getUser(), is((GHUser) me));
assertNotNull(m.getState()); assertThat(m.getState(), notNullValue());
assertNotNull(m.getRole()); assertThat(m.getRole(), notNullValue());
} }
} }
@@ -1207,15 +1207,15 @@ public class AppTest extends AbstractGitHubWireMockTest {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
String sha1 = "a12243f2fc5b8c2ba47dd677d0b0c7583539584d"; String sha1 = "a12243f2fc5b8c2ba47dd677d0b0c7583539584d";
assertBlobContent(r.readBlob(sha1)); verifyBlobContent(r.readBlob(sha1));
GHBlob blob = r.getBlob(sha1); GHBlob blob = r.getBlob(sha1);
assertBlobContent(blob.read()); verifyBlobContent(blob.read());
assertThat(blob.getSha(), is("a12243f2fc5b8c2ba47dd677d0b0c7583539584d")); assertThat(blob.getSha(), is("a12243f2fc5b8c2ba47dd677d0b0c7583539584d"));
assertThat(blob.getSize(), is(1104L)); assertThat(blob.getSize(), is(1104L));
} }
private void assertBlobContent(InputStream is) throws Exception { private void verifyBlobContent(InputStream is) throws Exception {
String content = new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8); String content = new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8);
assertThat(content, containsString("Copyright (c) 2011- Kohsuke Kawaguchi and other contributors")); assertThat(content, containsString("Copyright (c) 2011- Kohsuke Kawaguchi and other contributors"));
assertThat(content, containsString("FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR")); assertThat(content, containsString("FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR"));

View File

@@ -1,20 +1,42 @@
package org.kohsuke.github; package org.kohsuke.github;
import com.tngtech.archunit.base.DescribedPredicate; import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaAnnotation; import com.tngtech.archunit.core.domain.*;
import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.domain.properties.HasName;
import com.tngtech.archunit.core.domain.properties.HasOwner;
import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption; import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ArchRule; import com.tngtech.archunit.lang.ArchRule;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static com.tngtech.archunit.lang.conditions.ArchConditions.beAnnotatedWith; import java.io.Closeable;
import static com.tngtech.archunit.lang.conditions.ArchConditions.not; import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.tngtech.archunit.core.domain.JavaCall.Predicates.target;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.type;
import static com.tngtech.archunit.core.domain.JavaClass.namesOf;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.name;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.nameContaining;
import static com.tngtech.archunit.core.domain.properties.HasOwner.Predicates.With.owner;
import static com.tngtech.archunit.core.domain.properties.HasParameterTypes.Predicates.rawParameterTypes;
import static com.tngtech.archunit.lang.conditions.ArchConditions.*;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.fields; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.fields;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
import static org.junit.Assert.assertTrue; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
public class ArchTests { public class ArchTests {
@@ -23,6 +45,13 @@ public class ArchTests {
.withImportOption(new ImportOption.DoNotIncludeJars()) .withImportOption(new ImportOption.DoNotIncludeJars())
.importPackages("org.kohsuke.github"); .importPackages("org.kohsuke.github");
private static final JavaClasses apacheCommons = new ClassFileImporter().importPackages("org.apache.commons.lang3");
private static final JavaClasses testClassFiles = new ClassFileImporter()
.withImportOption(new ImportOption.OnlyIncludeTests())
.withImportOption(new ImportOption.DoNotIncludeJars())
.importPackages("org.kohsuke.github");
private static final DescribedPredicate<JavaAnnotation<?>> previewAnnotationWithNoMediaType = new DescribedPredicate<JavaAnnotation<?>>( private static final DescribedPredicate<JavaAnnotation<?>> previewAnnotationWithNoMediaType = new DescribedPredicate<JavaAnnotation<?>>(
"preview has no required media types defined") { "preview has no required media types defined") {
@@ -36,7 +65,7 @@ public class ArchTests {
@BeforeClass @BeforeClass
public static void beforeClass() { public static void beforeClass() {
assertTrue(classFiles.size() > 0); assertThat(classFiles.size(), greaterThan(0));
} }
@Test @Test
@@ -105,4 +134,107 @@ public class ArchTests {
methodRule.check(classFiles); methodRule.check(classFiles);
} }
@Test
public void testRequireUseOfAssertThat() {
final String reason = "This project uses `assertThat(...)` instead of other `assert*()` methods.";
final DescribedPredicate<HasName> assertMethodOtherThanAssertThat = nameContaining("assert")
.and(DescribedPredicate.not(name("assertThat")));
final ArchRule onlyAssertThatRule = classes()
.should(not(callMethodWhere(target(assertMethodOtherThanAssertThat))))
.because(reason);
onlyAssertThatRule.check(testClassFiles);
}
@Test
public void testRequireUseOfOnlySpecificApacheCommons() {
final ArchRule onlyApprovedApacheCommonsMethods = classes()
.should(notCallMethodsInPackageUnless("org.apache.commons..",
// unless it is one of these methods
targetMethodIs(StringUtils.class, "capitalize", String.class),
targetMethodIs(StringUtils.class, "defaultString", String.class, String.class),
targetMethodIs(StringUtils.class, "equals", CharSequence.class, CharSequence.class),
targetMethodIs(StringUtils.class, "isBlank", CharSequence.class),
targetMethodIs(StringUtils.class, "isEmpty", CharSequence.class),
targetMethodIs(StringUtils.class, "join", Iterable.class, String.class),
targetMethodIs(StringUtils.class,
"prependIfMissing",
String.class,
CharSequence.class,
CharSequence[].class),
targetMethodIs(ToStringBuilder.class, "toString"),
targetMethodIs(ToStringBuilder.class, "append", String.class, Object.class),
targetMethodIs(ToStringBuilder.class, "append", String.class, long.class),
targetMethodIs(ToStringBuilder.class, "append", String.class, int.class),
targetMethodIs(ToStringBuilder.class, "isEmpty"),
targetMethodIs(ToStringBuilder.class, "equals"),
targetMethodIs(ToStringBuilder.class, "capitalize"),
targetMethodIs(ToStringStyle.class,
"append",
StringBuffer.class,
String.class,
Object.class,
Boolean.class),
targetMethodIs(ReflectionToStringBuilder.class, "accept", Field.class),
targetMethodIs(IOUtils.class, "closeQuietly", InputStream.class),
targetMethodIs(IOUtils.class, "closeQuietly", Closeable.class),
targetMethodIs(IOUtils.class, "toString", InputStream.class, Charset.class),
targetMethodIs(IOUtils.class, "toString", Reader.class),
targetMethodIs(IOUtils.class, "toByteArray", InputStream.class)))
.because(
"Commons methods must be manually verified to be compatible with commons-io:2.4 or earlier and commons-lang3:3.9 or earlier.");
onlyApprovedApacheCommonsMethods.check(classFiles);
}
public static ArchCondition<JavaClass> notCallMethodsInPackageUnless(final String packageIdentifier,
final DescribedPredicate<JavaCall<?>>... unlessPredicates) {
DescribedPredicate<JavaCall<?>> restrictedPackageCalls = target(
HasOwner.Predicates.With.<JavaClass>owner(resideInAPackage(packageIdentifier)));
if (unlessPredicates.length > 0) {
DescribedPredicate<JavaCall<?>> allowed = unlessPredicates[0];
for (int x = 1; x < unlessPredicates.length; x++) {
allowed = allowed.or(unlessPredicates[x]);
}
restrictedPackageCalls = unless(restrictedPackageCalls, allowed);
}
return not(callMethodWhere(restrictedPackageCalls));
}
public static DescribedPredicate<JavaCall<?>> targetMethodIs(Class<?> owner,
String methodName,
Class<?>... parameterTypes) {
return JavaCall.Predicates.target(owner(type(owner)))
.and(JavaCall.Predicates.target(name(methodName)))
.and(JavaCall.Predicates.target(rawParameterTypes(parameterTypes)))
.as("method is %s",
Formatters.formatMethodSimple(owner.getSimpleName(), methodName, namesOf(parameterTypes)));
}
public static <T> DescribedPredicate<T> unless(DescribedPredicate<? super T> first,
DescribedPredicate<? super T> second) {
return new UnlessPredicate(first, second);
}
private static class UnlessPredicate<T> extends DescribedPredicate<T> {
private final DescribedPredicate<T> current;
private final DescribedPredicate<? super T> other;
UnlessPredicate(DescribedPredicate<T> current, DescribedPredicate<? super T> other) {
super(current.getDescription() + " unless " + other.getDescription());
this.current = checkNotNull(current);
this.other = checkNotNull(other);
}
@Override
public boolean apply(T input) {
return current.apply(input) && !other.apply(input);
}
}
} }

View File

@@ -9,7 +9,7 @@ import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.*;
/** /**
* @author Kohsuke Kawaguchi * @author Kohsuke Kawaguchi
@@ -18,7 +18,7 @@ public class CommitTest extends AbstractGitHubWireMockTest {
@Test // issue 152 @Test // issue 152
public void lastStatus() throws IOException { public void lastStatus() throws IOException {
GHTag t = gitHub.getRepository("stapler/stapler").listTags().iterator().next(); GHTag t = gitHub.getRepository("stapler/stapler").listTags().iterator().next();
assertNotNull(t.getCommit().getLastStatus()); assertThat(t.getCommit().getLastStatus(), notNullValue());
} }
@Test // issue 230 @Test // issue 230
@@ -27,7 +27,7 @@ public class CommitTest extends AbstractGitHubWireMockTest {
PagedIterable<GHCommit> commits = repo.queryCommits().path("pom.xml").list(); PagedIterable<GHCommit> commits = repo.queryCommits().path("pom.xml").list();
for (GHCommit commit : Iterables.limit(commits, 10)) { for (GHCommit commit : Iterables.limit(commits, 10)) {
GHCommit expected = repo.getCommit(commit.getSHA1()); GHCommit expected = repo.getCommit(commit.getSHA1());
assertEquals(expected.getFiles().size(), commit.getFiles().size()); assertThat(commit.getFiles().size(), equalTo(expected.getFiles().size()));
} }
} }
@@ -83,7 +83,7 @@ public class CommitTest extends AbstractGitHubWireMockTest {
.list() .list()
.toList(); .toList();
assertThat(commits.size(), equalTo(0)); assertThat(commits, is(empty()));
commits = gitHub.getUser("jenkinsci") commits = gitHub.getUser("jenkinsci")
.getRepository("jenkins") .getRepository("jenkins")
@@ -129,7 +129,7 @@ public class CommitTest extends AbstractGitHubWireMockTest {
List<GHPullRequest> listedPrs = commit.listPullRequests().toList(); List<GHPullRequest> listedPrs = commit.listPullRequests().toList();
assertEquals(listedPrs.size(), 1); assertThat(1, equalTo(listedPrs.size()));
assertThat("Pull request " + prNumber + " not found by searching from commit.", assertThat("Pull request " + prNumber + " not found by searching from commit.",
listedPrs.stream().findFirst().filter(it -> it.getNumber() == prNumber).isPresent()); listedPrs.stream().findFirst().filter(it -> it.getNumber() == prNumber).isPresent());
@@ -144,7 +144,7 @@ public class CommitTest extends AbstractGitHubWireMockTest {
List<GHPullRequest> listedPrs = commit.listPullRequests().toList(); List<GHPullRequest> listedPrs = commit.listPullRequests().toList();
assertEquals(listedPrs.size(), 2); assertThat(2, equalTo(listedPrs.size()));
listedPrs.stream() listedPrs.stream()
.forEach(pr -> assertThat("PR#" + pr.getNumber() + " not expected to be matched.", .forEach(pr -> assertThat("PR#" + pr.getNumber() + " not expected to be matched.",
@@ -157,12 +157,12 @@ public class CommitTest extends AbstractGitHubWireMockTest {
GHCommit commit = repo.getCommit("ab92e13c0fc844fd51a379a48a3ad0b18231215c"); GHCommit commit = repo.getCommit("ab92e13c0fc844fd51a379a48a3ad0b18231215c");
assertThat("Commit which was supposed to be HEAD in the \"master\" branch was not found.", assertThat("Commit which was supposed to be HEAD in the \"main\" branch was not found.",
commit.listBranchesWhereHead() commit.listBranchesWhereHead()
.toList() .toList()
.stream() .stream()
.findFirst() .findFirst()
.filter(it -> it.getName().equals("master")) .filter(it -> it.getName().equals("main"))
.isPresent()); .isPresent());
} }
@@ -172,9 +172,9 @@ public class CommitTest extends AbstractGitHubWireMockTest {
GHCommit commit = repo.getCommit("ab92e13c0fc844fd51a379a48a3ad0b18231215c"); GHCommit commit = repo.getCommit("ab92e13c0fc844fd51a379a48a3ad0b18231215c");
assertEquals("Commit which was supposed to be HEAD in 2 branches was not found as such.", assertThat("Commit which was supposed to be HEAD in 2 branches was not found as such.",
2, commit.listBranchesWhereHead().toList().size(),
commit.listBranchesWhereHead().toList().size()); equalTo(2));
} }
@Test @Test
@@ -193,14 +193,14 @@ public class CommitTest extends AbstractGitHubWireMockTest {
PagedIterable<GHCommit> commits = repo.queryCommits().path("pom.xml").list(); PagedIterable<GHCommit> commits = repo.queryCommits().path("pom.xml").list();
for (GHCommit commit : Iterables.limit(commits, 10)) { for (GHCommit commit : Iterables.limit(commits, 10)) {
GHCommit expected = repo.getCommit(commit.getSHA1()); GHCommit expected = repo.getCommit(commit.getSHA1());
assertEquals(expected.getCommitShortInfo().getVerification().isVerified(), assertThat(commit.getCommitShortInfo().getVerification().isVerified(),
commit.getCommitShortInfo().getVerification().isVerified()); equalTo(expected.getCommitShortInfo().getVerification().isVerified()));
assertEquals(expected.getCommitShortInfo().getVerification().getReason(), assertThat(commit.getCommitShortInfo().getVerification().getReason(),
commit.getCommitShortInfo().getVerification().getReason()); equalTo(expected.getCommitShortInfo().getVerification().getReason()));
assertEquals(expected.getCommitShortInfo().getVerification().getSignature(), assertThat(commit.getCommitShortInfo().getVerification().getSignature(),
commit.getCommitShortInfo().getVerification().getSignature()); equalTo(expected.getCommitShortInfo().getVerification().getSignature()));
assertEquals(expected.getCommitShortInfo().getVerification().getPayload(), assertThat(commit.getCommitShortInfo().getVerification().getPayload(),
commit.getCommitShortInfo().getVerification().getPayload()); equalTo(expected.getCommitShortInfo().getVerification().getPayload()));
} }
} }

View File

@@ -27,7 +27,7 @@ public class EnumTest extends AbstractGitHubWireMockTest {
assertThat(GHDirection.values().length, equalTo(2)); assertThat(GHDirection.values().length, equalTo(2));
assertThat(GHEvent.values().length, equalTo(56)); assertThat(GHEvent.values().length, equalTo(58));
assertThat(GHEvent.ALL.symbol(), equalTo("*")); assertThat(GHEvent.ALL.symbol(), equalTo("*"));
assertThat(GHEvent.PULL_REQUEST.symbol(), equalTo(GHEvent.PULL_REQUEST.toString().toLowerCase())); assertThat(GHEvent.PULL_REQUEST.symbol(), equalTo(GHEvent.PULL_REQUEST.toString().toLowerCase()));

View File

@@ -5,6 +5,8 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.*;
public class GHAppInstallationTest extends AbstractGHAppInstallationTest { public class GHAppInstallationTest extends AbstractGHAppInstallationTest {
@Test @Test
@@ -13,16 +15,16 @@ public class GHAppInstallationTest extends AbstractGHAppInstallationTest {
List<GHRepository> repositories = appInstallation.listRepositories().toList(); List<GHRepository> repositories = appInstallation.listRepositories().toList();
assertEquals(2, repositories.size()); assertThat(repositories.size(), equalTo(2));
assertTrue(repositories.stream().anyMatch(it -> it.getName().equals("empty"))); assertThat(repositories.stream().map(GHRepository::getName).toArray(),
assertTrue(repositories.stream().anyMatch(it -> it.getName().equals("test-readme"))); arrayContainingInAnyOrder("empty", "test-readme"));
} }
@Test @Test
public void testListRepositoriesNoPermissions() throws IOException { public void testListRepositoriesNoPermissions() throws IOException {
GHAppInstallation appInstallation = getAppInstallationWithTokenApp2(); GHAppInstallation appInstallation = getAppInstallationWithTokenApp2();
assertTrue("App does not have permissions and should have 0 repositories", assertThat("App does not have permissions and should have 0 repositories",
appInstallation.listRepositories().toList().isEmpty()); appInstallation.listRepositories().toList().isEmpty());
} }

View File

@@ -126,7 +126,7 @@ public class GHAppTest extends AbstractGitHubWireMockTest {
assertThat(installationToken2.getRepositorySelection(), is(GHRepositorySelection.ALL)); assertThat(installationToken2.getRepositorySelection(), is(GHRepositorySelection.ALL));
assertThat(installationToken2.getExpiresAt(), is(GitHubClient.parseDate("2019-12-19T12:27:59Z"))); assertThat(installationToken2.getExpiresAt(), is(GitHubClient.parseDate("2019-12-19T12:27:59Z")));
assertNull(installationToken2.getRepositories());; assertThat(installationToken2.getRepositories(), nullValue());;
} }
private void testAppInstallation(GHAppInstallation appInstallation) throws IOException { private void testAppInstallation(GHAppInstallation appInstallation) throws IOException {
@@ -154,7 +154,7 @@ public class GHAppTest extends AbstractGitHubWireMockTest {
assertThat(appInstallation.getEvents(), containsInAnyOrder(events.toArray(new GHEvent[0]))); assertThat(appInstallation.getEvents(), containsInAnyOrder(events.toArray(new GHEvent[0])));
assertThat(appInstallation.getCreatedAt(), is(GitHubClient.parseDate("2019-07-04T01:19:36.000Z"))); assertThat(appInstallation.getCreatedAt(), is(GitHubClient.parseDate("2019-07-04T01:19:36.000Z")));
assertThat(appInstallation.getUpdatedAt(), is(GitHubClient.parseDate("2019-07-30T22:48:09.000Z"))); assertThat(appInstallation.getUpdatedAt(), is(GitHubClient.parseDate("2019-07-30T22:48:09.000Z")));
assertNull(appInstallation.getSingleFileName()); assertThat(appInstallation.getSingleFileName(), nullValue());
} }
} }

View File

@@ -6,10 +6,10 @@ import org.kohsuke.github.GHBranchProtection.EnforceAdmins;
import org.kohsuke.github.GHBranchProtection.RequiredReviews; import org.kohsuke.github.GHBranchProtection.RequiredReviews;
import org.kohsuke.github.GHBranchProtection.RequiredStatusChecks; import org.kohsuke.github.GHBranchProtection.RequiredStatusChecks;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.*;
public class GHBranchProtectionTest extends AbstractGitHubWireMockTest { public class GHBranchProtectionTest extends AbstractGitHubWireMockTest {
private static final String BRANCH = "master"; private static final String BRANCH = "main";
private static final String BRANCH_REF = "heads/" + BRANCH; private static final String BRANCH_REF = "heads/" + BRANCH;
private GHBranch branch; private GHBranch branch;
@@ -43,33 +43,33 @@ public class GHBranchProtectionTest extends AbstractGitHubWireMockTest {
private void verifyBranchProtection(GHBranchProtection protection) { private void verifyBranchProtection(GHBranchProtection protection) {
RequiredStatusChecks statusChecks = protection.getRequiredStatusChecks(); RequiredStatusChecks statusChecks = protection.getRequiredStatusChecks();
assertNotNull(statusChecks); assertThat(statusChecks, notNullValue());
assertTrue(statusChecks.isRequiresBranchUpToDate()); assertThat(statusChecks.isRequiresBranchUpToDate(), is(true));
assertTrue(statusChecks.getContexts().contains("test-status-check")); assertThat(statusChecks.getContexts(), contains("test-status-check"));
RequiredReviews requiredReviews = protection.getRequiredReviews(); RequiredReviews requiredReviews = protection.getRequiredReviews();
assertNotNull(requiredReviews); assertThat(requiredReviews, notNullValue());
assertTrue(requiredReviews.isDismissStaleReviews()); assertThat(requiredReviews.isDismissStaleReviews(), is(true));
assertTrue(requiredReviews.isRequireCodeOwnerReviews()); assertThat(requiredReviews.isRequireCodeOwnerReviews(), is(true));
assertEquals(2, requiredReviews.getRequiredReviewers()); assertThat(requiredReviews.getRequiredReviewers(), equalTo(2));
EnforceAdmins enforceAdmins = protection.getEnforceAdmins(); EnforceAdmins enforceAdmins = protection.getEnforceAdmins();
assertNotNull(enforceAdmins); assertThat(enforceAdmins, notNullValue());
assertTrue(enforceAdmins.isEnabled()); assertThat(enforceAdmins.isEnabled(), is(true));
} }
@Test @Test
public void testEnableProtectionOnly() throws Exception { public void testEnableProtectionOnly() throws Exception {
branch.enableProtection().enable(); branch.enableProtection().enable();
assertTrue(repo.getBranch(BRANCH).isProtected()); assertThat(repo.getBranch(BRANCH).isProtected(), is(true));
} }
@Test @Test
public void testDisableProtectionOnly() throws Exception { public void testDisableProtectionOnly() throws Exception {
GHBranchProtection protection = branch.enableProtection().enable(); GHBranchProtection protection = branch.enableProtection().enable();
assertTrue(repo.getBranch(BRANCH).isProtected()); assertThat(repo.getBranch(BRANCH).isProtected(), is(true));
branch.disableProtection(); branch.disableProtection();
assertFalse(repo.getBranch(BRANCH).isProtected()); assertThat(repo.getBranch(BRANCH).isProtected(), is(false));
} }
@Test @Test
@@ -77,18 +77,18 @@ public class GHBranchProtectionTest extends AbstractGitHubWireMockTest {
GHBranchProtection protection = branch.enableProtection().requireReviews().enable(); GHBranchProtection protection = branch.enableProtection().requireReviews().enable();
RequiredReviews requiredReviews = protection.getRequiredReviews(); RequiredReviews requiredReviews = protection.getRequiredReviews();
assertNotNull(protection.getRequiredReviews()); assertThat(protection.getRequiredReviews(), notNullValue());
assertFalse(requiredReviews.isDismissStaleReviews()); assertThat(requiredReviews.isDismissStaleReviews(), is(false));
assertFalse(requiredReviews.isRequireCodeOwnerReviews()); assertThat(requiredReviews.isRequireCodeOwnerReviews(), is(false));
assertThat(protection.getRequiredReviews().getRequiredReviewers(), equalTo(1)); assertThat(protection.getRequiredReviews().getRequiredReviewers(), equalTo(1));
// Get goes through a different code path. Make sure it also gets the correct data. // Get goes through a different code path. Make sure it also gets the correct data.
protection = branch.getProtection(); protection = branch.getProtection();
requiredReviews = protection.getRequiredReviews(); requiredReviews = protection.getRequiredReviews();
assertNotNull(protection.getRequiredReviews()); assertThat(protection.getRequiredReviews(), notNullValue());
assertFalse(requiredReviews.isDismissStaleReviews()); assertThat(requiredReviews.isDismissStaleReviews(), is(false));
assertFalse(requiredReviews.isRequireCodeOwnerReviews()); assertThat(requiredReviews.isRequireCodeOwnerReviews(), is(false));
assertThat(protection.getRequiredReviews().getRequiredReviewers(), equalTo(1)); assertThat(protection.getRequiredReviews().getRequiredReviewers(), equalTo(1));
} }
@@ -96,20 +96,21 @@ public class GHBranchProtectionTest extends AbstractGitHubWireMockTest {
public void testSignedCommits() throws Exception { public void testSignedCommits() throws Exception {
GHBranchProtection protection = branch.enableProtection().enable(); GHBranchProtection protection = branch.enableProtection().enable();
assertFalse(protection.getRequiredSignatures()); assertThat(protection.getRequiredSignatures(), is(false));
protection.enabledSignedCommits(); protection.enabledSignedCommits();
assertTrue(protection.getRequiredSignatures()); assertThat(protection.getRequiredSignatures(), is(true));
protection.disableSignedCommits(); protection.disableSignedCommits();
assertFalse(protection.getRequiredSignatures()); assertThat(protection.getRequiredSignatures(), is(false));
} }
@Test @Test
public void testGetProtection() throws Exception { public void testGetProtection() throws Exception {
GHBranchProtection protection = branch.enableProtection().enable(); GHBranchProtection protection = branch.enableProtection().enable();
GHBranchProtection protectionTest = repo.getBranch(BRANCH).getProtection(); GHBranchProtection protectionTest = repo.getBranch(BRANCH).getProtection();
assertTrue(protectionTest instanceof GHBranchProtection); Boolean condition = protectionTest instanceof GHBranchProtection;
assertTrue(repo.getBranch(BRANCH).isProtected()); assertThat(protectionTest, instanceOf(GHBranchProtection.class));
assertThat(repo.getBranch(BRANCH).isProtected(), is(true));
} }
} }

View File

@@ -16,9 +16,9 @@ public class GHBranchTest extends AbstractGitHubWireMockTest {
public void testMergeBranch() throws Exception { public void testMergeBranch() throws Exception {
repository = getTempRepository(); repository = getTempRepository();
String masterHead = repository.getRef("heads/master").getObject().getSha(); String mainHead = repository.getRef("heads/main").getObject().getSha();
createRefAndPostContent(BRANCH_1, masterHead); createRefAndPostContent(BRANCH_1, mainHead);
createRefAndPostContent(BRANCH_2, masterHead); createRefAndPostContent(BRANCH_2, mainHead);
GHBranch otherBranch = repository.getBranch(BRANCH_2); GHBranch otherBranch = repository.getBranch(BRANCH_2);
String commitMessage = "merging " + BRANCH_2; String commitMessage = "merging " + BRANCH_2;
@@ -28,13 +28,13 @@ public class GHBranchTest extends AbstractGitHubWireMockTest {
// Merging commit sha should work // Merging commit sha should work
commitMessage = "merging from " + mergeCommit.getSHA1(); commitMessage = "merging from " + mergeCommit.getSHA1();
GHBranch master = repository.getBranch("master"); GHBranch main = repository.getBranch("main");
mergeCommit = master.merge(mergeCommit.getSHA1(), commitMessage); mergeCommit = main.merge(mergeCommit.getSHA1(), commitMessage);
assertThat(mergeCommit, notNullValue()); assertThat(mergeCommit, notNullValue());
assertThat(mergeCommit.getCommitShortInfo().getMessage(), equalTo(commitMessage)); assertThat(mergeCommit.getCommitShortInfo().getMessage(), equalTo(commitMessage));
mergeCommit = master.merge(mergeCommit.getSHA1(), commitMessage); mergeCommit = main.merge(mergeCommit.getSHA1(), commitMessage);
// Should be null since all changes already merged // Should be null since all changes already merged
assertThat(mergeCommit, nullValue()); assertThat(mergeCommit, nullValue());
} }

View File

@@ -30,8 +30,7 @@ import org.kohsuke.github.GHCheckRun.Status;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.equalTo;
@SuppressWarnings("deprecation") // preview @SuppressWarnings("deprecation") // preview
public class GHCheckRunBuilderTest extends AbstractGHAppInstallationTest { public class GHCheckRunBuilderTest extends AbstractGHAppInstallationTest {
@@ -60,10 +59,10 @@ public class GHCheckRunBuilderTest extends AbstractGHAppInstallationTest {
.withCaption("Princess Unikitty"))) .withCaption("Princess Unikitty")))
.add(new GHCheckRunBuilder.Action("Help", "what I need help with", "doit")) .add(new GHCheckRunBuilder.Action("Help", "what I need help with", "doit"))
.create(); .create();
assertEquals(Status.COMPLETED, checkRun.getStatus()); assertThat(checkRun.getStatus(), equalTo(Status.COMPLETED));
assertEquals(1, checkRun.getOutput().getAnnotationsCount()); assertThat(checkRun.getOutput().getAnnotationsCount(), equalTo(1));
assertEquals(1424883286, checkRun.getId()); assertThat(checkRun.getId(), equalTo(1424883286L));
assertEquals("Hello Text!", checkRun.getOutput().getText()); assertThat(checkRun.getOutput().getText(), equalTo("Hello Text!"));
} }
@Test @Test
@@ -80,12 +79,12 @@ public class GHCheckRunBuilderTest extends AbstractGHAppInstallationTest {
.withConclusion(GHCheckRun.Conclusion.SUCCESS) .withConclusion(GHCheckRun.Conclusion.SUCCESS)
.add(output) .add(output)
.create(); .create();
assertEquals(Status.COMPLETED, checkRun.getStatus()); assertThat(checkRun.getStatus(), equalTo(Status.COMPLETED));
assertEquals("Big Run", checkRun.getOutput().getTitle()); assertThat(checkRun.getOutput().getTitle(), equalTo("Big Run"));
assertEquals("Lots of stuff here »", checkRun.getOutput().getSummary()); assertThat(checkRun.getOutput().getSummary(), equalTo("Lots of stuff here »"));
assertEquals(101, checkRun.getOutput().getAnnotationsCount()); assertThat(checkRun.getOutput().getAnnotationsCount(), equalTo(101));
assertEquals("Hello Text!", checkRun.getOutput().getText()); assertThat(checkRun.getOutput().getText(), equalTo("Hello Text!"));
assertEquals(1424883599, checkRun.getId()); assertThat(checkRun.getId(), equalTo(1424883599L));
} }
@Test @Test
@@ -95,9 +94,9 @@ public class GHCheckRunBuilderTest extends AbstractGHAppInstallationTest {
.withConclusion(GHCheckRun.Conclusion.NEUTRAL) .withConclusion(GHCheckRun.Conclusion.NEUTRAL)
.add(new GHCheckRunBuilder.Output("Quick note", "nothing more to see here")) .add(new GHCheckRunBuilder.Output("Quick note", "nothing more to see here"))
.create(); .create();
assertEquals(Status.COMPLETED, checkRun.getStatus()); assertThat(checkRun.getStatus(), equalTo(Status.COMPLETED));
assertEquals(0, checkRun.getOutput().getAnnotationsCount()); assertThat(checkRun.getOutput().getAnnotationsCount(), equalTo(0));
assertEquals(1424883957, checkRun.getId()); assertThat(checkRun.getId(), equalTo(1424883957L));
} }
@Test @Test
@@ -106,9 +105,9 @@ public class GHCheckRunBuilderTest extends AbstractGHAppInstallationTest {
.createCheckRun("outstanding", "89a9ae301e35e667756034fdc933b1fc94f63fc1") .createCheckRun("outstanding", "89a9ae301e35e667756034fdc933b1fc94f63fc1")
.withStatus(GHCheckRun.Status.IN_PROGRESS) .withStatus(GHCheckRun.Status.IN_PROGRESS)
.create(); .create();
assertEquals(Status.IN_PROGRESS, checkRun.getStatus()); assertThat(checkRun.getStatus(), equalTo(Status.IN_PROGRESS));
assertNull(checkRun.getConclusion()); assertThat(checkRun.getConclusion(), nullValue());
assertEquals(1424883451, checkRun.getId()); assertThat(checkRun.getId(), equalTo(1424883451L));
} }
@Test @Test
@@ -120,7 +119,7 @@ public class GHCheckRunBuilderTest extends AbstractGHAppInstallationTest {
.create(); .create();
fail("should have been rejected"); fail("should have been rejected");
} catch (HttpException x) { } catch (HttpException x) {
assertEquals(422, x.getResponseCode()); assertThat(x.getResponseCode(), equalTo(422));
assertThat(x.getMessage(), containsString("\\\"conclusion\\\" wasn't supplied")); assertThat(x.getMessage(), containsString("\\\"conclusion\\\" wasn't supplied"));
assertThat(x.getUrl(), containsString("/repos/hub4j-test-org/test-checks/check-runs")); assertThat(x.getUrl(), containsString("/repos/hub4j-test-org/test-checks/check-runs"));
assertThat(x.getResponseMessage(), equalTo("422 Unprocessable Entity")); assertThat(x.getResponseMessage(), equalTo("422 Unprocessable Entity"));
@@ -144,9 +143,9 @@ public class GHCheckRunBuilderTest extends AbstractGHAppInstallationTest {
.withConclusion(GHCheckRun.Conclusion.SUCCESS) .withConclusion(GHCheckRun.Conclusion.SUCCESS)
.withCompletedAt(new Date(999_999_999)) .withCompletedAt(new Date(999_999_999))
.create(); .create();
assertEquals(updated.getStartedAt(), new Date(999_999_000)); assertThat(new Date(999_999_000), equalTo(updated.getStartedAt()));
assertEquals(updated.getName(), "foo"); assertThat("foo", equalTo(updated.getName()));
assertEquals(1, checkRun.getOutput().getAnnotationsCount()); assertThat(checkRun.getOutput().getAnnotationsCount(), equalTo(1));
} }
} }

View File

@@ -11,8 +11,7 @@ import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.hasProperty;
/** /**
* Integration test for {@link GHContent}. * Integration test for {@link GHContent}.
@@ -29,7 +28,7 @@ public class GHContentIntegrationTest extends AbstractGitHubWireMockTest {
@After @After
public void cleanup() throws Exception { public void cleanup() throws Exception {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
repo = getGitHubBeforeAfter().getRepository("hub4j-test-org/GHContentIntegrationTest"); repo = getNonRecordingGitHub().getRepository("hub4j-test-org/GHContentIntegrationTest");
try { try {
GHContent content = repo.getFileContent(createdFilename); GHContent content = repo.getFileContent(createdFilename);
if (content != null) { if (content != null) {
@@ -58,31 +57,31 @@ public class GHContentIntegrationTest extends AbstractGitHubWireMockTest {
repo = gitHub.getRepository("hub4j-test-org/GHContentIntegrationTest"); repo = gitHub.getRepository("hub4j-test-org/GHContentIntegrationTest");
GHContent content = repo.getFileContent("ghcontent-ro/a-file-with-content"); GHContent content = repo.getFileContent("ghcontent-ro/a-file-with-content");
assertTrue(content.isFile()); assertThat(content.isFile(), is(true));
assertEquals("thanks for reading me\n", content.getContent()); assertThat(content.getContent(), equalTo("thanks for reading me\n"));
} }
@Test @Test
public void testGetEmptyFileContent() throws Exception { public void testGetEmptyFileContent() throws Exception {
GHContent content = repo.getFileContent("ghcontent-ro/an-empty-file"); GHContent content = repo.getFileContent("ghcontent-ro/an-empty-file");
assertTrue(content.isFile()); assertThat(content.isFile(), is(true));
assertEquals("", content.getContent()); assertThat(content.getContent(), is(emptyString()));
} }
@Test @Test
public void testGetDirectoryContent() throws Exception { public void testGetDirectoryContent() throws Exception {
List<GHContent> entries = repo.getDirectoryContent("ghcontent-ro/a-dir-with-3-entries"); List<GHContent> entries = repo.getDirectoryContent("ghcontent-ro/a-dir-with-3-entries");
assertTrue(entries.size() == 3); assertThat(entries.size(), equalTo(3));
} }
@Test @Test
public void testGetDirectoryContentTrailingSlash() throws Exception { public void testGetDirectoryContentTrailingSlash() throws Exception {
// Used to truncate the ?ref=master, see gh-224 https://github.com/kohsuke/github-api/pull/224 // Used to truncate the ?ref=main, see gh-224 https://github.com/kohsuke/github-api/pull/224
List<GHContent> entries = repo.getDirectoryContent("ghcontent-ro/a-dir-with-3-entries/", "master"); List<GHContent> entries = repo.getDirectoryContent("ghcontent-ro/a-dir-with-3-entries/", "main");
assertTrue(entries.get(0).getUrl().endsWith("?ref=master")); assertThat(entries.get(0).getUrl(), endsWith("?ref=main"));
} }
@Test @Test
@@ -92,11 +91,11 @@ public class GHContentIntegrationTest extends AbstractGitHubWireMockTest {
createdFilename); createdFilename);
GHContent createdContent = created.getContent(); GHContent createdContent = created.getContent();
assertNotNull(created.getCommit()); assertThat(created.getCommit(), notNullValue());
assertNotNull(created.getContent()); assertThat(created.getContent(), notNullValue());
assertNotNull(createdContent.getContent()); assertThat(createdContent.getContent(), notNullValue());
assertThat(createdContent.getPath(), equalTo(createdFilename)); assertThat(createdContent.getPath(), equalTo(createdFilename));
assertEquals("this is an awesome file I created\n", createdContent.getContent()); assertThat(createdContent.getContent(), equalTo("this is an awesome file I created\n"));
GHContent content = repo.getFileContent(createdFilename); GHContent content = repo.getFileContent(createdFilename);
assertThat(content, is(notNullValue())); assertThat(content, is(notNullValue()));
@@ -116,17 +115,17 @@ public class GHContentIntegrationTest extends AbstractGitHubWireMockTest {
"Updated file for integration tests."); "Updated file for integration tests.");
GHContent updatedContent = updatedContentResponse.getContent(); GHContent updatedContent = updatedContentResponse.getContent();
assertNotNull(updatedContentResponse.getCommit()); assertThat(updatedContentResponse.getCommit(), notNullValue());
assertNotNull(updatedContentResponse.getContent()); assertThat(updatedContentResponse.getContent(), notNullValue());
// due to what appears to be a cache propagation delay, this test is too flaky // due to what appears to be a cache propagation delay, this test is too flaky
assertEquals("this is some new content", assertThat(new BufferedReader(new InputStreamReader(updatedContent.read())).readLine(),
new BufferedReader(new InputStreamReader(updatedContent.read())).readLine()); equalTo("this is some new content"));
assertEquals("this is some new content\n", updatedContent.getContent()); assertThat(updatedContent.getContent(), equalTo("this is some new content\n"));
GHContentUpdateResponse deleteResponse = updatedContent.delete("Enough of this foolishness!"); GHContentUpdateResponse deleteResponse = updatedContent.delete("Enough of this foolishness!");
assertNotNull(deleteResponse.getCommit()); assertThat(deleteResponse.getCommit(), notNullValue());
assertNull(deleteResponse.getContent()); assertThat(deleteResponse.getContent(), nullValue());
try { try {
repo.getFileContent(createdFilename); repo.getFileContent(createdFilename);

View File

@@ -6,6 +6,8 @@ import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map; import java.util.Map;
import static org.hamcrest.Matchers.*;
/** /**
* @author Martin van Zijl * @author Martin van Zijl
*/ */
@@ -15,38 +17,38 @@ public class GHDeploymentTest extends AbstractGitHubWireMockTest {
public void testGetDeploymentByIdStringPayload() throws IOException { public void testGetDeploymentByIdStringPayload() throws IOException {
final GHRepository repo = getRepository(); final GHRepository repo = getRepository();
final GHDeployment deployment = repo.getDeployment(178653229); final GHDeployment deployment = repo.getDeployment(178653229);
assertNotNull(deployment); assertThat(deployment, notNullValue());
assertEquals(178653229, deployment.getId()); assertThat(deployment.getId(), equalTo(178653229L));
assertEquals("production", deployment.getEnvironment()); assertThat(deployment.getEnvironment(), equalTo("production"));
assertEquals("custom", deployment.getPayload()); assertThat(deployment.getPayload(), equalTo("custom"));
assertEquals("custom", deployment.getPayloadObject()); assertThat(deployment.getPayloadObject(), equalTo("custom"));
assertEquals("master", deployment.getRef()); assertThat(deployment.getRef(), equalTo("main"));
assertEquals("3a09d2de4a9a1322a0ba2c3e2f54a919ca8fe353", deployment.getSha()); assertThat(deployment.getSha(), equalTo("3a09d2de4a9a1322a0ba2c3e2f54a919ca8fe353"));
assertEquals("deploy", deployment.getTask()); assertThat(deployment.getTask(), equalTo("deploy"));
assertEquals("production", deployment.getOriginalEnvironment()); assertThat(deployment.getOriginalEnvironment(), equalTo("production"));
assertEquals(false, deployment.isProductionEnvironment()); assertThat(deployment.isProductionEnvironment(), equalTo(false));
assertEquals(true, deployment.isTransientEnvironment()); assertThat(deployment.isTransientEnvironment(), equalTo(true));
} }
@Test @Test
public void testGetDeploymentByIdObjectPayload() throws IOException { public void testGetDeploymentByIdObjectPayload() throws IOException {
final GHRepository repo = getRepository(); final GHRepository repo = getRepository();
final GHDeployment deployment = repo.getDeployment(178653229); final GHDeployment deployment = repo.getDeployment(178653229);
assertNotNull(deployment); assertThat(deployment, notNullValue());
assertEquals(178653229, deployment.getId()); assertThat(deployment.getId(), equalTo(178653229L));
assertEquals("production", deployment.getEnvironment()); assertThat(deployment.getEnvironment(), equalTo("production"));
assertEquals("master", deployment.getRef()); assertThat(deployment.getRef(), equalTo("main"));
assertEquals("3a09d2de4a9a1322a0ba2c3e2f54a919ca8fe353", deployment.getSha()); assertThat(deployment.getSha(), equalTo("3a09d2de4a9a1322a0ba2c3e2f54a919ca8fe353"));
assertEquals("deploy", deployment.getTask()); assertThat(deployment.getTask(), equalTo("deploy"));
final Map<String, Object> payload = deployment.getPayloadMap(); final Map<String, Object> payload = deployment.getPayloadMap();
assertEquals(4, payload.size()); assertThat(payload.size(), equalTo(4));
assertEquals(1, payload.get("custom1")); assertThat(payload.get("custom1"), equalTo(1));
assertEquals("two", payload.get("custom2")); assertThat(payload.get("custom2"), equalTo("two"));
assertEquals(Arrays.asList("3", 3, "three"), payload.get("custom3")); assertThat(payload.get("custom3"), equalTo(Arrays.asList("3", 3, "three")));
assertNull(payload.get("custom4")); assertThat(payload.get("custom4"), nullValue());
assertEquals("production", deployment.getOriginalEnvironment()); assertThat(deployment.getOriginalEnvironment(), equalTo("production"));
assertEquals(false, deployment.isProductionEnvironment()); assertThat(deployment.isProductionEnvironment(), equalTo(false));
assertEquals(true, deployment.isTransientEnvironment()); assertThat(deployment.isTransientEnvironment(), equalTo(true));
} }
protected GHRepository getRepository() throws IOException { protected GHRepository getRepository() throws IOException {

View File

@@ -26,7 +26,7 @@ public class GHDiscussionTest extends AbstractGitHubWireMockTest {
public void cleanupDiscussions() throws Exception { public void cleanupDiscussions() throws Exception {
// only need to clean up if we're pointing to the live site // only need to clean up if we're pointing to the live site
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
for (GHDiscussion discussion : getGitHubBeforeAfter().getOrganization(GITHUB_API_TEST_ORG) for (GHDiscussion discussion : getNonRecordingGitHub().getOrganization(GITHUB_API_TEST_ORG)
.getTeamBySlug(TEAM_SLUG) .getTeamBySlug(TEAM_SLUG)
.listDiscussions()) { .listDiscussions()) {
discussion.delete(); discussion.delete();

View File

@@ -11,7 +11,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import static java.lang.Boolean.TRUE;
import static org.hamcrest.Matchers.aMapWithSize; import static org.hamcrest.Matchers.aMapWithSize;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.endsWith;
@@ -50,7 +49,7 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
.parseEventPayload(payload.asReader(), GHEventPayload.Create.class); .parseEventPayload(payload.asReader(), GHEventPayload.Create.class);
assertThat(event.getRef(), is("0.0.1")); assertThat(event.getRef(), is("0.0.1"));
assertThat(event.getRefType(), is("tag")); assertThat(event.getRefType(), is("tag"));
assertThat(event.getMasterBranch(), is("master")); assertThat(event.getMasterBranch(), is("main"));
assertThat(event.getDescription(), is("")); assertThat(event.getDescription(), is(""));
assertThat(event.getRepository().getName(), is("public-repo")); assertThat(event.getRepository().getName(), is("public-repo"));
assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker")); assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker"));
@@ -241,15 +240,15 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
assertThat(event.getPullRequest().getNumber(), is(1)); assertThat(event.getPullRequest().getNumber(), is(1));
assertThat(event.getPullRequest().getTitle(), is("Update the README with new information")); assertThat(event.getPullRequest().getTitle(), is("Update the README with new information"));
assertThat(event.getPullRequest().getBody(), assertThat(event.getPullRequest().getBody(),
is("This is a pretty simple change that we need to pull into " + "master.")); is("This is a pretty simple change that we need to pull into " + "main."));
assertThat(event.getPullRequest().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getUser().getLogin(), is("baxterthehacker"));
assertThat(event.getPullRequest().getHead().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getHead().getUser().getLogin(), is("baxterthehacker"));
assertThat(event.getPullRequest().getHead().getRef(), is("changes")); assertThat(event.getPullRequest().getHead().getRef(), is("changes"));
assertThat(event.getPullRequest().getHead().getLabel(), is("baxterthehacker:changes")); assertThat(event.getPullRequest().getHead().getLabel(), is("baxterthehacker:changes"));
assertThat(event.getPullRequest().getHead().getSha(), is("0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c")); assertThat(event.getPullRequest().getHead().getSha(), is("0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c"));
assertThat(event.getPullRequest().getBase().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getBase().getUser().getLogin(), is("baxterthehacker"));
assertThat(event.getPullRequest().getBase().getRef(), is("master")); assertThat(event.getPullRequest().getBase().getRef(), is("main"));
assertThat(event.getPullRequest().getBase().getLabel(), is("baxterthehacker:master")); assertThat(event.getPullRequest().getBase().getLabel(), is("baxterthehacker:main"));
assertThat(event.getPullRequest().getBase().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); assertThat(event.getPullRequest().getBase().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b"));
assertThat(event.getPullRequest().isMerged(), is(false)); assertThat(event.getPullRequest().isMerged(), is(false));
assertThat(event.getPullRequest().getMergeable(), nullValue()); assertThat(event.getPullRequest().getMergeable(), nullValue());
@@ -314,7 +313,7 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
assertThat(event.getPullRequest().getBase().getLabel(), is("trilogy-group:3.10")); assertThat(event.getPullRequest().getBase().getLabel(), is("trilogy-group:3.10"));
assertThat(event.getPullRequest().getBase().getSha(), is("7a735f17d686c6a1fc7df5b9d395e5863868f364")); assertThat(event.getPullRequest().getBase().getSha(), is("7a735f17d686c6a1fc7df5b9d395e5863868f364"));
assertThat(event.getPullRequest().isMerged(), is(false)); assertThat(event.getPullRequest().isMerged(), is(false));
assertThat(event.getPullRequest().getMergeable(), is(TRUE)); assertThat(event.getPullRequest().getMergeable(), is(true));
assertThat(event.getPullRequest().getMergeableState(), is("draft")); assertThat(event.getPullRequest().getMergeableState(), is("draft"));
assertThat(event.getPullRequest().getMergedBy(), nullValue()); assertThat(event.getPullRequest().getMergedBy(), nullValue());
assertThat(event.getPullRequest().getCommentsCount(), is(1)); assertThat(event.getPullRequest().getCommentsCount(), is(1));
@@ -355,8 +354,8 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
assertThat(event.getPullRequest().getHead().getLabel(), is("skalnik:patch-2")); assertThat(event.getPullRequest().getHead().getLabel(), is("skalnik:patch-2"));
assertThat(event.getPullRequest().getHead().getSha(), is("b7a1f9c27caa4e03c14a88feb56e2d4f7500aa63")); assertThat(event.getPullRequest().getHead().getSha(), is("b7a1f9c27caa4e03c14a88feb56e2d4f7500aa63"));
assertThat(event.getPullRequest().getBase().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getBase().getUser().getLogin(), is("baxterthehacker"));
assertThat(event.getPullRequest().getBase().getRef(), is("master")); assertThat(event.getPullRequest().getBase().getRef(), is("main"));
assertThat(event.getPullRequest().getBase().getLabel(), is("baxterthehacker:master")); assertThat(event.getPullRequest().getBase().getLabel(), is("baxterthehacker:main"));
assertThat(event.getPullRequest().getBase().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); assertThat(event.getPullRequest().getBase().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b"));
assertThat(event.getRepository().getName(), is("public-repo")); assertThat(event.getRepository().getName(), is("public-repo"));
@@ -376,15 +375,15 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
assertThat(event.getPullRequest().getNumber(), is(1)); assertThat(event.getPullRequest().getNumber(), is(1));
assertThat(event.getPullRequest().getTitle(), is("Update the README with new information")); assertThat(event.getPullRequest().getTitle(), is("Update the README with new information"));
assertThat(event.getPullRequest().getBody(), assertThat(event.getPullRequest().getBody(),
is("This is a pretty simple change that we need to pull into master.")); is("This is a pretty simple change that we need to pull into main."));
assertThat(event.getPullRequest().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getUser().getLogin(), is("baxterthehacker"));
assertThat(event.getPullRequest().getHead().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getHead().getUser().getLogin(), is("baxterthehacker"));
assertThat(event.getPullRequest().getHead().getRef(), is("changes")); assertThat(event.getPullRequest().getHead().getRef(), is("changes"));
assertThat(event.getPullRequest().getHead().getLabel(), is("baxterthehacker:changes")); assertThat(event.getPullRequest().getHead().getLabel(), is("baxterthehacker:changes"));
assertThat(event.getPullRequest().getHead().getSha(), is("0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c")); assertThat(event.getPullRequest().getHead().getSha(), is("0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c"));
assertThat(event.getPullRequest().getBase().getUser().getLogin(), is("baxterthehacker")); assertThat(event.getPullRequest().getBase().getUser().getLogin(), is("baxterthehacker"));
assertThat(event.getPullRequest().getBase().getRef(), is("master")); assertThat(event.getPullRequest().getBase().getRef(), is("main"));
assertThat(event.getPullRequest().getBase().getLabel(), is("baxterthehacker:master")); assertThat(event.getPullRequest().getBase().getLabel(), is("baxterthehacker:main"));
assertThat(event.getPullRequest().getBase().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); assertThat(event.getPullRequest().getBase().getSha(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b"));
assertThat(event.getRepository().getName(), is("public-repo")); assertThat(event.getRepository().getName(), is("public-repo"));
@@ -477,8 +476,8 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
assertThat(event.getRepository().getHttpTransportUrl(), is("https://github.com/hub4j-test-org/github-api.git")); assertThat(event.getRepository().getHttpTransportUrl(), is("https://github.com/hub4j-test-org/github-api.git"));
// ensure that root has been bound after populate // ensure that root has been bound after populate
event.getRepository().getSource().getRef("heads/master"); event.getRepository().getSource().getRef("heads/main");
event.getRepository().getParent().getRef("heads/master"); event.getRepository().getParent().getRef("heads/main");
// Source // Source
event = gitHub.parseEventPayload(payload.asReader(mockGitHub::mapToMockGitHub), GHEventPayload.Push.class); event = gitHub.parseEventPayload(payload.asReader(mockGitHub::mapToMockGitHub), GHEventPayload.Push.class);
@@ -525,7 +524,7 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
assertThat(event.getState(), is(GHCommitState.SUCCESS)); assertThat(event.getState(), is(GHCommitState.SUCCESS));
assertThat(event.getCommit().getSHA1(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b")); assertThat(event.getCommit().getSHA1(), is("9049f1265b7d61be4a8904a9a27120d2064dab3b"));
assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker")); assertThat(event.getRepository().getOwner().getLogin(), is("baxterthehacker"));
assertNull(event.getTargetUrl()); assertThat(event.getTargetUrl(), nullValue());
} }
@Test @Test
@@ -559,7 +558,7 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
int expectedRequestCount = mockGitHub.isUseProxy() ? 3 : 2; int expectedRequestCount = mockGitHub.isUseProxy() ? 3 : 2;
assertThat("pull body should be populated", assertThat("pull body should be populated",
checkRun.getPullRequests().get(0).getBody(), checkRun.getPullRequests().get(0).getBody(),
equalTo("This is a pretty simple change that we need to pull into master.")); equalTo("This is a pretty simple change that we need to pull into main."));
assertThat("multiple getPullRequests() calls are made, the pull is populated only once", assertThat("multiple getPullRequests() calls are made, the pull is populated only once",
mockGitHub.getRequestCount(), mockGitHub.getRequestCount(),
equalTo(expectedRequestCount)); equalTo(expectedRequestCount));
@@ -624,7 +623,7 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
int expectedRequestCount = mockGitHub.isUseProxy() ? 3 : 2; int expectedRequestCount = mockGitHub.isUseProxy() ? 3 : 2;
assertThat("pull body should be populated", assertThat("pull body should be populated",
checkSuite.getPullRequests().get(0).getBody(), checkSuite.getPullRequests().get(0).getBody(),
equalTo("This is a pretty simple change that we need to pull into master.")); equalTo("This is a pretty simple change that we need to pull into main."));
assertThat("multiple getPullRequests() calls are made, the pull is populated only once", assertThat("multiple getPullRequests() calls are made, the pull is populated only once",
mockGitHub.getRequestCount(), mockGitHub.getRequestCount(),
lessThanOrEqualTo(expectedRequestCount)); lessThanOrEqualTo(expectedRequestCount));
@@ -805,4 +804,55 @@ public class GHEventPayloadTest extends AbstractGitHubWireMockTest {
assertThat(workflowRun.getHeadRepository().getFullName(), assertThat(workflowRun.getHeadRepository().getFullName(),
is("gsmet-bot-playground/quarkus-bot-java-playground")); is("gsmet-bot-playground/quarkus-bot-java-playground"));
} }
@Test
public void label_created() throws Exception {
GHEventPayload.Label labelPayload = GitHub.offline()
.parseEventPayload(payload.asReader(), GHEventPayload.Label.class);
GHLabel label = labelPayload.getLabel();
assertThat(labelPayload.getAction(), is("created"));
assertThat(labelPayload.getRepository().getFullName(), is("gsmet/quarkus-bot-java-playground"));
assertThat(label.getId(), is(2901546662L));
assertThat(label.getNodeId(), is("MDU6TGFiZWwyOTAxNTQ2NjYy"));
assertThat(label.getName(), is("new-label"));
assertThat(label.getColor(), is("f9d0c4"));
assertThat(label.isDefault(), is(false));
assertThat(label.getDescription(), is("description"));
}
@Test
public void label_edited() throws Exception {
GHEventPayload.Label labelPayload = GitHub.offline()
.parseEventPayload(payload.asReader(), GHEventPayload.Label.class);
GHLabel label = labelPayload.getLabel();
assertThat(labelPayload.getAction(), is("edited"));
assertThat(labelPayload.getRepository().getFullName(), is("gsmet/quarkus-bot-java-playground"));
assertThat(label.getId(), is(2901546662L));
assertThat(label.getNodeId(), is("MDU6TGFiZWwyOTAxNTQ2NjYy"));
assertThat(label.getName(), is("new-label-updated"));
assertThat(label.getColor(), is("4AE686"));
assertThat(label.isDefault(), is(false));
assertThat(label.getDescription(), is("description"));
assertThat(labelPayload.getChanges().getName().getFrom(), is("new-label"));
assertThat(labelPayload.getChanges().getColor().getFrom(), is("f9d0c4"));
}
@Test
public void label_deleted() throws Exception {
GHEventPayload.Label labelPayload = GitHub.offline()
.parseEventPayload(payload.asReader(), GHEventPayload.Label.class);
GHLabel label = labelPayload.getLabel();
assertThat(labelPayload.getAction(), is("deleted"));
assertThat(labelPayload.getRepository().getFullName(), is("gsmet/quarkus-bot-java-playground"));
assertThat(label.getId(), is(2901546662L));
assertThat(label.getNodeId(), is("MDU6TGFiZWwyOTAxNTQ2NjYy"));
assertThat(label.getName(), is("new-label-updated"));
assertThat(label.getColor(), is("4AE686"));
assertThat(label.isDefault(), is(false));
assertThat(label.getDescription(), is("description"));
}
} }

View File

@@ -0,0 +1,35 @@
package org.kohsuke.github;
import org.junit.Test;
import org.kohsuke.github.GHEvent.GitHubEventType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class GHEventTest {
/**
* Function from GHEventInfo to transform string event to GHEvent which has been replaced by static mapping due to
* complex parsing logic below
*/
private static GHEvent oldTransformationFunction(String t) {
if (t.endsWith("Event")) {
t = t.substring(0, t.length() - 5);
}
for (GHEvent e : GHEvent.values()) {
if (e.name().replace("_", "").equalsIgnoreCase(t)) {
return e;
}
}
return GHEvent.UNKNOWN;
}
@Test
public void regressionTest() {
assertThat(GitHubEventType.transformToGHEvent("NewlyAddedOrBogusEvent"), is(GHEvent.UNKNOWN));
for (GitHubEventType gitHubEventType : GitHubEventType.values()) {
assertThat(GitHubEventType.transformToGHEvent(gitHubEventType.name()),
is(oldTransformationFunction(gitHubEventType.name())));
}
}
}

View File

@@ -5,7 +5,6 @@ import org.junit.Test;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
/** /**
* @author Kohsuke Kawaguchi * @author Kohsuke Kawaguchi
@@ -26,12 +25,12 @@ public class GHGistTest extends AbstractGitHubWireMockTest {
assertThat(gist.getDescription(), equalTo("Test Gist")); assertThat(gist.getDescription(), equalTo("Test Gist"));
assertThat(gist.getFiles().size(), equalTo(3)); assertThat(gist.getFiles().size(), equalTo(3));
assertNotNull(gist.getUpdatedAt()); assertThat(gist.getUpdatedAt(), notNullValue());
assertNotNull(gist.getCommentsUrl()); assertThat(gist.getCommentsUrl(), notNullValue());
assertNotNull(gist.getCommitsUrl()); assertThat(gist.getCommitsUrl(), notNullValue());
assertNotNull(gist.getGitPullUrl()); assertThat(gist.getGitPullUrl(), notNullValue());
assertNotNull(gist.getGitPushUrl()); assertThat(gist.getGitPushUrl(), notNullValue());
assertNotNull(gist.getHtmlUrl()); assertThat(gist.getHtmlUrl(), notNullValue());
String id = gist.getGistId(); String id = gist.getGistId();
@@ -98,13 +97,13 @@ public class GHGistTest extends AbstractGitHubWireMockTest {
@Test @Test
public void starTest() throws Exception { public void starTest() throws Exception {
GHGist gist = gitHub.getGist("9903708"); GHGist gist = gitHub.getGist("9903708");
assertEquals("rtyler", gist.getOwner().getLogin()); assertThat(gist.getOwner().getLogin(), equalTo("rtyler"));
gist.star(); gist.star();
assertTrue(gist.isStarred()); assertThat(gist.isStarred(), is(true));
gist.unstar(); gist.unstar();
assertFalse(gist.isStarred()); assertThat(gist.isStarred(), is(false));
GHGist newGist = gist.fork(); GHGist newGist = gist.fork();
@@ -126,16 +125,15 @@ public class GHGistTest extends AbstractGitHubWireMockTest {
public void gistFile() throws Exception { public void gistFile() throws Exception {
GHGist gist = gitHub.getGist("9903708"); GHGist gist = gitHub.getGist("9903708");
assertTrue(gist.isPublic()); assertThat(gist.isPublic(), is(true));
assertThat(gist.getId(), equalTo(9903708L)); assertThat(gist.getId(), equalTo(9903708L));
assertThat(gist.getGistId(), equalTo("9903708")); assertThat(gist.getGistId(), equalTo("9903708"));
assertEquals(1, gist.getFiles().size()); assertThat(gist.getFiles().size(), equalTo(1));
GHGistFile f = gist.getFile("keybase.md"); GHGistFile f = gist.getFile("keybase.md");
assertEquals("text/markdown", f.getType()); assertThat(f.getType(), equalTo("text/markdown"));
assertEquals("Markdown", f.getLanguage()); assertThat(f.getLanguage(), equalTo("Markdown"));
assertTrue(f.getContent().contains("### Keybase proof")); assertThat(f.getContent(), containsString("### Keybase proof"));
assertNotNull(f.getContent());
} }
} }

View File

@@ -7,6 +7,8 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import static org.hamcrest.Matchers.*;
/** /**
* @author Martin van Zijl * @author Martin van Zijl
*/ */
@@ -46,24 +48,24 @@ public class GHGistUpdaterTest extends AbstractGitHubWireMockTest {
.updateFile("update-me.txt", "Content updated by API") .updateFile("update-me.txt", "Content updated by API")
.update(); .update();
assertEquals("Description updated by API", updatedGist.getDescription()); assertThat(updatedGist.getDescription(), equalTo("Description updated by API"));
Map<String, GHGistFile> files = updatedGist.getFiles(); Map<String, GHGistFile> files = updatedGist.getFiles();
// Check that the unmodified file stays intact. // Check that the unmodified file stays intact.
assertTrue(files.containsKey("unmodified.txt")); assertThat(files.get("unmodified.txt"), is(notNullValue()));
assertEquals("Should be unmodified", files.get("unmodified.txt").getContent()); assertThat(files.get("unmodified.txt").getContent(), equalTo("Should be unmodified"));
// Check that the files are updated as expected. // Check that the files are updated as expected.
// assertFalse("File was not deleted.", files.containsKey("delete-me.txt")); // assertFalse("File was not deleted.", files.containsKey("delete-me.txt"));
assertTrue(files.containsKey("new-file.txt")); assertThat(files.get("new-file.txt"), is(notNullValue()));
assertEquals("Added by updater", files.get("new-file.txt").getContent()); assertThat(files.get("new-file.txt").getContent(), equalTo("Added by updater"));
assertFalse(files.containsKey("rename-me.py")); assertThat(files.containsKey("rename-me.py"), is(false));
assertTrue(files.containsKey("renamed.py")); assertThat(files.get("renamed.py"), is(notNullValue()));
assertEquals("print 'hello'", files.get("renamed.py").getContent()); assertThat(files.get("renamed.py").getContent(), equalTo("print 'hello'"));
assertEquals("Content updated by API", files.get("update-me.txt").getContent()); assertThat(files.get("update-me.txt").getContent(), equalTo("Content updated by API"));
} }
} }

View File

@@ -13,13 +13,14 @@ import java.util.stream.StreamSupport;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
public class GHIssueEventAttributeTest extends AbstractGitHubWireMockTest { public class GHIssueEventAttributeTest extends AbstractGitHubWireMockTest {
private enum Type implements Predicate<GHIssueEvent>, Consumer<GHIssueEvent> { private enum Type implements Predicate<GHIssueEvent>, Consumer<GHIssueEvent> {
milestone(e -> assertNotNull(e.getMilestone()), "milestoned", "demilestoned"), milestone(e -> assertThat(e.getMilestone(), notNullValue()), "milestoned", "demilestoned"),
label(e -> assertNotNull(e.getLabel()), "labeled", "unlabeled"), label(e -> assertThat(e.getLabel(), notNullValue()), "labeled", "unlabeled"),
assignment(e -> assertNotNull(e.getAssignee()), "assigned", "unassigned"); assignment(e -> assertThat(e.getAssignee(), notNullValue()), "assigned", "unassigned");
private final Consumer<GHIssueEvent> assertion; private final Consumer<GHIssueEvent> assertion;
private final Set<String> subtypes; private final Set<String> subtypes;

View File

@@ -5,6 +5,8 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.*;
/** /**
* @author Martin van Zijl * @author Martin van Zijl
*/ */
@@ -22,16 +24,16 @@ public class GHIssueEventTest extends AbstractGitHubWireMockTest {
// Test that the events are present. // Test that the events are present.
List<GHIssueEvent> list = issue.listEvents().toList(); List<GHIssueEvent> list = issue.listEvents().toList();
assertEquals(1, list.size()); assertThat(list.size(), equalTo(1));
GHIssueEvent event = list.get(0); GHIssueEvent event = list.get(0);
assertEquals(issue.getNumber(), event.getIssue().getNumber()); assertThat(event.getIssue().getNumber(), equalTo(issue.getNumber()));
assertEquals("labeled", event.getEvent()); assertThat(event.getEvent(), equalTo("labeled"));
// Test that we can get a single event directly. // Test that we can get a single event directly.
GHIssueEvent eventFromRepo = repo.getIssueEvent(event.getId()); GHIssueEvent eventFromRepo = repo.getIssueEvent(event.getId());
assertEquals(event.getId(), eventFromRepo.getId()); assertThat(eventFromRepo.getId(), equalTo(event.getId()));
assertEquals(event.getCreatedAt(), eventFromRepo.getCreatedAt()); assertThat(eventFromRepo.getCreatedAt(), equalTo(event.getCreatedAt()));
// Close the issue. // Close the issue.
issue.close(); issue.close();
@@ -41,11 +43,11 @@ public class GHIssueEventTest extends AbstractGitHubWireMockTest {
public void testRepositoryEvents() throws Exception { public void testRepositoryEvents() throws Exception {
GHRepository repo = getRepository(); GHRepository repo = getRepository();
List<GHIssueEvent> list = repo.listIssueEvents().toList(); List<GHIssueEvent> list = repo.listIssueEvents().toList();
assertTrue(list.size() > 0); assertThat(list, is(not(empty())));
int i = 0; int i = 0;
for (GHIssueEvent event : list) { for (GHIssueEvent event : list) {
assertNotNull(event.getIssue()); assertThat(event.getIssue(), notNullValue());
if (i++ > 10) if (i++ > 10)
break; break;
} }

View File

@@ -46,7 +46,7 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
@Test @Test
public void listLicenses() throws IOException { public void listLicenses() throws IOException {
Iterable<GHLicense> licenses = gitHub.listLicenses(); Iterable<GHLicense> licenses = gitHub.listLicenses();
assertTrue(licenses.iterator().hasNext()); assertThat(licenses, is(not(emptyIterable())));
} }
/** /**
@@ -60,7 +60,7 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
PagedIterable<GHLicense> licenses = gitHub.listLicenses(); PagedIterable<GHLicense> licenses = gitHub.listLicenses();
for (GHLicense lic : licenses) { for (GHLicense lic : licenses) {
if (lic.getKey().equals("mit")) { if (lic.getKey().equals("mit")) {
assertTrue(lic.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); assertThat(lic.getUrl(), equalTo(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit")));
return; return;
} }
} }
@@ -78,14 +78,14 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
public void getLicense() throws IOException { public void getLicense() throws IOException {
String key = "mit"; String key = "mit";
GHLicense license = gitHub.getLicense(key); GHLicense license = gitHub.getLicense(key);
assertNotNull(license); assertThat(license, notNullValue());
assertThat("The name is correct", license.getName(), equalTo("MIT License")); assertThat("The name is correct", license.getName(), equalTo("MIT License"));
assertThat("The HTML URL is correct", assertThat("The HTML URL is correct",
license.getHtmlUrl(), license.getHtmlUrl(),
equalTo(new URL("http://choosealicense.com/licenses/mit/"))); equalTo(new URL("http://choosealicense.com/licenses/mit/")));
assertThat(license.getBody(), startsWith("MIT License\n" + "\n" + "Copyright (c) [year] [fullname]\n\n")); assertThat(license.getBody(), startsWith("MIT License\n" + "\n" + "Copyright (c) [year] [fullname]\n\n"));
assertThat(license.getForbidden().size(), equalTo(0)); assertThat(license.getForbidden(), is(empty()));
assertThat(license.getPermitted().size(), equalTo(0)); assertThat(license.getPermitted(), is(empty()));
assertThat(license.getImplementation(), assertThat(license.getImplementation(),
equalTo("Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders.")); equalTo("Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders."));
assertThat(license.getCategory(), nullValue()); assertThat(license.getCategory(), nullValue());
@@ -105,11 +105,12 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
public void checkRepositoryLicense() throws IOException { public void checkRepositoryLicense() throws IOException {
GHRepository repo = gitHub.getRepository("hub4j/github-api"); GHRepository repo = gitHub.getRepository("hub4j/github-api");
GHLicense license = repo.getLicense(); GHLicense license = repo.getLicense();
assertNotNull("The license is populated", license); assertThat("The license is populated", license, notNullValue());
assertTrue("The key is correct", license.getKey().equals("mit")); assertThat("The key is correct", license.getKey(), equalTo("mit"));
assertTrue("The name is correct", license.getName().equals("MIT License")); assertThat("The name is correct", license.getName(), equalTo("MIT License"));
assertTrue("The URL is correct", assertThat("The URL is correct",
license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); license.getUrl(),
equalTo(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit")));
} }
/** /**
@@ -122,11 +123,12 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
public void checkRepositoryLicenseAtom() throws IOException { public void checkRepositoryLicenseAtom() throws IOException {
GHRepository repo = gitHub.getRepository("atom/atom"); GHRepository repo = gitHub.getRepository("atom/atom");
GHLicense license = repo.getLicense(); GHLicense license = repo.getLicense();
assertNotNull("The license is populated", license); assertThat("The license is populated", license, notNullValue());
assertTrue("The key is correct", license.getKey().equals("mit")); assertThat("The key is correct", license.getKey(), equalTo("mit"));
assertTrue("The name is correct", license.getName().equals("MIT License")); assertThat("The name is correct", license.getName(), equalTo("MIT License"));
assertTrue("The URL is correct", assertThat("The URL is correct",
license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); license.getUrl(),
equalTo(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit")));
} }
/** /**
@@ -139,11 +141,12 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
public void checkRepositoryLicensePomes() throws IOException { public void checkRepositoryLicensePomes() throws IOException {
GHRepository repo = gitHub.getRepository("pomes/pomes"); GHRepository repo = gitHub.getRepository("pomes/pomes");
GHLicense license = repo.getLicense(); GHLicense license = repo.getLicense();
assertNotNull("The license is populated", license); assertThat("The license is populated", license, notNullValue());
assertTrue("The key is correct", license.getKey().equals("apache-2.0")); assertThat("The key is correct", license.getKey(), equalTo("apache-2.0"));
assertTrue("The name is correct", license.getName().equals("Apache License 2.0")); assertThat("The name is correct", license.getName(), equalTo("Apache License 2.0"));
assertTrue("The URL is correct", assertThat("The URL is correct",
license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/apache-2.0"))); license.getUrl(),
equalTo(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/apache-2.0")));
} }
/** /**
@@ -157,7 +160,7 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
public void checkRepositoryWithoutLicense() throws IOException { public void checkRepositoryWithoutLicense() throws IOException {
GHRepository repo = gitHub.getRepository(GITHUB_API_TEST_ORG + "/empty"); GHRepository repo = gitHub.getRepository(GITHUB_API_TEST_ORG + "/empty");
GHLicense license = repo.getLicense(); GHLicense license = repo.getLicense();
assertNull("There is no license", license); assertThat("There is no license", license, nullValue());
} }
/** /**
@@ -171,13 +174,15 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
public void checkRepositoryFullLicense() throws IOException { public void checkRepositoryFullLicense() throws IOException {
GHRepository repo = gitHub.getRepository("hub4j/github-api"); GHRepository repo = gitHub.getRepository("hub4j/github-api");
GHLicense license = repo.getLicense(); GHLicense license = repo.getLicense();
assertNotNull("The license is populated", license); assertThat("The license is populated", license, notNullValue());
assertTrue("The key is correct", license.getKey().equals("mit")); assertThat("The key is correct", license.getKey(), equalTo("mit"));
assertTrue("The name is correct", license.getName().equals("MIT License")); assertThat("The name is correct", license.getName(), equalTo("MIT License"));
assertTrue("The URL is correct", assertThat("The URL is correct",
license.getUrl().equals(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit"))); license.getUrl(),
assertTrue("The HTML URL is correct", equalTo(new URL(mockGitHub.apiServer().baseUrl() + "/licenses/mit")));
license.getHtmlUrl().equals(new URL("http://choosealicense.com/licenses/mit/"))); assertThat("The HTML URL is correct",
license.getHtmlUrl(),
equalTo(new URL("http://choosealicense.com/licenses/mit/")));
} }
/** /**
@@ -191,13 +196,13 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
public void checkRepositoryLicenseContent() throws IOException { public void checkRepositoryLicenseContent() throws IOException {
GHRepository repo = gitHub.getRepository("pomes/pomes"); GHRepository repo = gitHub.getRepository("pomes/pomes");
GHContent content = repo.getLicenseContent(); GHContent content = repo.getLicenseContent();
assertNotNull("The license content is populated", content); assertThat("The license content is populated", content, notNullValue());
assertTrue("The type is 'file'", content.getType().equals("file")); assertThat("The type is 'file'", content.getType(), equalTo("file"));
assertTrue("The license file is 'LICENSE'", content.getName().equals("LICENSE")); assertThat("The license file is 'LICENSE'", content.getName(), equalTo("LICENSE"));
if (content.getEncoding().equals("base64")) { if (content.getEncoding().equals("base64")) {
String licenseText = new String(IOUtils.toByteArray(content.read())); String licenseText = new String(IOUtils.toByteArray(content.read()));
assertTrue("The license appears to be an Apache License", licenseText.contains("Apache License")); assertThat("The license appears to be an Apache License", licenseText.contains("Apache License"));
} else { } else {
fail("Expected the license to be Base64 encoded but instead it was " + content.getEncoding()); fail("Expected the license to be Base64 encoded but instead it was " + content.getEncoding());
} }
@@ -214,7 +219,7 @@ public class GHLicenseTest extends AbstractGitHubWireMockTest {
public void checkRepositoryLicenseForIndeterminate() throws IOException { public void checkRepositoryLicenseForIndeterminate() throws IOException {
GHRepository repo = gitHub.getRepository("bndtools/bnd"); GHRepository repo = gitHub.getRepository("bndtools/bnd");
GHLicense license = repo.getLicense(); GHLicense license = repo.getLicense();
assertNotNull("The license is populated", license); assertThat("The license is populated", license, notNullValue());
assertThat(license.getKey(), equalTo("other")); assertThat(license.getKey(), equalTo("other"));
assertThat(license.getDescription(), is(nullValue())); assertThat(license.getDescription(), is(nullValue()));
assertThat(license.getUrl(), is(nullValue())); assertThat(license.getUrl(), is(nullValue()));

View File

@@ -5,11 +5,7 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.kohsuke.github.GHDirection.DESC; import static org.kohsuke.github.GHDirection.DESC;
import static org.kohsuke.github.GHMarketplaceAccountType.ORGANIZATION; import static org.kohsuke.github.GHMarketplaceAccountType.ORGANIZATION;
import static org.kohsuke.github.GHMarketplaceListAccountBuilder.Sort.UPDATED; import static org.kohsuke.github.GHMarketplaceListAccountBuilder.Sort.UPDATED;
@@ -31,30 +27,30 @@ public class GHMarketplacePlanTest extends AbstractGitHubWireMockTest {
@Test @Test
public void listMarketplacePlans() throws IOException { public void listMarketplacePlans() throws IOException {
List<GHMarketplacePlan> plans = gitHub.listMarketplacePlans().toList(); List<GHMarketplacePlan> plans = gitHub.listMarketplacePlans().toList();
assertEquals(3, plans.size()); assertThat(plans.size(), equalTo(3));
plans.forEach(this::testMarketplacePlan); plans.forEach(this::testMarketplacePlan);
} }
@Test @Test
public void listAccounts() throws IOException { public void listAccounts() throws IOException {
List<GHMarketplacePlan> plans = gitHub.listMarketplacePlans().toList(); List<GHMarketplacePlan> plans = gitHub.listMarketplacePlans().toList();
assertEquals(3, plans.size()); assertThat(plans.size(), equalTo(3));
List<GHMarketplaceAccountPlan> marketplaceUsers = plans.get(0).listAccounts().createRequest().toList(); List<GHMarketplaceAccountPlan> marketplaceUsers = plans.get(0).listAccounts().createRequest().toList();
assertEquals(2, marketplaceUsers.size()); assertThat(marketplaceUsers.size(), equalTo(2));
marketplaceUsers.forEach(this::testMarketplaceAccount); marketplaceUsers.forEach(this::testMarketplaceAccount);
} }
@Test @Test
public void listAccountsWithDirection() throws IOException { public void listAccountsWithDirection() throws IOException {
List<GHMarketplacePlan> plans = gitHub.listMarketplacePlans().toList(); List<GHMarketplacePlan> plans = gitHub.listMarketplacePlans().toList();
assertEquals(3, plans.size()); assertThat(plans.size(), equalTo(3));
for (GHMarketplacePlan plan : plans) { for (GHMarketplacePlan plan : plans) {
List<GHMarketplaceAccountPlan> marketplaceUsers = plan.listAccounts() List<GHMarketplaceAccountPlan> marketplaceUsers = plan.listAccounts()
.direction(DESC) .direction(DESC)
.createRequest() .createRequest()
.toList(); .toList();
assertEquals(2, marketplaceUsers.size()); assertThat(marketplaceUsers.size(), equalTo(2));
marketplaceUsers.forEach(this::testMarketplaceAccount); marketplaceUsers.forEach(this::testMarketplaceAccount);
} }
@@ -63,7 +59,7 @@ public class GHMarketplacePlanTest extends AbstractGitHubWireMockTest {
@Test @Test
public void listAccountsWithSortAndDirection() throws IOException { public void listAccountsWithSortAndDirection() throws IOException {
List<GHMarketplacePlan> plans = gitHub.listMarketplacePlans().toList(); List<GHMarketplacePlan> plans = gitHub.listMarketplacePlans().toList();
assertEquals(3, plans.size()); assertThat(plans.size(), equalTo(3));
for (GHMarketplacePlan plan : plans) { for (GHMarketplacePlan plan : plans) {
List<GHMarketplaceAccountPlan> marketplaceUsers = plan.listAccounts() List<GHMarketplaceAccountPlan> marketplaceUsers = plan.listAccounts()
@@ -71,7 +67,7 @@ public class GHMarketplacePlanTest extends AbstractGitHubWireMockTest {
.direction(DESC) .direction(DESC)
.createRequest() .createRequest()
.toList(); .toList();
assertEquals(2, marketplaceUsers.size()); assertThat(marketplaceUsers.size(), equalTo(2));
marketplaceUsers.forEach(this::testMarketplaceAccount); marketplaceUsers.forEach(this::testMarketplaceAccount);
} }
@@ -79,39 +75,39 @@ public class GHMarketplacePlanTest extends AbstractGitHubWireMockTest {
private void testMarketplacePlan(GHMarketplacePlan plan) { private void testMarketplacePlan(GHMarketplacePlan plan) {
// Non-nullable fields // Non-nullable fields
assertNotNull(plan.getUrl()); assertThat(plan.getUrl(), notNullValue());
assertNotNull(plan.getAccountsUrl()); assertThat(plan.getAccountsUrl(), notNullValue());
assertNotNull(plan.getName()); assertThat(plan.getName(), notNullValue());
assertNotNull(plan.getDescription()); assertThat(plan.getDescription(), notNullValue());
assertNotNull(plan.getPriceModel()); assertThat(plan.getPriceModel(), notNullValue());
assertNotNull(plan.getState()); assertThat(plan.getState(), notNullValue());
// primitive fields // primitive fields
assertNotEquals(0L, plan.getId()); assertThat(plan.getId(), not(0L));
assertNotEquals(0L, plan.getNumber()); assertThat(plan.getNumber(), not(0L));
assertTrue(plan.getMonthlyPriceInCents() >= 0); assertThat(plan.getMonthlyPriceInCents(), greaterThanOrEqualTo(0L));
// list // list
assertEquals(2, plan.getBullets().size()); assertThat(plan.getBullets().size(), equalTo(2));
} }
private void testMarketplaceAccount(GHMarketplaceAccountPlan account) { private void testMarketplaceAccount(GHMarketplaceAccountPlan account) {
// Non-nullable fields // Non-nullable fields
assertNotNull(account.getLogin()); assertThat(account.getLogin(), notNullValue());
assertNotNull(account.getUrl()); assertThat(account.getUrl(), notNullValue());
assertNotNull(account.getType()); assertThat(account.getType(), notNullValue());
assertNotNull(account.getMarketplacePurchase()); assertThat(account.getMarketplacePurchase(), notNullValue());
testMarketplacePurchase(account.getMarketplacePurchase()); testMarketplacePurchase(account.getMarketplacePurchase());
// primitive fields // primitive fields
assertNotEquals(0L, account.getId()); assertThat(account.getId(), not(0L));
/* logical combination tests */ /* logical combination tests */
// Rationale: organization_billing_email is only set when account type is ORGANIZATION. // Rationale: organization_billing_email is only set when account type is ORGANIZATION.
if (account.getType() == ORGANIZATION) if (account.getType() == ORGANIZATION)
assertNotNull(account.getOrganizationBillingEmail()); assertThat(account.getOrganizationBillingEmail(), notNullValue());
else else
assertNull(account.getOrganizationBillingEmail()); assertThat(account.getOrganizationBillingEmail(), nullValue());
// Rationale: marketplace_pending_change isn't always set... This is what GitHub says about it: // Rationale: marketplace_pending_change isn't always set... This is what GitHub says about it:
// "When someone submits a plan change that won't be processed until the end of their billing cycle, // "When someone submits a plan change that won't be processed until the end of their billing cycle,
@@ -122,41 +118,41 @@ public class GHMarketplacePlanTest extends AbstractGitHubWireMockTest {
private void testMarketplacePurchase(GHMarketplacePurchase marketplacePurchase) { private void testMarketplacePurchase(GHMarketplacePurchase marketplacePurchase) {
// Non-nullable fields // Non-nullable fields
assertNotNull(marketplacePurchase.getBillingCycle()); assertThat(marketplacePurchase.getBillingCycle(), notNullValue());
assertNotNull(marketplacePurchase.getNextBillingDate()); assertThat(marketplacePurchase.getNextBillingDate(), notNullValue());
assertNotNull(marketplacePurchase.getUpdatedAt()); assertThat(marketplacePurchase.getUpdatedAt(), notNullValue());
testMarketplacePlan(marketplacePurchase.getPlan()); testMarketplacePlan(marketplacePurchase.getPlan());
/* logical combination tests */ /* logical combination tests */
// Rationale: if onFreeTrial is true, then we should see free_trial_ends_on property set to something // Rationale: if onFreeTrial is true, then we should see free_trial_ends_on property set to something
// different than null // different than null
if (marketplacePurchase.isOnFreeTrial()) if (marketplacePurchase.isOnFreeTrial())
assertNotNull(marketplacePurchase.getFreeTrialEndsOn()); assertThat(marketplacePurchase.getFreeTrialEndsOn(), notNullValue());
else else
assertNull(marketplacePurchase.getFreeTrialEndsOn()); assertThat(marketplacePurchase.getFreeTrialEndsOn(), nullValue());
// Rationale: if price model is PER_UNIT then unit_count can't be null // Rationale: if price model is PER_UNIT then unit_count can't be null
if (marketplacePurchase.getPlan().getPriceModel() == GHMarketplacePriceModel.PER_UNIT) if (marketplacePurchase.getPlan().getPriceModel() == GHMarketplacePriceModel.PER_UNIT)
assertNotNull(marketplacePurchase.getUnitCount()); assertThat(marketplacePurchase.getUnitCount(), notNullValue());
else else
assertNull(marketplacePurchase.getUnitCount()); assertThat(marketplacePurchase.getUnitCount(), nullValue());
} }
private void testMarketplacePendingChange(GHMarketplacePendingChange marketplacePendingChange) { private void testMarketplacePendingChange(GHMarketplacePendingChange marketplacePendingChange) {
// Non-nullable fields // Non-nullable fields
assertNotNull(marketplacePendingChange.getEffectiveDate()); assertThat(marketplacePendingChange.getEffectiveDate(), notNullValue());
testMarketplacePlan(marketplacePendingChange.getPlan()); testMarketplacePlan(marketplacePendingChange.getPlan());
// primitive fields // primitive fields
assertNotEquals(0L, marketplacePendingChange.getId()); assertThat(marketplacePendingChange.getId(), not(0L));
/* logical combination tests */ /* logical combination tests */
// Rationale: if price model is PER_UNIT then unit_count can't be null // Rationale: if price model is PER_UNIT then unit_count can't be null
if (marketplacePendingChange.getPlan().getPriceModel() == GHMarketplacePriceModel.PER_UNIT) if (marketplacePendingChange.getPlan().getPriceModel() == GHMarketplacePriceModel.PER_UNIT)
assertNotNull(marketplacePendingChange.getUnitCount()); assertThat(marketplacePendingChange.getUnitCount(), notNullValue());
else else
assertNull(marketplacePendingChange.getUnitCount()); assertThat(marketplacePendingChange.getUnitCount(), nullValue());
} }

View File

@@ -7,6 +7,9 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/** /**
* @author Martin van Zijl * @author Martin van Zijl
*/ */
@@ -20,7 +23,7 @@ public class GHMilestoneTest extends AbstractGitHubWireMockTest {
return; return;
} }
for (GHMilestone milestone : getRepository(getGitHubBeforeAfter()).listMilestones(GHIssueState.ALL)) { for (GHMilestone milestone : getRepository(getNonRecordingGitHub()).listMilestones(GHIssueState.ALL)) {
if ("Original Title".equals(milestone.getTitle()) || "Updated Title".equals(milestone.getTitle()) if ("Original Title".equals(milestone.getTitle()) || "Updated Title".equals(milestone.getTitle())
|| "Unset Test Milestone".equals(milestone.getTitle())) { || "Unset Test Milestone".equals(milestone.getTitle())) {
milestone.delete(); milestone.delete();
@@ -45,12 +48,12 @@ public class GHMilestoneTest extends AbstractGitHubWireMockTest {
// Force reload. // Force reload.
milestone = repo.getMilestone(milestone.getNumber()); milestone = repo.getMilestone(milestone.getNumber());
assertEquals(NEW_TITLE, milestone.getTitle()); assertThat(milestone.getTitle(), equalTo(NEW_TITLE));
assertEquals(NEW_DESCRIPTION, milestone.getDescription()); assertThat(milestone.getDescription(), equalTo(NEW_DESCRIPTION));
// The time is truncated when sent to the server, but still part of the returned value // The time is truncated when sent to the server, but still part of the returned value
// 07:00 midnight PDT // 07:00 midnight PDT
assertEquals(OUTPUT_DUE_DATE, milestone.getDueOn()); assertThat(milestone.getDueOn(), equalTo(OUTPUT_DUE_DATE));
} }
@Test @Test
@@ -62,32 +65,30 @@ public class GHMilestoneTest extends AbstractGitHubWireMockTest {
// set the milestone // set the milestone
issue.setMilestone(milestone); issue.setMilestone(milestone);
issue = repo.getIssue(issue.getNumber()); // force reload issue = repo.getIssue(issue.getNumber()); // force reload
assertEquals(milestone.getNumber(), issue.getMilestone().getNumber()); assertThat(issue.getMilestone().getNumber(), equalTo(milestone.getNumber()));
// remove the milestone // remove the milestone
issue.setMilestone(null); issue.setMilestone(null);
issue = repo.getIssue(issue.getNumber()); // force reload issue = repo.getIssue(issue.getNumber()); // force reload
assertEquals(null, issue.getMilestone()); assertThat(issue.getMilestone(), nullValue());
} }
@Test @Test
public void testUnsetMilestoneFromPullRequest() throws IOException { public void testUnsetMilestoneFromPullRequest() throws IOException {
GHRepository repo = getRepository(); GHRepository repo = getRepository();
GHMilestone milestone = repo.createMilestone("Unset Test Milestone", "For testUnsetMilestone"); GHMilestone milestone = repo.createMilestone("Unset Test Milestone", "For testUnsetMilestone");
GHPullRequest p = repo.createPullRequest("testUnsetMilestoneFromPullRequest", GHPullRequest p = repo
"test/stable", .createPullRequest("testUnsetMilestoneFromPullRequest", "test/stable", "main", "## test pull request");
"master",
"## test pull request");
// set the milestone // set the milestone
p.setMilestone(milestone); p.setMilestone(milestone);
p = repo.getPullRequest(p.getNumber()); // force reload p = repo.getPullRequest(p.getNumber()); // force reload
assertEquals(milestone.getNumber(), p.getMilestone().getNumber()); assertThat(p.getMilestone().getNumber(), equalTo(milestone.getNumber()));
// remove the milestone // remove the milestone
p.setMilestone(null); p.setMilestone(null);
p = repo.getPullRequest(p.getNumber()); // force reload p = repo.getPullRequest(p.getNumber()); // force reload
assertNull(p.getMilestone()); assertThat(p.getMilestone(), nullValue());
} }
protected GHRepository getRepository() throws IOException { protected GHRepository getRepository() throws IOException {

View File

@@ -1,13 +1,13 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.junit.After; import org.junit.After;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.kohsuke.github.GHOrganization.Permission; import org.kohsuke.github.GHOrganization.Permission;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
@@ -25,10 +25,12 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
return; return;
} }
GHTeam team = getGitHubBeforeAfter().getOrganization(GITHUB_API_TEST_ORG).getTeamByName(TEAM_NAME_CREATE); GHTeam team = getNonRecordingGitHub().getOrganization(GITHUB_API_TEST_ORG).getTeamByName(TEAM_NAME_CREATE);
if (team != null) { if (team != null) {
team.delete(); team.delete();
} }
getNonRecordingGitHub().getOrganization(GITHUB_API_TEST_ORG).enableOrganizationProjects(true);
} }
@Test @Test
@@ -42,7 +44,7 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
.team(org.getTeamByName("Core Developers")) .team(org.getTeamByName("Core Developers"))
.private_(false) .private_(false)
.create(); .create();
Assert.assertNotNull(repository); assertThat(repository, notNullValue());
} }
@Test @Test
@@ -56,8 +58,8 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
.team(org.getTeamByName("Core Developers")) .team(org.getTeamByName("Core Developers"))
.autoInit(true) .autoInit(true)
.create(); .create();
Assert.assertNotNull(repository); assertThat(repository, notNullValue());
Assert.assertNotNull(repository.getReadme()); assertThat(repository.getReadme(), notNullValue());
} }
@Test @Test
@@ -75,10 +77,10 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
.autoInit(true) .autoInit(true)
.isTemplate(true) .isTemplate(true)
.create(); .create();
Assert.assertNotNull(repository); assertThat(repository, notNullValue());
assertThat(mockGitHub.getRequestCount(), equalTo(requestCount + 1)); assertThat(mockGitHub.getRequestCount(), equalTo(requestCount + 1));
Assert.assertNotNull(repository.getReadme()); assertThat(repository.getReadme(), notNullValue());
assertThat(mockGitHub.getRequestCount(), equalTo(requestCount + 2)); assertThat(mockGitHub.getRequestCount(), equalTo(requestCount + 2));
// isTemplate() does not call populate() from create // isTemplate() does not call populate() from create
@@ -107,8 +109,8 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
.owner(GITHUB_API_TEST_ORG) .owner(GITHUB_API_TEST_ORG)
.create(); .create();
Assert.assertNotNull(repository); assertThat(repository, notNullValue());
Assert.assertNotNull(repository.getReadme()); assertThat(repository.getReadme(), notNullValue());
} }
@@ -139,20 +141,22 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
List<GHUser> admins = org.listMembersWithFilter("all").toList(); List<GHUser> admins = org.listMembersWithFilter("all").toList();
assertNotNull(admins); assertThat(admins, notNullValue());
assertTrue(admins.size() >= 12); // In case more are added in the future // In case more are added in the future
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("alexanderrtaylor"))); assertThat(admins.size(), greaterThanOrEqualTo(12));
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("asthinasthi"))); assertThat(admins.stream().map(GHUser::getLogin).collect(Collectors.toList()),
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("bitwiseman"))); hasItems("alexanderrtaylor",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("farmdawgnation"))); "asthinasthi",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("halkeye"))); "bitwiseman",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("jberglund-BSFT"))); "farmdawgnation",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("kohsuke"))); "halkeye",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("kohsuke2"))); "jberglund-BSFT",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("martinvanzijl"))); "kohsuke",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("PauloMigAlmeida"))); "kohsuke2",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("Sage-Pierce"))); "martinvanzijl",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("timja"))); "PauloMigAlmeida",
"Sage-Pierce",
"timja"));
} }
@Test @Test
@@ -161,20 +165,22 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
List<GHUser> admins = org.listMembersWithRole("admin").toList(); List<GHUser> admins = org.listMembersWithRole("admin").toList();
assertNotNull(admins); assertThat(admins, notNullValue());
assertTrue(admins.size() >= 12); // In case more are added in the future // In case more are added in the future
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("alexanderrtaylor"))); assertThat(admins.size(), greaterThanOrEqualTo(12));
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("asthinasthi"))); assertThat(admins.stream().map(GHUser::getLogin).collect(Collectors.toList()),
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("bitwiseman"))); hasItems("alexanderrtaylor",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("farmdawgnation"))); "asthinasthi",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("halkeye"))); "bitwiseman",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("jberglund-BSFT"))); "farmdawgnation",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("kohsuke"))); "halkeye",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("kohsuke2"))); "jberglund-BSFT",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("martinvanzijl"))); "kohsuke",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("PauloMigAlmeida"))); "kohsuke2",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("Sage-Pierce"))); "martinvanzijl",
assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("timja"))); "PauloMigAlmeida",
"Sage-Pierce",
"timja"));
} }
@Test @Test
@@ -186,8 +192,8 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
// Create team with access to repository. Check access was granted. // Create team with access to repository. Check access was granted.
GHTeam team = org.createTeam(TEAM_NAME_CREATE, GHOrganization.Permission.PUSH, repo); GHTeam team = org.createTeam(TEAM_NAME_CREATE, GHOrganization.Permission.PUSH, repo);
Assert.assertTrue(team.getRepositories().containsKey(REPO_NAME)); assertThat(team.getRepositories().containsKey(REPO_NAME), is(true));
assertEquals(Permission.PUSH.toString().toLowerCase(), team.getPermission()); assertThat(team.getPermission(), equalTo(Permission.PUSH.toString().toLowerCase()));
} }
@Test @Test
@@ -200,8 +206,8 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
// Create team with no permission field. Verify that default permission is pull // Create team with no permission field. Verify that default permission is pull
GHTeam team = org.createTeam(TEAM_NAME_CREATE, repo); GHTeam team = org.createTeam(TEAM_NAME_CREATE, repo);
Assert.assertTrue(team.getRepositories().containsKey(REPO_NAME)); assertThat(team.getRepositories().containsKey(REPO_NAME), is(true));
assertEquals(DEFAULT_PERMISSION, team.getPermission()); assertThat(team.getPermission(), equalTo(DEFAULT_PERMISSION));
} }
@Test @Test
@@ -209,7 +215,7 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG);
GHTeam team = org.createTeam(TEAM_NAME_CREATE).privacy(GHTeam.Privacy.CLOSED).create(); GHTeam team = org.createTeam(TEAM_NAME_CREATE).privacy(GHTeam.Privacy.CLOSED).create();
assertEquals(GHTeam.Privacy.CLOSED, team.getPrivacy()); assertThat(team.getPrivacy(), equalTo(GHTeam.Privacy.CLOSED));
} }
@Test @Test
@@ -224,7 +230,31 @@ public class GHOrganizationTest extends AbstractGitHubWireMockTest {
.privacy(GHTeam.Privacy.CLOSED) .privacy(GHTeam.Privacy.CLOSED)
.parentTeamId(3617900) .parentTeamId(3617900)
.create(); .create();
assertEquals("Team description", team.getDescription()); assertThat(team.getDescription(), equalTo("Team description"));
assertEquals(GHTeam.Privacy.CLOSED, team.getPrivacy()); assertThat(team.getPrivacy(), equalTo(GHTeam.Privacy.CLOSED));
}
@Test
public void testAreOrganizationProjectsEnabled() throws IOException {
// Arrange
GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG);
// Act
boolean result = org.areOrganizationProjectsEnabled();
// Assert
assertThat(result, is(true));
}
@Test
public void testEnableOrganizationProjects() throws IOException {
// Arrange
GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG);
// Act
org.enableOrganizationProjects(false);
// Assert
assertThat(org.areOrganizationProjectsEnabled(), is(false));
} }
} }

View File

@@ -4,6 +4,9 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
/** /**
* @author Martin van Zijl * @author Martin van Zijl
*/ */
@@ -12,15 +15,15 @@ public class GHPersonTest extends AbstractGitHubWireMockTest {
public void testFieldsForOrganization() throws Exception { public void testFieldsForOrganization() throws Exception {
GHRepository repo = getRepository(); GHRepository repo = getRepository();
GHUser owner = repo.getOwner(); GHUser owner = repo.getOwner();
assertEquals("Organization", owner.getType()); assertThat(owner.getType(), equalTo("Organization"));
assertNotNull(owner.isSiteAdmin()); assertThat(owner.isSiteAdmin(), notNullValue());
} }
@Test @Test
public void testFieldsForUser() throws Exception { public void testFieldsForUser() throws Exception {
GHUser user = gitHub.getUser("kohsuke2"); GHUser user = gitHub.getUser("kohsuke2");
assertEquals("User", user.getType()); assertThat(user.getType(), equalTo("User"));
assertNotNull(user.isSiteAdmin()); assertThat(user.isSiteAdmin(), notNullValue());
} }
protected GHRepository getRepository() throws IOException { protected GHRepository getRepository() throws IOException {

View File

@@ -1,13 +1,14 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.junit.After; import org.junit.After;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import static org.hamcrest.Matchers.*;
/** /**
* @author Gunnar Skjold * @author Gunnar Skjold
*/ */
@@ -27,24 +28,24 @@ public class GHProjectCardTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testCreatedCard() { public void testCreatedCard() {
Assert.assertEquals("This is a card", card.getNote()); assertThat(card.getNote(), equalTo("This is a card"));
Assert.assertFalse(card.isArchived()); assertThat(card.isArchived(), is(false));
} }
@Test @Test
public void testEditCardNote() throws IOException { public void testEditCardNote() throws IOException {
card.setNote("New note"); card.setNote("New note");
card = gitHub.getProjectCard(card.getId()); card = gitHub.getProjectCard(card.getId());
Assert.assertEquals("New note", card.getNote()); assertThat(card.getNote(), equalTo("New note"));
Assert.assertFalse(card.isArchived()); assertThat(card.isArchived(), is(false));
} }
@Test @Test
public void testArchiveCard() throws IOException { public void testArchiveCard() throws IOException {
card.setArchived(true); card.setArchived(true);
card = gitHub.getProjectCard(card.getId()); card = gitHub.getProjectCard(card.getId());
Assert.assertEquals("This is a card", card.getNote()); assertThat(card.getNote(), equalTo("This is a card"));
Assert.assertTrue(card.isArchived()); assertThat(card.isArchived(), is(true));
} }
@Test @Test
@@ -53,7 +54,7 @@ public class GHProjectCardTest extends AbstractGitHubWireMockTest {
try { try {
GHIssue issue = repo.createIssue("new-issue").body("With body").create(); GHIssue issue = repo.createIssue("new-issue").body("With body").create();
GHProjectCard card = column.createCard(issue); GHProjectCard card = column.createCard(issue);
Assert.assertEquals(issue.getUrl(), card.getContentUrl()); assertThat(card.getContentUrl(), equalTo(issue.getUrl()));
} finally { } finally {
repo.delete(); repo.delete();
} }
@@ -64,7 +65,7 @@ public class GHProjectCardTest extends AbstractGitHubWireMockTest {
card.delete(); card.delete();
try { try {
card = gitHub.getProjectCard(card.getId()); card = gitHub.getProjectCard(card.getId());
Assert.assertNull(card); assertThat(card, nullValue());
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
card = null; card = null;
} }
@@ -74,7 +75,7 @@ public class GHProjectCardTest extends AbstractGitHubWireMockTest {
public void after() throws IOException { public void after() throws IOException {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
if (card != null) { if (card != null) {
card = getGitHubBeforeAfter().getProjectCard(card.getId()); card = getNonRecordingGitHub().getProjectCard(card.getId());
try { try {
card.delete(); card.delete();
card = null; card = null;
@@ -83,7 +84,7 @@ public class GHProjectCardTest extends AbstractGitHubWireMockTest {
} }
} }
if (column != null) { if (column != null) {
column = getGitHubBeforeAfter().getProjectColumn(column.getId()); column = getNonRecordingGitHub().getProjectColumn(column.getId());
try { try {
column.delete(); column.delete();
column = null; column = null;
@@ -92,7 +93,7 @@ public class GHProjectCardTest extends AbstractGitHubWireMockTest {
} }
} }
if (project != null) { if (project != null) {
project = getGitHubBeforeAfter().getProject(project.getId()); project = getNonRecordingGitHub().getProject(project.getId());
try { try {
project.delete(); project.delete();
project = null; project = null;

View File

@@ -1,13 +1,15 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.junit.After; import org.junit.After;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/** /**
* @author Gunnar Skjold * @author Gunnar Skjold
*/ */
@@ -23,14 +25,14 @@ public class GHProjectColumnTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testCreatedColumn() { public void testCreatedColumn() {
Assert.assertEquals("column-one", column.getName()); assertThat(column.getName(), equalTo("column-one"));
} }
@Test @Test
public void testEditColumnName() throws IOException { public void testEditColumnName() throws IOException {
column.setName("new-name"); column.setName("new-name");
column = gitHub.getProjectColumn(column.getId()); column = gitHub.getProjectColumn(column.getId());
Assert.assertEquals("new-name", column.getName()); assertThat(column.getName(), equalTo("new-name"));
} }
@Test @Test
@@ -38,7 +40,7 @@ public class GHProjectColumnTest extends AbstractGitHubWireMockTest {
column.delete(); column.delete();
try { try {
column = gitHub.getProjectColumn(column.getId()); column = gitHub.getProjectColumn(column.getId());
Assert.assertNull(column); assertThat(column, nullValue());
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
column = null; column = null;
} }
@@ -48,7 +50,7 @@ public class GHProjectColumnTest extends AbstractGitHubWireMockTest {
public void after() throws IOException { public void after() throws IOException {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
if (column != null) { if (column != null) {
column = getGitHubBeforeAfter().getProjectColumn(column.getId()); column = getNonRecordingGitHub().getProjectColumn(column.getId());
try { try {
column.delete(); column.delete();
column = null; column = null;
@@ -57,7 +59,7 @@ public class GHProjectColumnTest extends AbstractGitHubWireMockTest {
} }
} }
if (project != null) { if (project != null) {
project = getGitHubBeforeAfter().getProject(project.getId()); project = getNonRecordingGitHub().getProject(project.getId());
try { try {
project.delete(); project.delete();
project = null; project = null;

View File

@@ -1,13 +1,14 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.junit.After; import org.junit.After;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import static org.hamcrest.Matchers.*;
/** /**
* @author Gunnar Skjold * @author Gunnar Skjold
*/ */
@@ -21,37 +22,37 @@ public class GHProjectTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testCreatedProject() { public void testCreatedProject() {
Assert.assertNotNull(project); assertThat(project, notNullValue());
Assert.assertEquals("test-project", project.getName()); assertThat(project.getName(), equalTo("test-project"));
Assert.assertEquals("This is a test project", project.getBody()); assertThat(project.getBody(), equalTo("This is a test project"));
Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); assertThat(project.getState(), equalTo(GHProject.ProjectState.OPEN));
} }
@Test @Test
public void testEditProjectName() throws IOException { public void testEditProjectName() throws IOException {
project.setName("new-name"); project.setName("new-name");
project = gitHub.getProject(project.getId()); project = gitHub.getProject(project.getId());
Assert.assertEquals("new-name", project.getName()); assertThat(project.getName(), equalTo("new-name"));
Assert.assertEquals("This is a test project", project.getBody()); assertThat(project.getBody(), equalTo("This is a test project"));
Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); assertThat(project.getState(), equalTo(GHProject.ProjectState.OPEN));
} }
@Test @Test
public void testEditProjectBody() throws IOException { public void testEditProjectBody() throws IOException {
project.setBody("New body"); project.setBody("New body");
project = gitHub.getProject(project.getId()); project = gitHub.getProject(project.getId());
Assert.assertEquals("test-project", project.getName()); assertThat(project.getName(), equalTo("test-project"));
Assert.assertEquals("New body", project.getBody()); assertThat(project.getBody(), equalTo("New body"));
Assert.assertEquals(GHProject.ProjectState.OPEN, project.getState()); assertThat(project.getState(), equalTo(GHProject.ProjectState.OPEN));
} }
@Test @Test
public void testEditProjectState() throws IOException { public void testEditProjectState() throws IOException {
project.setState(GHProject.ProjectState.CLOSED); project.setState(GHProject.ProjectState.CLOSED);
project = gitHub.getProject(project.getId()); project = gitHub.getProject(project.getId());
Assert.assertEquals("test-project", project.getName()); assertThat(project.getName(), equalTo("test-project"));
Assert.assertEquals("This is a test project", project.getBody()); assertThat(project.getBody(), equalTo("This is a test project"));
Assert.assertEquals(GHProject.ProjectState.CLOSED, project.getState()); assertThat(project.getState(), equalTo(GHProject.ProjectState.CLOSED));
} }
@Test @Test
@@ -59,7 +60,7 @@ public class GHProjectTest extends AbstractGitHubWireMockTest {
project.delete(); project.delete();
try { try {
project = gitHub.getProject(project.getId()); project = gitHub.getProject(project.getId());
Assert.assertNull(project); assertThat(project, nullValue());
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
project = null; project = null;
} }
@@ -69,7 +70,7 @@ public class GHProjectTest extends AbstractGitHubWireMockTest {
public void after() throws IOException { public void after() throws IOException {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
if (project != null) { if (project != null) {
project = getGitHubBeforeAfter().getProject(project.getId()); project = getNonRecordingGitHub().getProject(project.getId());
try { try {
project.delete(); project.delete();
project = null; project = null;

View File

@@ -4,7 +4,7 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.junit.Assert.assertTrue; import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@@ -15,7 +15,7 @@ public class GHPullRequestMockTest {
GHPullRequest pullRequest = mock(GHPullRequest.class); GHPullRequest pullRequest = mock(GHPullRequest.class);
when(pullRequest.isDraft()).thenReturn(true); when(pullRequest.isDraft()).thenReturn(true);
assertTrue("Mock should return true", pullRequest.isDraft()); assertThat("Mock should return true", pullRequest.isDraft());
} }
} }

View File

@@ -9,14 +9,7 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/** /**
* @author Kohsuke Kawaguchi * @author Kohsuke Kawaguchi
@@ -31,7 +24,7 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
return; return;
} }
for (GHPullRequest pr : getRepository(this.getGitHubBeforeAfter()).getPullRequests(GHIssueState.OPEN)) { for (GHPullRequest pr : getRepository(this.getNonRecordingGitHub()).getPullRequests(GHIssueState.OPEN)) {
pr.close(); pr.close();
} }
} }
@@ -40,8 +33,8 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
public void createPullRequest() throws Exception { public void createPullRequest() throws Exception {
String name = "createPullRequest"; String name = "createPullRequest";
GHRepository repo = getRepository(); GHRepository repo = getRepository();
GHPullRequest p = repo.createPullRequest(name, "test/stable", "master", "## test"); GHPullRequest p = repo.createPullRequest(name, "test/stable", "main", "## test");
assertEquals(name, p.getTitle()); assertThat(p.getTitle(), equalTo(name));
assertThat(p.canMaintainerModify(), is(false)); assertThat(p.canMaintainerModify(), is(false));
assertThat(p.isDraft(), is(false)); assertThat(p.isDraft(), is(false));
} }
@@ -50,8 +43,8 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
public void createDraftPullRequest() throws Exception { public void createDraftPullRequest() throws Exception {
String name = "createDraftPullRequest"; String name = "createDraftPullRequest";
GHRepository repo = getRepository(); GHRepository repo = getRepository();
GHPullRequest p = repo.createPullRequest(name, "test/stable", "master", "## test", false, true); GHPullRequest p = repo.createPullRequest(name, "test/stable", "main", "## test", false, true);
assertEquals(name, p.getTitle()); assertThat(p.getTitle(), equalTo(name));
assertThat(p.canMaintainerModify(), is(false)); assertThat(p.canMaintainerModify(), is(false));
assertThat(p.isDraft(), is(true)); assertThat(p.isDraft(), is(true));
@@ -73,25 +66,25 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
@Test @Test
public void createPullRequestComment() throws Exception { public void createPullRequestComment() throws Exception {
String name = "createPullRequestComment"; String name = "createPullRequestComment";
GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "main", "## test");
p.comment("Some comment"); p.comment("Some comment");
} }
@Test @Test
public void closePullRequest() throws Exception { public void closePullRequest() throws Exception {
String name = "closePullRequest"; String name = "closePullRequest";
GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "main", "## test");
// System.out.println(p.getUrl()); // System.out.println(p.getUrl());
assertEquals(name, p.getTitle()); assertThat(p.getTitle(), equalTo(name));
assertEquals(GHIssueState.OPEN, getRepository().getPullRequest(p.getNumber()).getState()); assertThat(getRepository().getPullRequest(p.getNumber()).getState(), equalTo(GHIssueState.OPEN));
p.close(); p.close();
assertEquals(GHIssueState.CLOSED, getRepository().getPullRequest(p.getNumber()).getState()); assertThat(getRepository().getPullRequest(p.getNumber()).getState(), equalTo(GHIssueState.CLOSED));
} }
@Test @Test
public void pullRequestReviews() throws Exception { public void pullRequestReviews() throws Exception {
String name = "testPullRequestReviews"; String name = "testPullRequestReviews";
GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "main", "## test");
GHPullRequestReview draftReview = p.createReview() GHPullRequestReview draftReview = p.createReview()
.body("Some draft review") .body("Some draft review")
.comment("Some niggle", "README.md", 1) .comment("Some niggle", "README.md", 1)
@@ -107,9 +100,9 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
assertThat(review.getCommitId(), notNullValue()); assertThat(review.getCommitId(), notNullValue());
draftReview.submit("Some review comment", GHPullRequestReviewEvent.COMMENT); draftReview.submit("Some review comment", GHPullRequestReviewEvent.COMMENT);
List<GHPullRequestReviewComment> comments = review.listReviewComments().toList(); List<GHPullRequestReviewComment> comments = review.listReviewComments().toList();
assertEquals(1, comments.size()); assertThat(comments.size(), equalTo(1));
GHPullRequestReviewComment comment = comments.get(0); GHPullRequestReviewComment comment = comments.get(0);
assertEquals("Some niggle", comment.getBody()); assertThat(comment.getBody(), equalTo("Some niggle"));
draftReview = p.createReview().body("Some new review").comment("Some niggle", "README.md", 1).create(); draftReview = p.createReview().body("Some new review").comment("Some niggle", "README.md", 1).create();
draftReview.delete(); draftReview.delete();
} }
@@ -117,15 +110,15 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
@Test @Test
public void pullRequestReviewComments() throws Exception { public void pullRequestReviewComments() throws Exception {
String name = "pullRequestReviewComments"; String name = "pullRequestReviewComments";
GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "main", "## test");
try { try {
// System.out.println(p.getUrl()); // System.out.println(p.getUrl());
assertTrue(p.listReviewComments().toList().isEmpty()); assertThat(p.listReviewComments().toList(), is(empty()));
p.createReviewComment("Sample review comment", p.getHead().getSha(), "README.md", 1); p.createReviewComment("Sample review comment", p.getHead().getSha(), "README.md", 1);
List<GHPullRequestReviewComment> comments = p.listReviewComments().toList(); List<GHPullRequestReviewComment> comments = p.listReviewComments().toList();
assertEquals(1, comments.size()); assertThat(comments.size(), equalTo(1));
GHPullRequestReviewComment comment = comments.get(0); GHPullRequestReviewComment comment = comments.get(0);
assertEquals("Sample review comment", comment.getBody()); assertThat(comment.getBody(), equalTo("Sample review comment"));
assertThat(comment.getInReplyToId(), equalTo(-1L)); assertThat(comment.getInReplyToId(), equalTo(-1L));
assertThat(comment.getPath(), equalTo("README.md")); assertThat(comment.getPath(), equalTo("README.md"));
assertThat(comment.getPosition(), equalTo(1)); assertThat(comment.getPosition(), equalTo(1));
@@ -136,7 +129,7 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
containsString("hub4j-test-org/github-api/pull/" + p.getNumber())); containsString("hub4j-test-org/github-api/pull/" + p.getNumber()));
List<GHReaction> reactions = comment.listReactions().toList(); List<GHReaction> reactions = comment.listReactions().toList();
assertThat(reactions.size(), equalTo(0)); assertThat(reactions, is(empty()));
GHReaction reaction = comment.createReaction(ReactionContent.CONFUSED); GHReaction reaction = comment.createReaction(ReactionContent.CONFUSED);
assertThat(reaction.getContent(), equalTo(ReactionContent.CONFUSED)); assertThat(reaction.getContent(), equalTo(ReactionContent.CONFUSED));
@@ -148,12 +141,12 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
assertThat(reply.getInReplyToId(), equalTo(comment.getId())); assertThat(reply.getInReplyToId(), equalTo(comment.getId()));
comments = p.listReviewComments().toList(); comments = p.listReviewComments().toList();
assertEquals(2, comments.size()); assertThat(comments.size(), equalTo(2));
comment.update("Updated review comment"); comment.update("Updated review comment");
comments = p.listReviewComments().toList(); comments = p.listReviewComments().toList();
comment = comments.get(0); comment = comments.get(0);
assertEquals("Updated review comment", comment.getBody()); assertThat(comment.getBody(), equalTo("Updated review comment"));
comment.delete(); comment.delete();
comments = p.listReviewComments().toList(); comments = p.listReviewComments().toList();
@@ -169,22 +162,22 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testPullRequestReviewRequests() throws Exception { public void testPullRequestReviewRequests() throws Exception {
String name = "testPullRequestReviewRequests"; String name = "testPullRequestReviewRequests";
GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "main", "## test");
// System.out.println(p.getUrl()); // System.out.println(p.getUrl());
assertTrue(p.getRequestedReviewers().isEmpty()); assertThat(p.getRequestedReviewers(), is(empty()));
GHUser kohsuke2 = gitHub.getUser("kohsuke2"); GHUser kohsuke2 = gitHub.getUser("kohsuke2");
p.requestReviewers(Collections.singletonList(kohsuke2)); p.requestReviewers(Collections.singletonList(kohsuke2));
p.refresh(); p.refresh();
assertFalse(p.getRequestedReviewers().isEmpty()); assertThat(p.getRequestedReviewers(), is(not(empty())));
} }
@Test @Test
public void testPullRequestTeamReviewRequests() throws Exception { public void testPullRequestTeamReviewRequests() throws Exception {
String name = "testPullRequestTeamReviewRequests"; String name = "testPullRequestTeamReviewRequests";
GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "main", "## test");
// System.out.println(p.getUrl()); // System.out.println(p.getUrl());
assertTrue(p.getRequestedReviewers().isEmpty()); assertThat(p.getRequestedReviewers(), is(empty()));
GHOrganization testOrg = gitHub.getOrganization("hub4j-test-org"); GHOrganization testOrg = gitHub.getOrganization("hub4j-test-org");
GHTeam testTeam = testOrg.getTeamBySlug("dummy-team"); GHTeam testTeam = testOrg.getTeamBySlug("dummy-team");
@@ -212,7 +205,7 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
public void mergeCommitSHA() throws Exception { public void mergeCommitSHA() throws Exception {
String name = "mergeCommitSHA"; String name = "mergeCommitSHA";
GHRepository repo = getRepository(); GHRepository repo = getRepository();
GHPullRequest p = repo.createPullRequest(name, "test/mergeable_branch", "master", "## test"); GHPullRequest p = repo.createPullRequest(name, "test/mergeable_branch", "main", "## test");
int baseRequestCount = mockGitHub.getRequestCount(); int baseRequestCount = mockGitHub.getRequestCount();
assertThat(p.getMergeableNoRefresh(), nullValue()); assertThat(p.getMergeableNoRefresh(), nullValue());
assertThat("Used existing value", mockGitHub.getRequestCount() - baseRequestCount, equalTo(0)); assertThat("Used existing value", mockGitHub.getRequestCount() - baseRequestCount, equalTo(0));
@@ -227,7 +220,7 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
// make sure commit exists // make sure commit exists
GHCommit commit = repo.getCommit(p.getMergeCommitSha()); GHCommit commit = repo.getCommit(p.getMergeCommitSha());
assertNotNull(commit); assertThat(commit, notNullValue());
assertThat("Asked for PR information", mockGitHub.getRequestCount() - baseRequestCount, equalTo(i + 1)); assertThat("Asked for PR information", mockGitHub.getRequestCount() - baseRequestCount, equalTo(i + 1));
@@ -244,33 +237,33 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
@Test @Test
public void setBaseBranch() throws Exception { public void setBaseBranch() throws Exception {
String prName = "testSetBaseBranch"; String prName = "testSetBaseBranch";
String originalBaseBranch = "master"; String originalBaseBranch = "main";
String newBaseBranch = "gh-pages"; String newBaseBranch = "gh-pages";
GHPullRequest pullRequest = getRepository().createPullRequest(prName, "test/stable", "master", "## test"); GHPullRequest pullRequest = getRepository().createPullRequest(prName, "test/stable", "main", "## test");
assertEquals("Pull request base branch is supposed to be " + originalBaseBranch, assertThat("Pull request base branch is supposed to be " + originalBaseBranch,
originalBaseBranch, pullRequest.getBase().getRef(),
pullRequest.getBase().getRef()); equalTo(originalBaseBranch));
GHPullRequest responsePullRequest = pullRequest.setBaseBranch(newBaseBranch); GHPullRequest responsePullRequest = pullRequest.setBaseBranch(newBaseBranch);
assertEquals("Pull request base branch is supposed to be " + newBaseBranch, assertThat("Pull request base branch is supposed to be " + newBaseBranch,
newBaseBranch, responsePullRequest.getBase().getRef(),
responsePullRequest.getBase().getRef()); equalTo(newBaseBranch));
} }
@Test @Test
public void setBaseBranchNonExisting() throws Exception { public void setBaseBranchNonExisting() throws Exception {
String prName = "testSetBaseBranchNonExisting"; String prName = "testSetBaseBranchNonExisting";
String originalBaseBranch = "master"; String originalBaseBranch = "main";
String newBaseBranch = "non-existing"; String newBaseBranch = "non-existing";
GHPullRequest pullRequest = getRepository().createPullRequest(prName, "test/stable", "master", "## test"); GHPullRequest pullRequest = getRepository().createPullRequest(prName, "test/stable", "main", "## test");
assertEquals("Pull request base branch is supposed to be " + originalBaseBranch, assertThat("Pull request base branch is supposed to be " + originalBaseBranch,
originalBaseBranch, pullRequest.getBase().getRef(),
pullRequest.getBase().getRef()); equalTo(originalBaseBranch));
try { try {
pullRequest.setBaseBranch(newBaseBranch); pullRequest.setBaseBranch(newBaseBranch);
@@ -291,16 +284,16 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
GHRef outdatedRef = repository.getRef(outdatedRefName); GHRef outdatedRef = repository.getRef(outdatedRefName);
outdatedRef.updateTo("6440189369f9f33b2366556a94dbc26f2cfdd969", true); outdatedRef.updateTo("6440189369f9f33b2366556a94dbc26f2cfdd969", true);
GHPullRequest outdatedPullRequest = repository.createPullRequest(prName, "outdated", "master", "## test"); GHPullRequest outdatedPullRequest = repository.createPullRequest(prName, "outdated", "main", "## test");
do { do {
Thread.sleep(5000); Thread.sleep(5000);
outdatedPullRequest.refresh(); outdatedPullRequest.refresh();
} while (outdatedPullRequest.getMergeableState().equalsIgnoreCase("unknown")); } while (outdatedPullRequest.getMergeableState().equalsIgnoreCase("unknown"));
assertEquals("Pull request is supposed to be not up to date", assertThat("Pull request is supposed to be not up to date",
"behind", outdatedPullRequest.getMergeableState(),
outdatedPullRequest.getMergeableState()); equalTo("behind"));
outdatedRef.updateTo("f567328eb81270487864963b7d7446953353f2b5", true); outdatedRef.updateTo("f567328eb81270487864963b7d7446953353f2b5", true);
@@ -322,21 +315,21 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
repository.getRef(outdatedRefName).updateTo("6440189369f9f33b2366556a94dbc26f2cfdd969", true); repository.getRef(outdatedRefName).updateTo("6440189369f9f33b2366556a94dbc26f2cfdd969", true);
GHPullRequest outdatedPullRequest = repository.createPullRequest(prName, "outdated", "master", "## test"); GHPullRequest outdatedPullRequest = repository.createPullRequest(prName, "outdated", "main", "## test");
do { do {
Thread.sleep(5000); Thread.sleep(5000);
outdatedPullRequest.refresh(); outdatedPullRequest.refresh();
} while (outdatedPullRequest.getMergeableState().equalsIgnoreCase("unknown")); } while (outdatedPullRequest.getMergeableState().equalsIgnoreCase("unknown"));
assertEquals("Pull request is supposed to be not up to date", assertThat("Pull request is supposed to be not up to date",
"behind", outdatedPullRequest.getMergeableState(),
outdatedPullRequest.getMergeableState()); equalTo("behind"));
outdatedPullRequest.updateBranch(); outdatedPullRequest.updateBranch();
outdatedPullRequest.refresh(); outdatedPullRequest.refresh();
assertNotEquals("Pull request is supposed to be up to date", "behind", outdatedPullRequest.getMergeableState()); assertThat("Pull request is supposed to be up to date", outdatedPullRequest.getMergeableState(), not("behind"));
outdatedPullRequest.close(); outdatedPullRequest.close();
} }
@@ -345,12 +338,12 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
public void squashMerge() throws Exception { public void squashMerge() throws Exception {
String name = "squashMerge"; String name = "squashMerge";
String branchName = "test/" + name; String branchName = "test/" + name;
GHRef masterRef = getRepository().getRef("heads/master"); GHRef mainRef = getRepository().getRef("heads/main");
GHRef branchRef = getRepository().createRef("refs/heads/" + branchName, masterRef.getObject().getSha()); GHRef branchRef = getRepository().createRef("refs/heads/" + branchName, mainRef.getObject().getSha());
getRepository().createContent(name, name, name, branchName); getRepository().createContent(name, name, name, branchName);
Thread.sleep(1000); Thread.sleep(1000);
GHPullRequest p = getRepository().createPullRequest(name, branchName, "master", "## test squash"); GHPullRequest p = getRepository().createPullRequest(name, branchName, "main", "## test squash");
Thread.sleep(1000); Thread.sleep(1000);
p.merge("squash merge", null, GHPullRequest.MergeMethod.SQUASH); p.merge("squash merge", null, GHPullRequest.MergeMethod.SQUASH);
} }
@@ -360,8 +353,8 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
String name = "updateContentSquashMerge"; String name = "updateContentSquashMerge";
String branchName = "test/" + name; String branchName = "test/" + name;
GHRef masterRef = getRepository().getRef("heads/master"); GHRef mainRef = getRepository().getRef("heads/main");
GHRef branchRef = getRepository().createRef("refs/heads/" + branchName, masterRef.getObject().getSha()); GHRef branchRef = getRepository().createRef("refs/heads/" + branchName, mainRef.getObject().getSha());
GHContentUpdateResponse response = getRepository().createContent(name, name, name, branchName); GHContentUpdateResponse response = getRepository().createContent(name, name, name, branchName);
Thread.sleep(1000); Thread.sleep(1000);
@@ -373,7 +366,7 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
.message(name) .message(name)
.sha(response.getContent().getSha()) .sha(response.getContent().getSha())
.commit(); .commit();
GHPullRequest p = getRepository().createPullRequest(name, branchName, "master", "## test squash"); GHPullRequest p = getRepository().createPullRequest(name, branchName, "main", "## test squash");
Thread.sleep(1000); Thread.sleep(1000);
p.merge("squash merge", null, GHPullRequest.MergeMethod.SQUASH); p.merge("squash merge", null, GHPullRequest.MergeMethod.SQUASH);
} }
@@ -381,81 +374,84 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
@Test @Test
public void queryPullRequestsQualifiedHead() throws Exception { public void queryPullRequestsQualifiedHead() throws Exception {
GHRepository repo = getRepository(); GHRepository repo = getRepository();
// Create PRs from two different branches to master // Create PRs from two different branches to main
repo.createPullRequest("queryPullRequestsQualifiedHead_stable", "test/stable", "master", null); repo.createPullRequest("queryPullRequestsQualifiedHead_stable", "test/stable", "main", null);
repo.createPullRequest("queryPullRequestsQualifiedHead_rc", "test/rc", "master", null); repo.createPullRequest("queryPullRequestsQualifiedHead_rc", "test/rc", "main", null);
// Query by one of the heads and make sure we only get that branch's PR back. // Query by one of the heads and make sure we only get that branch's PR back.
List<GHPullRequest> prs = repo.queryPullRequests() List<GHPullRequest> prs = repo.queryPullRequests()
.state(GHIssueState.OPEN) .state(GHIssueState.OPEN)
.head("hub4j-test-org:test/stable") .head("hub4j-test-org:test/stable")
.base("master") .base("main")
.list() .list()
.toList(); .toList();
assertNotNull(prs); assertThat(prs, notNullValue());
assertEquals(1, prs.size()); assertThat(prs.size(), equalTo(1));
assertEquals("test/stable", prs.get(0).getHead().getRef()); assertThat(prs.get(0).getHead().getRef(), equalTo("test/stable"));
} }
@Test @Test
public void queryPullRequestsUnqualifiedHead() throws Exception { public void queryPullRequestsUnqualifiedHead() throws Exception {
GHRepository repo = getRepository(); GHRepository repo = getRepository();
// Create PRs from two different branches to master // Create PRs from two different branches to main
repo.createPullRequest("queryPullRequestsUnqualifiedHead_stable", "test/stable", "master", null); repo.createPullRequest("queryPullRequestsUnqualifiedHead_stable", "test/stable", "main", null);
repo.createPullRequest("queryPullRequestsUnqualifiedHead_rc", "test/rc", "master", null); repo.createPullRequest("queryPullRequestsUnqualifiedHead_rc", "test/rc", "main", null);
// Query by one of the heads and make sure we only get that branch's PR back. // Query by one of the heads and make sure we only get that branch's PR back.
List<GHPullRequest> prs = repo.queryPullRequests() List<GHPullRequest> prs = repo.queryPullRequests()
.state(GHIssueState.OPEN) .state(GHIssueState.OPEN)
.head("test/stable") .head("test/stable")
.base("master") .base("main")
.list() .list()
.toList(); .toList();
assertNotNull(prs); assertThat(prs, notNullValue());
assertEquals(1, prs.size()); assertThat(prs.size(), equalTo(1));
assertEquals("test/stable", prs.get(0).getHead().getRef()); assertThat(prs.get(0).getHead().getRef(), equalTo("test/stable"));
} }
@Test @Test
// Requires push access to the test repo to pass // Requires push access to the test repo to pass
public void setLabels() throws Exception { public void setLabels() throws Exception {
GHPullRequest p = getRepository().createPullRequest("setLabels", "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest("setLabels", "test/stable", "main", "## test");
String label = "setLabels_label_name"; String label = "setLabels_label_name";
p.setLabels(label); p.setLabels(label);
Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels(); Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels();
assertEquals(1, labels.size()); assertThat(labels.size(), equalTo(1));
GHLabel savedLabel = labels.iterator().next(); GHLabel savedLabel = labels.iterator().next();
assertEquals(label, savedLabel.getName()); assertThat(savedLabel.getName(), equalTo(label));
assertNotNull(savedLabel.getId()); assertThat(savedLabel.getId(), notNullValue());
assertNotNull(savedLabel.getNodeId()); assertThat(savedLabel.getNodeId(), notNullValue());
assertFalse(savedLabel.isDefault()); assertThat(savedLabel.isDefault(), is(false));
} }
@Test @Test
// Requires push access to the test repo to pass // Requires push access to the test repo to pass
public void addLabels() throws Exception { public void addLabels() throws Exception {
GHPullRequest p = getRepository().createPullRequest("addLabels", "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest("addLabels", "test/stable", "main", "## test");
String addedLabel1 = "addLabels_label_name_1"; String addedLabel1 = "addLabels_label_name_1";
String addedLabel2 = "addLabels_label_name_2"; String addedLabel2 = "addLabels_label_name_2";
String addedLabel3 = "addLabels_label_name_3"; String addedLabel3 = "addLabels_label_name_3";
p.addLabels(addedLabel1); List<GHLabel> resultingLabels = p.addLabels(addedLabel1);
assertThat(resultingLabels.size(), equalTo(1));
GHLabel ghLabel = resultingLabels.get(0);
assertThat(ghLabel.getName(), equalTo(addedLabel1));
int requestCount = mockGitHub.getRequestCount(); int requestCount = mockGitHub.getRequestCount();
p.addLabels(addedLabel2, addedLabel3); resultingLabels = p.addLabels(addedLabel2, addedLabel3);
// multiple labels can be added with one api call // multiple labels can be added with one api call
assertThat(mockGitHub.getRequestCount(), equalTo(requestCount + 1)); assertThat(mockGitHub.getRequestCount(), equalTo(requestCount + 1));
Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels(); assertThat(resultingLabels.size(), equalTo(3));
assertEquals(3, labels.size()); assertThat(resultingLabels,
assertThat(labels,
containsInAnyOrder(hasProperty("name", equalTo(addedLabel1)), containsInAnyOrder(hasProperty("name", equalTo(addedLabel1)),
hasProperty("name", equalTo(addedLabel2)), hasProperty("name", equalTo(addedLabel2)),
hasProperty("name", equalTo(addedLabel3)))); hasProperty("name", equalTo(addedLabel3))));
// Adding a label which is already present does not throw an error // Adding a label which is already present does not throw an error
p.addLabels(addedLabel1); resultingLabels = p.addLabels(ghLabel);
assertThat(resultingLabels.size(), equalTo(3));
} }
@Test @Test
@@ -465,16 +461,15 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
String addedLabel2 = "addLabelsConcurrencyIssue_label_name_2"; String addedLabel2 = "addLabelsConcurrencyIssue_label_name_2";
GHPullRequest p1 = getRepository() GHPullRequest p1 = getRepository()
.createPullRequest("addLabelsConcurrencyIssue", "test/stable", "master", "## test"); .createPullRequest("addLabelsConcurrencyIssue", "test/stable", "main", "## test");
p1.getLabels(); p1.getLabels();
GHPullRequest p2 = getRepository().getPullRequest(p1.getNumber()); GHPullRequest p2 = getRepository().getPullRequest(p1.getNumber());
p2.addLabels(addedLabel2); p2.addLabels(addedLabel2);
p1.addLabels(addedLabel1); Collection<GHLabel> labels = p1.addLabels(addedLabel1);
Collection<GHLabel> labels = getRepository().getPullRequest(p1.getNumber()).getLabels(); assertThat(labels.size(), equalTo(2));
assertEquals(2, labels.size());
assertThat(labels, assertThat(labels,
containsInAnyOrder(hasProperty("name", equalTo(addedLabel1)), containsInAnyOrder(hasProperty("name", equalTo(addedLabel1)),
hasProperty("name", equalTo(addedLabel2)))); hasProperty("name", equalTo(addedLabel2))));
@@ -483,27 +478,27 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
@Test @Test
// Requires push access to the test repo to pass // Requires push access to the test repo to pass
public void removeLabels() throws Exception { public void removeLabels() throws Exception {
GHPullRequest p = getRepository().createPullRequest("removeLabels", "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest("removeLabels", "test/stable", "main", "## test");
String label1 = "removeLabels_label_name_1"; String label1 = "removeLabels_label_name_1";
String label2 = "removeLabels_label_name_2"; String label2 = "removeLabels_label_name_2";
String label3 = "removeLabels_label_name_3"; String label3 = "removeLabels_label_name_3";
p.setLabels(label1, label2, label3); p.setLabels(label1, label2, label3);
Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels(); Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels();
assertEquals(3, labels.size()); assertThat(labels.size(), equalTo(3));
GHLabel ghLabel3 = labels.stream().filter(label -> label3.equals(label.getName())).findFirst().get();
int requestCount = mockGitHub.getRequestCount(); int requestCount = mockGitHub.getRequestCount();
p.removeLabels(label2, label3); List<GHLabel> resultingLabels = p.removeLabels(label2, label3);
// each label deleted is a separate api call // each label deleted is a separate api call
assertThat(mockGitHub.getRequestCount(), equalTo(requestCount + 2)); assertThat(mockGitHub.getRequestCount(), equalTo(requestCount + 2));
labels = getRepository().getPullRequest(p.getNumber()).getLabels(); assertThat(resultingLabels.size(), equalTo(1));
assertEquals(1, labels.size()); assertThat(resultingLabels.get(0).getName(), equalTo(label1));
assertEquals(label1, labels.iterator().next().getName());
// Removing some labels that are not present does not throw // Removing some labels that are not present does not throw
// This is consistent with earlier behavior and with addLabels() // This is consistent with earlier behavior and with addLabels()
p.removeLabels(label3); p.removeLabels(ghLabel3);
// Calling removeLabel() on label that is not present will throw // Calling removeLabel() on label that is not present will throw
try { try {
@@ -517,26 +512,26 @@ public class GHPullRequestTest extends AbstractGitHubWireMockTest {
@Test @Test
// Requires push access to the test repo to pass // Requires push access to the test repo to pass
public void setAssignee() throws Exception { public void setAssignee() throws Exception {
GHPullRequest p = getRepository().createPullRequest("setAssignee", "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest("setAssignee", "test/stable", "main", "## test");
GHMyself user = gitHub.getMyself(); GHMyself user = gitHub.getMyself();
p.assignTo(user); p.assignTo(user);
assertEquals(user, getRepository().getPullRequest(p.getNumber()).getAssignee()); assertThat(getRepository().getPullRequest(p.getNumber()).getAssignee(), equalTo(user));
} }
@Test @Test
public void getUserTest() throws IOException { public void getUserTest() throws IOException {
GHPullRequest p = getRepository().createPullRequest("getUserTest", "test/stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest("getUserTest", "test/stable", "main", "## test");
GHPullRequest prSingle = getRepository().getPullRequest(p.getNumber()); GHPullRequest prSingle = getRepository().getPullRequest(p.getNumber());
assertNotNull(prSingle.getUser().getRoot()); assertThat(prSingle.getUser().getRoot(), notNullValue());
prSingle.getMergeable(); prSingle.getMergeable();
assertNotNull(prSingle.getUser().getRoot()); assertThat(prSingle.getUser().getRoot(), notNullValue());
PagedIterable<GHPullRequest> ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN); PagedIterable<GHPullRequest> ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN);
for (GHPullRequest pr : ghPullRequests) { for (GHPullRequest pr : ghPullRequests) {
assertNotNull(pr.getUser().getRoot()); assertThat(pr.getUser().getRoot(), notNullValue());
pr.getMergeable(); pr.getMergeable();
assertNotNull(pr.getUser().getRoot()); assertThat(pr.getUser().getRoot(), notNullValue());
} }
} }

View File

@@ -493,7 +493,7 @@ public class GHRateLimitTest extends AbstractGitHubWireMockTest {
// This time, rateLimit() should find an expired record and get a new one. // This time, rateLimit() should find an expired record and get a new one.
Thread.sleep(2500); Thread.sleep(2500);
assertThat("Header instance has expired", gitHub.lastRateLimit().isExpired(), is(true)); assertThat("Header instance has expired", gitHub.lastRateLimit().isExpired());
assertThat("rateLimit() will ask server when cached instance has expired", assertThat("rateLimit() will ask server when cached instance has expired",
gitHub.rateLimit(), gitHub.rateLimit(),

View File

@@ -6,6 +6,8 @@ import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import static org.hamcrest.Matchers.equalTo;
public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest { public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest {
public static int MAX_ITERATIONS = 3; public static int MAX_ITERATIONS = 3;
@@ -25,7 +27,7 @@ public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest {
// check the statistics are accurate // check the statistics are accurate
List<GHRepositoryStatistics.ContributorStats> list = stats.toList(); List<GHRepositoryStatistics.ContributorStats> list = stats.toList();
assertEquals(99, list.size()); assertThat(list.size(), equalTo(99));
// find a particular developer // find a particular developer
// TODO: Add an accessor method for this instead of having use a loop. // TODO: Add an accessor method for this instead of having use a loop.
@@ -33,22 +35,22 @@ public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest {
final String authorLogin = "kohsuke"; final String authorLogin = "kohsuke";
for (GHRepositoryStatistics.ContributorStats statsForAuthor : list) { for (GHRepositoryStatistics.ContributorStats statsForAuthor : list) {
if (authorLogin.equals(statsForAuthor.getAuthor().getLogin())) { if (authorLogin.equals(statsForAuthor.getAuthor().getLogin())) {
assertEquals(715, statsForAuthor.getTotal()); assertThat(statsForAuthor.getTotal(), equalTo(715));
assertEquals("kohsuke made 715 contributions over 494 weeks", statsForAuthor.toString()); assertThat(statsForAuthor.toString(), equalTo("kohsuke made 715 contributions over 494 weeks"));
List<GHRepositoryStatistics.ContributorStats.Week> weeks = statsForAuthor.getWeeks(); List<GHRepositoryStatistics.ContributorStats.Week> weeks = statsForAuthor.getWeeks();
assertEquals(494, weeks.size()); assertThat(weeks.size(), equalTo(494));
try { try {
// check a particular week // check a particular week
// TODO: Maybe add a convenience method to get the week // TODO: Maybe add a convenience method to get the week
// containing a certain date (Java.Util.Date). // containing a certain date (Java.Util.Date).
GHRepositoryStatistics.ContributorStats.Week week = statsForAuthor.getWeek(1541289600); GHRepositoryStatistics.ContributorStats.Week week = statsForAuthor.getWeek(1541289600);
assertEquals(63, week.getNumberOfAdditions()); assertThat(week.getNumberOfAdditions(), equalTo(63));
assertEquals(56, week.getNumberOfDeletions()); assertThat(week.getNumberOfDeletions(), equalTo(56));
assertEquals(5, week.getNumberOfCommits()); assertThat(week.getNumberOfCommits(), equalTo(5));
assertEquals("Week starting 1541289600 - Additions: 63, Deletions: 56, Commits: 5", assertThat(week.toString(),
week.toString()); equalTo("Week starting 1541289600 - Additions: 63, Deletions: 56, Commits: 5"));
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
fail("Did not find week 1546128000"); fail("Did not find week 1546128000");
} }
@@ -57,7 +59,7 @@ public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest {
} }
} }
assertTrue("Did not find author " + authorLogin, developerFound); assertThat("Did not find author " + authorLogin, developerFound);
} }
@Test @Test
@@ -89,20 +91,20 @@ public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest {
Boolean foundWeek = false; Boolean foundWeek = false;
for (GHRepositoryStatistics.CommitActivity item : list) { for (GHRepositoryStatistics.CommitActivity item : list) {
if (item.getWeek() == 1566691200) { if (item.getWeek() == 1566691200) {
assertEquals(6, item.getTotal()); assertThat(item.getTotal(), equalTo(6));
List<Integer> days = item.getDays(); List<Integer> days = item.getDays();
assertEquals(0, (long) days.get(0)); assertThat((long) days.get(0), equalTo(0L));
assertEquals(0, (long) days.get(1)); assertThat((long) days.get(1), equalTo(0L));
assertEquals(1, (long) days.get(2)); assertThat((long) days.get(2), equalTo(1L));
assertEquals(0, (long) days.get(3)); assertThat((long) days.get(3), equalTo(0L));
assertEquals(0, (long) days.get(4)); assertThat((long) days.get(4), equalTo(0L));
assertEquals(1, (long) days.get(5)); assertThat((long) days.get(5), equalTo(1L));
assertEquals(4, (long) days.get(6)); assertThat((long) days.get(6), equalTo(4L));
foundWeek = true; foundWeek = true;
break; break;
} }
} }
assertTrue("Could not find week starting 1546128000", foundWeek); assertThat("Could not find week starting 1546128000", foundWeek);
} }
@Test @Test
@@ -132,14 +134,14 @@ public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest {
Boolean foundWeek = false; Boolean foundWeek = false;
for (GHRepositoryStatistics.CodeFrequency item : stats) { for (GHRepositoryStatistics.CodeFrequency item : stats) {
if (item.getWeekTimestamp() == 1535241600) { if (item.getWeekTimestamp() == 1535241600) {
assertEquals(185, item.getAdditions()); assertThat(item.getAdditions(), equalTo(185L));
assertEquals(-243, item.getDeletions()); assertThat(item.getDeletions(), equalTo(-243L));
assertEquals("Week starting 1535241600 has 185 additions and 243 deletions", item.toString()); assertThat(item.toString(), equalTo("Week starting 1535241600 has 185 additions and 243 deletions"));
foundWeek = true; foundWeek = true;
break; break;
} }
} }
assertTrue("Could not find week starting 1535241600", foundWeek); assertThat("Could not find week starting 1535241600", foundWeek);
} }
@Test @Test
@@ -164,11 +166,11 @@ public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest {
// check the statistics are accurate // check the statistics are accurate
List<Integer> allCommits = stats.getAllCommits(); List<Integer> allCommits = stats.getAllCommits();
assertEquals(52, allCommits.size()); assertThat(allCommits.size(), equalTo(52));
assertEquals(2, (int) allCommits.get(2)); assertThat((int) allCommits.get(2), equalTo(2));
List<Integer> ownerCommits = stats.getOwnerCommits(); List<Integer> ownerCommits = stats.getOwnerCommits();
assertEquals(52, ownerCommits.size()); assertThat(ownerCommits.size(), equalTo(52));
// The values depend on who is running the test. // The values depend on who is running the test.
} }
@@ -199,13 +201,13 @@ public class GHRepositoryStatisticsTest extends AbstractGitHubWireMockTest {
if (item.getDayOfWeek() == 2 && item.getHourOfDay() == 10) { if (item.getDayOfWeek() == 2 && item.getHourOfDay() == 10) {
// TODO: Make an easier access method. Perhaps wrap in an // TODO: Make an easier access method. Perhaps wrap in an
// object and have a method such as GetCommits(1, 16). // object and have a method such as GetCommits(1, 16).
assertEquals(16, item.getNumberOfCommits()); assertThat(item.getNumberOfCommits(), equalTo(16L));
assertEquals("Day 2 Hour 10: 16 commits", item.toString()); assertThat(item.toString(), equalTo("Day 2 Hour 10: 16 commits"));
hourFound = true; hourFound = true;
break; break;
} }
} }
assertTrue("Hour 10 for Day 2 not found.", hourFound); assertThat("Hour 10 for Day 2 not found.", hourFound);
} }
protected GHRepository getRepository() throws IOException { protected GHRepository getRepository() throws IOException {

View File

@@ -14,7 +14,9 @@ import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsInstanceOf.instanceOf;
@@ -109,7 +111,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
.getCommitShortInfo() .getCommitShortInfo()
.getVerification(); .getVerification();
assertEquals(GPGVERIFY_ERROR, verification.getReason()); assertThat(verification.getReason(), equalTo(GPGVERIFY_ERROR));
} }
@Test @Test
@@ -126,13 +128,13 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
.getCommitShortInfo() .getCommitShortInfo()
.getVerification(); .getVerification();
assertEquals(UNKNOWN_SIGNATURE_TYPE, verification.getReason()); assertThat(verification.getReason(), equalTo(UNKNOWN_SIGNATURE_TYPE));
} }
@Test @Test
public void listStargazers() throws IOException { public void listStargazers() throws IOException {
GHRepository repository = getRepository(); GHRepository repository = getRepository();
assertThat(repository.listStargazers2().toList(), empty()); assertThat(repository.listStargazers2().toList(), is(empty()));
repository = gitHub.getOrganization("hub4j").getRepository("github-api"); repository = gitHub.getOrganization("hub4j").getRepository("github-api");
Iterable<GHStargazer> stargazers = repository.listStargazers2(); Iterable<GHStargazer> stargazers = repository.listStargazers2();
@@ -166,11 +168,11 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
@Test @Test
public void subscription() throws Exception { public void subscription() throws Exception {
GHRepository r = getRepository(); GHRepository r = getRepository();
assertNull(r.getSubscription()); assertThat(r.getSubscription(), nullValue());
GHSubscription s = r.subscribe(true, false); GHSubscription s = r.subscribe(true, false);
try { try {
assertEquals(s.getRepository(), r); assertThat(r, equalTo(s.getRepository()));
assertThat(s.isIgnored(), equalTo(false)); assertThat(s.isIgnored(), equalTo(false));
assertThat(s.isSubscribed(), equalTo(true)); assertThat(s.isSubscribed(), equalTo(true));
assertThat(s.getRepositoryUrl().toString(), containsString("/repos/hub4j-test-org/github-api")); assertThat(s.getRepositoryUrl().toString(), containsString("/repos/hub4j-test-org/github-api"));
@@ -182,7 +184,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
s.delete(); s.delete();
} }
assertNull(r.getSubscription()); assertThat(r.getSubscription(), nullValue());
} }
@Test @Test
@@ -192,11 +194,11 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
String repoName = "test-repo-public"; String repoName = "test-repo-public";
GHRepository repo = gitHub.createRepository(repoName).private_(false).create(); GHRepository repo = gitHub.createRepository(repoName).private_(false).create();
try { try {
assertFalse(repo.isPrivate()); assertThat(repo.isPrivate(), is(false));
repo.setPrivate(true); repo.setPrivate(true);
assertTrue(myself.getRepository(repoName).isPrivate()); assertThat(myself.getRepository(repoName).isPrivate(), is(true));
repo.setPrivate(false); repo.setPrivate(false);
assertFalse(myself.getRepository(repoName).isPrivate()); assertThat(myself.getRepository(repoName).isPrivate(), is(false));
} finally { } finally {
repo.delete(); repo.delete();
} }
@@ -224,25 +226,25 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
.wiki(false) .wiki(false)
.done(); .done();
assertTrue(updated.isAllowMergeCommit()); assertThat(updated.isAllowMergeCommit(), is(true));
assertFalse(updated.isAllowRebaseMerge()); assertThat(updated.isAllowRebaseMerge(), is(false));
assertFalse(updated.isAllowSquashMerge()); assertThat(updated.isAllowSquashMerge(), is(false));
assertTrue(updated.isDeleteBranchOnMerge()); assertThat(updated.isDeleteBranchOnMerge(), is(true));
assertTrue(updated.isPrivate()); assertThat(updated.isPrivate(), is(true));
assertFalse(updated.hasDownloads()); assertThat(updated.hasDownloads(), is(false));
assertFalse(updated.hasIssues()); assertThat(updated.hasIssues(), is(false));
assertFalse(updated.hasProjects()); assertThat(updated.hasProjects(), is(false));
assertFalse(updated.hasWiki()); assertThat(updated.hasWiki(), is(false));
assertEquals(homepage, updated.getHomepage()); assertThat(updated.getHomepage(), equalTo(homepage));
assertEquals(description, updated.getDescription()); assertThat(updated.getDescription(), equalTo(description));
// test the other merge option and making the repo public again // test the other merge option and making the repo public again
GHRepository redux = updated.update().allowMergeCommit(false).allowRebaseMerge(true).private_(false).done(); GHRepository redux = updated.update().allowMergeCommit(false).allowRebaseMerge(true).private_(false).done();
assertFalse(redux.isAllowMergeCommit()); assertThat(redux.isAllowMergeCommit(), is(false));
assertTrue(redux.isAllowRebaseMerge()); assertThat(redux.isAllowRebaseMerge(), is(true));
assertFalse(redux.isPrivate()); assertThat(redux.isPrivate(), is(false));
String updatedDescription = "updated using set()"; String updatedDescription = "updated using set()";
redux = redux.set().description(updatedDescription); redux = redux.set().description(updatedDescription);
@@ -255,23 +257,23 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
snapshotNotAllowed(); snapshotNotAllowed();
final String repoName = "test-repo-visibility"; final String repoName = "test-repo-visibility";
final GHRepository repo = getTempRepository(repoName); final GHRepository repo = getTempRepository(repoName);
assertEquals(Visibility.PUBLIC, repo.getVisibility()); assertThat(repo.getVisibility(), equalTo(Visibility.PUBLIC));
repo.setVisibility(Visibility.INTERNAL); repo.setVisibility(Visibility.INTERNAL);
assertEquals(Visibility.INTERNAL, assertThat(gitHub.getRepository(repo.getOwnerName() + "/" + repo.getName()).getVisibility(),
gitHub.getRepository(repo.getOwnerName() + "/" + repo.getName()).getVisibility()); equalTo(Visibility.INTERNAL));
repo.setVisibility(Visibility.PRIVATE); repo.setVisibility(Visibility.PRIVATE);
assertEquals(Visibility.PRIVATE, assertThat(gitHub.getRepository(repo.getOwnerName() + "/" + repo.getName()).getVisibility(),
gitHub.getRepository(repo.getOwnerName() + "/" + repo.getName()).getVisibility()); equalTo(Visibility.PRIVATE));
repo.setVisibility(Visibility.PUBLIC); repo.setVisibility(Visibility.PUBLIC);
assertEquals(Visibility.PUBLIC, assertThat(gitHub.getRepository(repo.getOwnerName() + "/" + repo.getName()).getVisibility(),
gitHub.getRepository(repo.getOwnerName() + "/" + repo.getName()).getVisibility()); equalTo(Visibility.PUBLIC));
// deliberately bogus response in snapshot // deliberately bogus response in snapshot
assertEquals(Visibility.UNKNOWN, assertThat(gitHub.getRepository(repo.getOwnerName() + "/" + repo.getName()).getVisibility(),
gitHub.getRepository(repo.getOwnerName() + "/" + repo.getName()).getVisibility()); equalTo(Visibility.UNKNOWN));
} }
@Test @Test
@@ -282,7 +284,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
for (GHRepository.Contributor c : r.listContributors()) { for (GHRepository.Contributor c : r.listContributors()) {
if (c.getLogin().equals("kohsuke")) { if (c.getLogin().equals("kohsuke")) {
assertTrue(c.getContributions() > 0); assertThat(c.getContributions(), greaterThan(0));
kohsuke = true; kohsuke = true;
} }
if (i++ > 5) { if (i++ > 5) {
@@ -290,22 +292,22 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
} }
} }
assertTrue(kohsuke); assertThat(kohsuke, is(true));
} }
@Test @Test
public void getPermission() throws Exception { public void getPermission() throws Exception {
kohsuke(); kohsuke();
GHRepository r = gitHub.getRepository("hub4j-test-org/test-permission"); GHRepository r = gitHub.getRepository("hub4j-test-org/test-permission");
assertEquals(GHPermissionType.ADMIN, r.getPermission("kohsuke")); assertThat(r.getPermission("kohsuke"), equalTo(GHPermissionType.ADMIN));
assertEquals(GHPermissionType.READ, r.getPermission("dude")); assertThat(r.getPermission("dude"), equalTo(GHPermissionType.READ));
r = gitHub.getOrganization("apache").getRepository("groovy"); r = gitHub.getOrganization("apache").getRepository("groovy");
try { try {
r.getPermission("jglick"); r.getPermission("jglick");
fail(); fail();
} catch (HttpException x) { } catch (HttpException x) {
// x.printStackTrace(); // good // x.printStackTrace(); // good
assertEquals(403, x.getResponseCode()); assertThat(x.getResponseCode(), equalTo(403));
} }
if (false) { if (false) {
@@ -325,7 +327,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
try { try {
// add the repository that have latest release // add the repository that have latest release
GHRelease release = gitHub.getRepository("kamontat/CheckIDNumber").getLatestRelease(); GHRelease release = gitHub.getRepository("kamontat/CheckIDNumber").getLatestRelease();
assertEquals("v3.0", release.getTagName()); assertThat(release.getTagName(), equalTo("v3.0"));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
fail(); fail();
@@ -346,7 +348,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
GHUser colabUser = collabs.byLogin("jimmysombrero"); GHUser colabUser = collabs.byLogin("jimmysombrero");
assertEquals(colabUser.getName(), user.getName()); assertThat(user.getName(), equalTo(colabUser.getName()));
} }
@Test @Test
@@ -354,7 +356,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
try { try {
// add the repository that `NOT` have latest release // add the repository that `NOT` have latest release
GHRelease release = gitHub.getRepository("kamontat/Java8Example").getLatestRelease(); GHRelease release = gitHub.getRepository("kamontat/Java8Example").getLatestRelease();
assertNull(release); assertThat(release, nullValue());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
fail(); fail();
@@ -364,39 +366,42 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
@Test @Test
public void listReleases() throws IOException { public void listReleases() throws IOException {
PagedIterable<GHRelease> releases = gitHub.getOrganization("github").getRepository("hub").listReleases(); PagedIterable<GHRelease> releases = gitHub.getOrganization("github").getRepository("hub").listReleases();
assertTrue(releases.iterator().hasNext()); assertThat(releases, is(not(emptyIterable())));
} }
@Test @Test
public void getReleaseExists() throws IOException { public void getReleaseExists() throws IOException {
GHRelease release = gitHub.getOrganization("github").getRepository("hub").getRelease(6839710); GHRelease release = gitHub.getOrganization("github").getRepository("hub").getRelease(6839710);
assertEquals("v2.3.0-pre10", release.getTagName()); assertThat(release.getTagName(), equalTo("v2.3.0-pre10"));
} }
@Test @Test
public void getReleaseDoesNotExist() throws IOException { public void getReleaseDoesNotExist() throws IOException {
GHRelease release = gitHub.getOrganization("github").getRepository("hub").getRelease(Long.MAX_VALUE); GHRelease release = gitHub.getOrganization("github").getRepository("hub").getRelease(Long.MAX_VALUE);
assertNull(release); assertThat(release, nullValue());
} }
@Test @Test
public void getReleaseByTagNameExists() throws IOException { public void getReleaseByTagNameExists() throws IOException {
GHRelease release = gitHub.getOrganization("github").getRepository("hub").getReleaseByTagName("v2.3.0-pre10"); GHRelease release = gitHub.getOrganization("github").getRepository("hub").getReleaseByTagName("v2.3.0-pre10");
assertNotNull(release); assertThat(release, notNullValue());
assertEquals("v2.3.0-pre10", release.getTagName()); assertThat(release.getTagName(), equalTo("v2.3.0-pre10"));
} }
@Test @Test
public void getReleaseByTagNameDoesNotExist() throws IOException { public void getReleaseByTagNameDoesNotExist() throws IOException {
GHRelease release = getRepository().getReleaseByTagName("foo-bar-baz"); GHRelease release = getRepository().getReleaseByTagName("foo-bar-baz");
assertNull(release); assertThat(release, nullValue());
} }
@Test @Test
public void listLanguages() throws IOException { public void listLanguages() throws IOException {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
String mainLanguage = r.getLanguage(); String mainLanguage = r.getLanguage();
assertTrue(r.listLanguages().containsKey(mainLanguage)); assertThat(mainLanguage, equalTo("Java"));
Map<String, Long> languages = r.listLanguages();
assertThat(languages.containsKey(mainLanguage), is(true));
assertThat(languages.get("Java"), greaterThan(100000L));
} }
@Test @Test
@@ -414,17 +419,17 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
.listCommitComments("499d91f9f846b0087b2a20cf3648b49dc9c2eeef") .listCommitComments("499d91f9f846b0087b2a20cf3648b49dc9c2eeef")
.toList(); .toList();
assertThat("Two comments present", commitComments.size() == 2); assertThat("Two comments present", commitComments.size(), equalTo(2));
assertThat("Comment text found", commitComments.stream().anyMatch(it -> it.body.equals("comment 1"))); assertThat("Comment text found",
assertThat("Comment text found", commitComments.stream().anyMatch(it -> it.body.equals("comment 2"))); commitComments.stream().map(GHCommitComment::getBody).collect(Collectors.toList()),
containsInAnyOrder("comment 1", "comment 2"));
} }
@Test // Issue #261 @Test // Issue #261
public void listEmptyContributors() throws IOException { public void listEmptyContributors() throws IOException {
for (GHRepository.Contributor c : gitHub.getRepository(GITHUB_API_TEST_ORG + "/empty").listContributors()) { assertThat("This list should be empty, but should return a valid empty iterable.",
// System.out.println(c); gitHub.getRepository(GITHUB_API_TEST_ORG + "/empty").listContributors(),
fail("This list should be empty, but should return a valid empty iterable."); is(emptyIterable()));
}
} }
@Test @Test
@@ -436,9 +441,9 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
.list(); .list();
GHRepository u = r.iterator().next(); GHRepository u = r.iterator().next();
// System.out.println(u.getName()); // System.out.println(u.getName());
assertNotNull(u.getId()); assertThat(u.getId(), notNullValue());
assertEquals("Assembly", u.getLanguage()); assertThat(u.getLanguage(), equalTo("Assembly"));
assertTrue(r.getTotalCount() > 0); assertThat(r.getTotalCount(), greaterThan(0));
} }
@Test // issue #162 @Test // issue #162
@@ -450,23 +455,24 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
String content1 = content.getContent(); String content1 = content.getContent();
String content2 = r.getFileContent(content.getPath(), "gh-pages").getContent(); String content2 = r.getFileContent(content.getPath(), "gh-pages").getContent();
// System.out.println(content.getPath()); // System.out.println(content.getPath());
assertEquals(content1, content2); assertThat(content2, equalTo(content1));
} }
} }
} }
@Test @Test
public void markDown() throws Exception { public void markDown() throws Exception {
assertEquals("<p><strong>Test日本語</strong></p>", IOUtils.toString(gitHub.renderMarkdown("**Test日本語**")).trim()); assertThat(IOUtils.toString(gitHub.renderMarkdown("**Test日本語**")).trim(),
equalTo("<p><strong>Test日本語</strong></p>"));
String actual = IOUtils.toString( String actual = IOUtils.toString(
gitHub.getRepository("hub4j/github-api").renderMarkdown("@kohsuke to fix issue #1", MarkdownMode.GFM)); gitHub.getRepository("hub4j/github-api").renderMarkdown("@kohsuke to fix issue #1", MarkdownMode.GFM));
// System.out.println(actual); // System.out.println(actual);
assertTrue(actual.contains("href=\"https://github.com/kohsuke\"")); assertThat(actual, containsString("href=\"https://github.com/kohsuke\""));
assertTrue(actual.contains("href=\"https://github.com/hub4j/github-api/pull/1\"")); assertThat(actual, containsString("href=\"https://github.com/hub4j/github-api/pull/1\""));
assertTrue(actual.contains("class=\"user-mention\"")); assertThat(actual, containsString("class=\"user-mention\""));
assertTrue(actual.contains("class=\"issue-link ")); assertThat(actual, containsString("class=\"issue-link "));
assertTrue(actual.contains("to fix issue")); assertThat(actual, containsString("to fix issue"));
} }
@Test @Test
@@ -482,9 +488,9 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
r.allowRebaseMerge(false); r.allowRebaseMerge(false);
r = gitHub.getRepository(r.getFullName()); r = gitHub.getRepository(r.getFullName());
assertFalse(r.isAllowMergeCommit()); assertThat(r.isAllowMergeCommit(), is(false));
assertFalse(r.isAllowRebaseMerge()); assertThat(r.isAllowRebaseMerge(), is(false));
assertTrue(r.isAllowSquashMerge()); assertThat(r.isAllowSquashMerge(), is(true));
// flip the last value // flip the last value
r.allowMergeCommit(true); r.allowMergeCommit(true);
@@ -492,15 +498,15 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
r.allowSquashMerge(false); r.allowSquashMerge(false);
r = gitHub.getRepository(r.getFullName()); r = gitHub.getRepository(r.getFullName());
assertTrue(r.isAllowMergeCommit()); assertThat(r.isAllowMergeCommit(), is(true));
assertTrue(r.isAllowRebaseMerge()); assertThat(r.isAllowRebaseMerge(), is(true));
assertFalse(r.isAllowSquashMerge()); assertThat(r.isAllowSquashMerge(), is(false));
} }
@Test @Test
public void getDeleteBranchOnMerge() throws IOException { public void getDeleteBranchOnMerge() throws IOException {
GHRepository r = getRepository(); GHRepository r = getRepository();
assertNotNull(r.isDeleteBranchOnMerge()); assertThat(r.isDeleteBranchOnMerge(), notNullValue());
} }
@Test @Test
@@ -511,13 +517,13 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
r.deleteBranchOnMerge(true); r.deleteBranchOnMerge(true);
r = gitHub.getRepository(r.getFullName()); r = gitHub.getRepository(r.getFullName());
assertTrue(r.isDeleteBranchOnMerge()); assertThat(r.isDeleteBranchOnMerge(), is(true));
// flip the last value // flip the last value
r.deleteBranchOnMerge(false); r.deleteBranchOnMerge(false);
r = gitHub.getRepository(r.getFullName()); r = gitHub.getRepository(r.getFullName());
assertFalse(r.isDeleteBranchOnMerge()); assertThat(r.isDeleteBranchOnMerge(), is(false));
} }
@Test @Test
@@ -552,7 +558,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
topics = new ArrayList<>(); topics = new ArrayList<>();
repo.setTopics(topics); repo.setTopics(topics);
assertTrue("Topics can be set to empty", repo.listTopics().isEmpty()); assertThat("Topics can be set to empty", repo.listTopics(), is(empty()));
} }
@Test @Test
@@ -566,7 +572,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
public void getPostCommitHooks() throws Exception { public void getPostCommitHooks() throws Exception {
GHRepository repo = getRepository(gitHub); GHRepository repo = getRepository(gitHub);
Set<URL> postcommitHooks = repo.getPostCommitHooks(); Set<URL> postcommitHooks = repo.getPostCommitHooks();
assertThat(postcommitHooks.size(), equalTo(0)); assertThat(postcommitHooks, is(empty()));
} }
@Test @Test
@@ -575,7 +581,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
GHRef[] refs = repo.getRefs(); GHRef[] refs = repo.getRefs();
assertThat(refs, notNullValue()); assertThat(refs, notNullValue());
assertThat(refs.length, equalTo(1)); assertThat(refs.length, equalTo(1));
assertThat(refs[0].getRef(), equalTo("refs/heads/master")); assertThat(refs[0].getRef(), equalTo("refs/heads/main"));
} }
@Test @Test
@@ -584,7 +590,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
GHRef[] refs = repo.getRefs("heads"); GHRef[] refs = repo.getRefs("heads");
assertThat(refs, notNullValue()); assertThat(refs, notNullValue());
assertThat(refs.length, equalTo(1)); assertThat(refs.length, equalTo(1));
assertThat(refs[0].getRef(), equalTo("refs/heads/master")); assertThat(refs[0].getRef(), equalTo("refs/heads/main"));
} }
@Test @Test
@@ -693,7 +699,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
List<GHRef> refs = repo.listRefs("heads").toList(); List<GHRef> refs = repo.listRefs("heads").toList();
assertThat(refs, notNullValue()); assertThat(refs, notNullValue());
assertThat(refs.size(), equalTo(1)); assertThat(refs.size(), equalTo(1));
assertThat(refs.get(0).getRef(), equalTo("refs/heads/master")); assertThat(refs.get(0).getRef(), equalTo("refs/heads/main"));
} }
@Test @Test
@@ -713,7 +719,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
GHRepository repo = getTempRepository(); GHRepository repo = getTempRepository();
List<GHTag> refs = repo.listTags().toList(); List<GHTag> refs = repo.listTags().toList();
assertThat(refs, notNullValue()); assertThat(refs, notNullValue());
assertThat(refs.size(), equalTo(0)); assertThat(refs, is(empty()));
} }
@Test @Test
@@ -729,7 +735,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
snapshotNotAllowed(); snapshotNotAllowed();
GHRepository repo = getTempRepository(); GHRepository repo = getTempRepository();
int watchersCount = repo.getWatchersCount(); int watchersCount = repo.getWatchersCount();
assertEquals(10, watchersCount); assertThat(watchersCount, equalTo(10));
} }
@Test @Test
@@ -737,7 +743,7 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
snapshotNotAllowed(); snapshotNotAllowed();
GHRepository repo = getTempRepository(); GHRepository repo = getTempRepository();
int stargazersCount = repo.getStargazersCount(); int stargazersCount = repo.getStargazersCount();
assertEquals(10, stargazersCount); assertThat(stargazersCount, equalTo(10));
} }
@Test @Test
@@ -773,6 +779,11 @@ public class GHRepositoryTest extends AbstractGitHubWireMockTest {
checkRunsCount++; checkRunsCount++;
} }
assertThat(checkRunsCount, equalTo(expectedCount)); assertThat(checkRunsCount, equalTo(expectedCount));
// Check that we can call update on the results
for (GHCheckRun checkRun : checkRuns) {
checkRun.update();
}
} }
@Test @Test

View File

@@ -7,8 +7,6 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/** /**
* *
@@ -25,7 +23,7 @@ public class GHTagTest extends AbstractGitHubWireMockTest {
} }
try { try {
GHRef ref = getRepository(this.getGitHubBeforeAfter()).getRef("tags/create_tag_test"); GHRef ref = getRepository(this.getNonRecordingGitHub()).getRef("tags/create_tag_test");
if (ref != null) { if (ref != null) {
ref.delete(); ref.delete();
} }
@@ -45,11 +43,11 @@ public class GHTagTest extends AbstractGitHubWireMockTest {
String tagType = "commit"; String tagType = "commit";
GHTagObject tag = repo.createTag(tagName, tagMessage, commitSha, tagType); GHTagObject tag = repo.createTag(tagName, tagMessage, commitSha, tagType);
assertEquals(tagName, tag.getTag()); assertThat(tag.getTag(), equalTo(tagName));
assertEquals(tagMessage, tag.getMessage()); assertThat(tag.getMessage(), equalTo(tagMessage));
assertEquals(commitSha, tag.getObject().getSha()); assertThat(tag.getObject().getSha(), equalTo(commitSha));
assertFalse(tag.getVerification().isVerified()); assertThat(tag.getVerification().isVerified(), is(false));
assertEquals(tag.getVerification().getReason(), GHVerification.Reason.UNSIGNED); assertThat(GHVerification.Reason.UNSIGNED, equalTo(tag.getVerification().getReason()));
assertThat(tag.getUrl(), assertThat(tag.getUrl(),
containsString("/repos/hub4j-test-org/github-api/git/tags/e7aa6d4afbaa48669f0bbe11ca3c4d787b2b153c")); containsString("/repos/hub4j-test-org/github-api/git/tags/e7aa6d4afbaa48669f0bbe11ca3c4d787b2b153c"));
assertThat(tag.getOwner().getId(), equalTo(repo.getId())); assertThat(tag.getOwner().getId(), equalTo(repo.getId()));
@@ -57,7 +55,7 @@ public class GHTagTest extends AbstractGitHubWireMockTest {
// Make a reference to the newly created tag. // Make a reference to the newly created tag.
GHRef ref = repo.createRef("refs/tags/" + tagName, tag.getSha()); GHRef ref = repo.createRef("refs/tags/" + tagName, tag.getSha());
assertNotNull(ref); assertThat(ref, notNullValue());
} }
protected GHRepository getRepository() throws IOException { protected GHRepository getRepository() throws IOException {

View File

@@ -4,6 +4,8 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
public class GHTeamBuilderTest extends AbstractGitHubWireMockTest { public class GHTeamBuilderTest extends AbstractGitHubWireMockTest {
@Test @Test
@@ -23,10 +25,10 @@ public class GHTeamBuilderTest extends AbstractGitHubWireMockTest {
.parentTeamId(parentTeam.getId()) .parentTeamId(parentTeam.getId())
.create(); .create();
assertEquals(description, childTeam.getDescription()); assertThat(childTeam.getDescription(), equalTo(description));
assertEquals(childTeamSlug, childTeam.getName()); assertThat(childTeam.getName(), equalTo(childTeamSlug));
assertEquals(childTeamSlug, childTeam.getSlug()); assertThat(childTeam.getSlug(), equalTo(childTeamSlug));
assertEquals(GHTeam.Privacy.CLOSED, childTeam.getPrivacy()); assertThat(childTeam.getPrivacy(), equalTo(GHTeam.Privacy.CLOSED));
} }
} }

View File

@@ -7,7 +7,7 @@ import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static org.junit.Assert.assertEquals; import static org.hamcrest.Matchers.*;
public class GHTeamTest extends AbstractGitHubWireMockTest { public class GHTeamTest extends AbstractGitHubWireMockTest {
@@ -23,7 +23,7 @@ public class GHTeamTest extends AbstractGitHubWireMockTest {
// Check that it was set correctly. // Check that it was set correctly.
team = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug(teamSlug); team = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug(teamSlug);
assertEquals(description, team.getDescription()); assertThat(team.getDescription(), equalTo(description));
description += "Modified"; description += "Modified";
@@ -32,7 +32,7 @@ public class GHTeamTest extends AbstractGitHubWireMockTest {
// Check that it was set correctly. // Check that it was set correctly.
team = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug(teamSlug); team = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug(teamSlug);
assertEquals(description, team.getDescription()); assertThat(team.getDescription(), equalTo(description));
} }
@Test @Test
@@ -43,8 +43,8 @@ public class GHTeamTest extends AbstractGitHubWireMockTest {
List<GHUser> admins = team.listMembers("admin").toList(); List<GHUser> admins = team.listMembers("admin").toList();
assertNotNull(admins); assertThat(admins, notNullValue());
assertThat("One admin in dummy team", admins.size() == 1); assertThat("One admin in dummy team", admins.size(), equalTo(1));
assertThat("Specific user in admin team", assertThat("Specific user in admin team",
admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("bitwiseman"))); admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("bitwiseman")));
} }
@@ -71,7 +71,7 @@ public class GHTeamTest extends AbstractGitHubWireMockTest {
// Check that it was set correctly. // Check that it was set correctly.
team = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug(teamSlug); team = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug(teamSlug);
assertEquals(privacy, team.getPrivacy()); assertThat(team.getPrivacy(), equalTo(privacy));
privacy = Privacy.SECRET; privacy = Privacy.SECRET;
@@ -80,7 +80,7 @@ public class GHTeamTest extends AbstractGitHubWireMockTest {
// Check that it was set correctly. // Check that it was set correctly.
team = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug(teamSlug); team = gitHub.getOrganization(GITHUB_API_TEST_ORG).getTeamBySlug(teamSlug);
assertEquals(privacy, team.getPrivacy()); assertThat(team.getPrivacy(), equalTo(privacy));
} }
@Test @Test
@@ -91,8 +91,8 @@ public class GHTeamTest extends AbstractGitHubWireMockTest {
GHTeam team = org.getTeamBySlug(teamSlug); GHTeam team = org.getTeamBySlug(teamSlug);
Set<GHTeam> result = team.listChildTeams().toSet(); Set<GHTeam> result = team.listChildTeams().toSet();
assertEquals(1, result.size()); assertThat(result.size(), equalTo(1));
assertEquals("child-team-for-dummy", result.toArray(new GHTeam[]{})[0].getName()); assertThat(result.toArray(new GHTeam[]{})[0].getName(), equalTo("child-team-for-dummy"));
} }
@Test @Test
@@ -103,7 +103,7 @@ public class GHTeamTest extends AbstractGitHubWireMockTest {
GHTeam team = org.getTeamBySlug(teamSlug); GHTeam team = org.getTeamBySlug(teamSlug);
Set<GHTeam> result = team.listChildTeams().toSet(); Set<GHTeam> result = team.listChildTeams().toSet();
assertEquals(0, result.size()); assertThat(result, is(empty()));
} }
} }

View File

@@ -10,7 +10,6 @@ import java.util.Arrays;
import java.util.Date; import java.util.Date;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
public class GHTreeBuilderTest extends AbstractGitHubWireMockTest { public class GHTreeBuilderTest extends AbstractGitHubWireMockTest {
private static String REPO_NAME = "hub4j-test-org/GHTreeBuilderTest"; private static String REPO_NAME = "hub4j-test-org/GHTreeBuilderTest";
@@ -28,14 +27,14 @@ public class GHTreeBuilderTest extends AbstractGitHubWireMockTest {
private static byte[] CONTENT_DATA2 = { 0x04, 0x05, 0x06, 0x07 }; private static byte[] CONTENT_DATA2 = { 0x04, 0x05, 0x06, 0x07 };
private GHRepository repo; private GHRepository repo;
private GHRef masterRef; private GHRef mainRef;
private GHTreeBuilder treeBuilder; private GHTreeBuilder treeBuilder;
@Before @Before
@After @After
public void cleanup() throws Exception { public void cleanup() throws Exception {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
repo = getGitHubBeforeAfter().getRepository(REPO_NAME); repo = getNonRecordingGitHub().getRepository(REPO_NAME);
Arrays.asList(PATH_SCRIPT, PATH_README, PATH_DATA1, PATH_DATA2).forEach(path -> { Arrays.asList(PATH_SCRIPT, PATH_README, PATH_DATA1, PATH_DATA2).forEach(path -> {
try { try {
GHContent content = repo.getFileContent(path); GHContent content = repo.getFileContent(path);
@@ -51,9 +50,9 @@ public class GHTreeBuilderTest extends AbstractGitHubWireMockTest {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
repo = gitHub.getRepository(REPO_NAME); repo = gitHub.getRepository(REPO_NAME);
masterRef = repo.getRef("heads/master"); mainRef = repo.getRef("heads/main");
String masterTreeSha = repo.getTreeRecursive("master", 1).getSha(); String mainTreeSha = repo.getTreeRecursive("main", 1).getSha();
treeBuilder = repo.createTree().baseTree(masterTreeSha); treeBuilder = repo.createTree().baseTree(mainTreeSha);
} }
@Test @Test
@@ -64,8 +63,8 @@ public class GHTreeBuilderTest extends AbstractGitHubWireMockTest {
updateTree(); updateTree();
assertEquals(CONTENT_SCRIPT.length(), getFileSize(PATH_SCRIPT)); assertThat(getFileSize(PATH_SCRIPT), equalTo(CONTENT_SCRIPT.length()));
assertEquals(CONTENT_README.length(), getFileSize(PATH_README)); assertThat(getFileSize(PATH_README), equalTo(CONTENT_README.length()));
} }
@Test @Test
@@ -78,8 +77,8 @@ public class GHTreeBuilderTest extends AbstractGitHubWireMockTest {
updateTree(); updateTree();
assertEquals(CONTENT_DATA1.length, getFileSize(PATH_DATA1)); assertThat(getFileSize(PATH_DATA1), equalTo((long) CONTENT_DATA1.length));
assertEquals(CONTENT_DATA2.length, getFileSize(PATH_DATA2)); assertThat(getFileSize(PATH_DATA2), equalTo((long) CONTENT_DATA2.length));
} }
@Test @Test
@@ -91,10 +90,10 @@ public class GHTreeBuilderTest extends AbstractGitHubWireMockTest {
GHCommit commit = updateTree(); GHCommit commit = updateTree();
assertEquals(CONTENT_SCRIPT.length(), getFileSize(PATH_SCRIPT)); assertThat(getFileSize(PATH_SCRIPT), equalTo((long) CONTENT_SCRIPT.length()));
assertEquals(CONTENT_README.length(), getFileSize(PATH_README)); assertThat(getFileSize(PATH_README), equalTo((long) CONTENT_README.length()));
assertEquals(CONTENT_DATA1.length, getFileSize(PATH_DATA1)); assertThat(getFileSize(PATH_DATA1), equalTo((long) CONTENT_DATA1.length));
assertEquals(CONTENT_DATA2.length, getFileSize(PATH_DATA2)); assertThat(getFileSize(PATH_DATA2), equalTo((long) CONTENT_DATA2.length));
assertThat(commit.getCommitShortInfo().getAuthor().getEmail(), equalTo("author@author.com")); assertThat(commit.getCommitShortInfo().getAuthor().getEmail(), equalTo("author@author.com"));
assertThat(commit.getCommitShortInfo().getCommitter().getEmail(), equalTo("committer@committer.com")); assertThat(commit.getCommitShortInfo().getCommitter().getEmail(), equalTo("committer@committer.com"));
@@ -107,11 +106,11 @@ public class GHTreeBuilderTest extends AbstractGitHubWireMockTest {
.tree(treeSha) .tree(treeSha)
.author("author", "author@author.com", new Date(1611433225969L)) .author("author", "author@author.com", new Date(1611433225969L))
.committer("committer", "committer@committer.com", new Date(1611433225968L)) .committer("committer", "committer@committer.com", new Date(1611433225968L))
.parent(masterRef.getObject().getSha()) .parent(mainRef.getObject().getSha())
.create(); .create();
String commitSha = commit.getSHA1(); String commitSha = commit.getSHA1();
masterRef.updateTo(commitSha); mainRef.updateTo(commitSha);
return commit; return commit;
} }

View File

@@ -1,19 +1,22 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
public class GHUserTest extends AbstractGitHubWireMockTest { public class GHUserTest extends AbstractGitHubWireMockTest {
@Test @Test
public void listFollowsAndFollowers() throws IOException { public void listFollowsAndFollowers() throws IOException {
GHUser u = gitHub.getUser("rtyler"); GHUser u = gitHub.getUser("rtyler");
assertNotEquals(count30(u.listFollowers()), count30(u.listFollows())); assertThat(count30(u.listFollows()), not(count30(u.listFollowers())));
} }
private Set<GHUser> count30(PagedIterable<GHUser> l) { private Set<GHUser> count30(PagedIterable<GHUser> l) {
@@ -22,7 +25,7 @@ public class GHUserTest extends AbstractGitHubWireMockTest {
for (int i = 0; i < 30 && itr.hasNext(); i++) { for (int i = 0; i < 30 && itr.hasNext(); i++) {
users.add(itr.next()); users.add(itr.next());
} }
assertEquals(30, users.size()); assertThat(users.size(), equalTo(30));
return users; return users;
} }
@@ -31,14 +34,14 @@ public class GHUserTest extends AbstractGitHubWireMockTest {
GHUser u = gitHub.getUser("rtyler"); GHUser u = gitHub.getUser("rtyler");
List<GHKey> ghKeys = new ArrayList<>(u.getKeys()); List<GHKey> ghKeys = new ArrayList<>(u.getKeys());
assertEquals(3, ghKeys.size()); assertThat(ghKeys.size(), equalTo(3));
Collections.sort(ghKeys, new Comparator<GHKey>() { Collections.sort(ghKeys, new Comparator<GHKey>() {
@Override @Override
public int compare(GHKey ghKey, GHKey t1) { public int compare(GHKey ghKey, GHKey t1) {
return ghKey.getId() - t1.getId(); return ghKey.getId() - t1.getId();
} }
}); });
assertEquals(1066173, ghKeys.get(0).getId()); assertThat(ghKeys.get(0).getId(), equalTo(1066173));
assertThat(ghKeys.get(0).getTitle(), nullValue()); assertThat(ghKeys.get(0).getTitle(), nullValue());
assertThat(ghKeys.get(0).getUrl(), nullValue()); assertThat(ghKeys.get(0).getUrl(), nullValue());
assertThat(ghKeys.get(0).isVerified(), equalTo(false)); assertThat(ghKeys.get(0).isVerified(), equalTo(false));
@@ -46,23 +49,20 @@ public class GHUserTest extends AbstractGitHubWireMockTest {
containsString( containsString(
"title=<null>,id=1066173,key=ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAueiy12T5bvFhsc9YjfLc3aVIxgySd3gDxQWy/bletIoZL8omKmzocBYJ7F58U1asoyfWsy2ToTOY8jJp1eToXmbD6L5+xvHba0A7djYh9aQRrFam7doKQ0zp0ZSUF6+R1v0OM4nnWqK4n2ECIYd+Bdzrp+xA5+XlW3ZSNzlnW2BeWznzmgRMcp6wI+zQ9GMHWviR1cxpml5Z6wrxTZ0aX91btvnNPqoOGva976B6e6403FOEkkIFTk6CC1TFKwc/VjbqxYBg4kU0JhiTP+iEZibcQrYjWdYUgAotYbFVe5/DneHMLNsMPdeihba4PUwt62rXyNegenuCRmCntLcaFQ==")); "title=<null>,id=1066173,key=ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAueiy12T5bvFhsc9YjfLc3aVIxgySd3gDxQWy/bletIoZL8omKmzocBYJ7F58U1asoyfWsy2ToTOY8jJp1eToXmbD6L5+xvHba0A7djYh9aQRrFam7doKQ0zp0ZSUF6+R1v0OM4nnWqK4n2ECIYd+Bdzrp+xA5+XlW3ZSNzlnW2BeWznzmgRMcp6wI+zQ9GMHWviR1cxpml5Z6wrxTZ0aX91btvnNPqoOGva976B6e6403FOEkkIFTk6CC1TFKwc/VjbqxYBg4kU0JhiTP+iEZibcQrYjWdYUgAotYbFVe5/DneHMLNsMPdeihba4PUwt62rXyNegenuCRmCntLcaFQ=="));
assertEquals( assertThat(ghKeys.get(0).getKey(),
"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAueiy12T5bvFhsc9YjfLc3aVIxgySd3gDxQWy/bletIoZL8omKmzocBYJ7F58U1asoyfWsy2ToTOY8jJp1eToXmbD6L5+xvHba0A7djYh9aQRrFam7doKQ0zp0ZSUF6+R1v0OM4nnWqK4n2ECIYd+Bdzrp+xA5+XlW3ZSNzlnW2BeWznzmgRMcp6wI+zQ9GMHWviR1cxpml5Z6wrxTZ0aX91btvnNPqoOGva976B6e6403FOEkkIFTk6CC1TFKwc/VjbqxYBg4kU0JhiTP+iEZibcQrYjWdYUgAotYbFVe5/DneHMLNsMPdeihba4PUwt62rXyNegenuCRmCntLcaFQ==", equalTo("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAueiy12T5bvFhsc9YjfLc3aVIxgySd3gDxQWy/bletIoZL8omKmzocBYJ7F58U1asoyfWsy2ToTOY8jJp1eToXmbD6L5+xvHba0A7djYh9aQRrFam7doKQ0zp0ZSUF6+R1v0OM4nnWqK4n2ECIYd+Bdzrp+xA5+XlW3ZSNzlnW2BeWznzmgRMcp6wI+zQ9GMHWviR1cxpml5Z6wrxTZ0aX91btvnNPqoOGva976B6e6403FOEkkIFTk6CC1TFKwc/VjbqxYBg4kU0JhiTP+iEZibcQrYjWdYUgAotYbFVe5/DneHMLNsMPdeihba4PUwt62rXyNegenuCRmCntLcaFQ=="));
ghKeys.get(0).getKey()); assertThat(ghKeys.get(1).getId(), equalTo(28136459));
assertEquals(28136459, ghKeys.get(1).getId());
assertThat(ghKeys.get(1).getTitle(), nullValue()); assertThat(ghKeys.get(1).getTitle(), nullValue());
assertThat(ghKeys.get(1).getUrl(), nullValue()); assertThat(ghKeys.get(1).getUrl(), nullValue());
assertThat(ghKeys.get(1).isVerified(), equalTo(false)); assertThat(ghKeys.get(1).isVerified(), equalTo(false));
assertEquals( assertThat(ghKeys.get(1).getKey(),
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTU0s5OKCC6VpKZGL9NJD4mNLY0AtujkVB1JkkuQ4OkMi2YGUHJtGhTbTwEVhNxpm0x2dM5KSzse6MLDYuGBW0qkE/VVuD9+9I73hbq461KqP0+WlupNh+Qc86kbiLBDv64+vWc+50mp1dbINpoM5xvaPYxgjnemydPv7vu5bhCHBugW7aN8VcLgfFgcp8vZCEanMtd3hIRjRU8v8Skk233ZGu1bXkG8iIOBQPabvEtZ0VDMg9pT3Q1R6lnnKqfCwHXd6zP6uAtejFSxvKRGKpu3OLGQMHwk7NlImVuhkVdaEFBq7pQtpOaGuP2eLKcN1wy5jsTYE+ZB6pvHCi2ecb", equalTo("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTU0s5OKCC6VpKZGL9NJD4mNLY0AtujkVB1JkkuQ4OkMi2YGUHJtGhTbTwEVhNxpm0x2dM5KSzse6MLDYuGBW0qkE/VVuD9+9I73hbq461KqP0+WlupNh+Qc86kbiLBDv64+vWc+50mp1dbINpoM5xvaPYxgjnemydPv7vu5bhCHBugW7aN8VcLgfFgcp8vZCEanMtd3hIRjRU8v8Skk233ZGu1bXkG8iIOBQPabvEtZ0VDMg9pT3Q1R6lnnKqfCwHXd6zP6uAtejFSxvKRGKpu3OLGQMHwk7NlImVuhkVdaEFBq7pQtpOaGuP2eLKcN1wy5jsTYE+ZB6pvHCi2ecb"));
ghKeys.get(1).getKey()); assertThat(ghKeys.get(2).getId(), equalTo(31452581));
assertEquals(31452581, ghKeys.get(2).getId());
assertThat(ghKeys.get(2).getTitle(), nullValue()); assertThat(ghKeys.get(2).getTitle(), nullValue());
assertThat(ghKeys.get(2).getUrl(), nullValue()); assertThat(ghKeys.get(2).getUrl(), nullValue());
assertThat(ghKeys.get(2).isVerified(), equalTo(false)); assertThat(ghKeys.get(2).isVerified(), equalTo(false));
assertEquals( assertThat(ghKeys.get(2).getKey(),
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC3JhH2FZBDmHLjXTcBoV6tdcYKmsQ7sgu8k1RsUhwxGsXm65+Cuas6GcMVoA1DncKfJGQkulHDFiTxIROIBmedh9/otHWBlZ4HqYZ4MQ1A8W5quULkXwX/kF+UdRBUxFvjigibEbuHB+LARVxRRzFlPnTSE9rAfAv8OOEsb3lNUGT/IGhN8w1vwe8GclB90tgqN1RBDgrVqwLFwn5AfrW9kUIa2f2oT4RjYu1OrhKhVIIzfHADo85aD+s8wEhqwI96BCJG3qTWrypoHwBUoj1O6Ak5CGc1iKz9o8XyTMjudRt2ddCjfOtxsuwSlTbVtQXJGIpgKviX1sgh4pPvGh7BVAFP+mdAK4F+mEugDnuj47GO/K5KGGDRCL56kh9+h28l4q/+fZvp7DhtmSN2EzrVAdQFskF8yY/6Xit/aAvjeKm03DcjbylSXbG26EJefaLHlwYFq2mUFRMak25wuuCZS71GF3RC3Sl/bMoxBKRYkyfYtGafeaYTFNGn8Dbd+hfVUCz31ebI8cvmlQR5b5AbCre3T7HTVgw8FKbAxWRf1Fio56PnqHsj+sT1KVj255Zo1F8iD9GrgERSVAlkh5bY/CKszQ8ZSd01c9Qp2a47/gR7XAAbxhzGHP+cSOlrqDlJ24fbPtcpVsM0llqKUcxpmoOBFNboRmE1QqnSmAf9ww==", equalTo("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC3JhH2FZBDmHLjXTcBoV6tdcYKmsQ7sgu8k1RsUhwxGsXm65+Cuas6GcMVoA1DncKfJGQkulHDFiTxIROIBmedh9/otHWBlZ4HqYZ4MQ1A8W5quULkXwX/kF+UdRBUxFvjigibEbuHB+LARVxRRzFlPnTSE9rAfAv8OOEsb3lNUGT/IGhN8w1vwe8GclB90tgqN1RBDgrVqwLFwn5AfrW9kUIa2f2oT4RjYu1OrhKhVIIzfHADo85aD+s8wEhqwI96BCJG3qTWrypoHwBUoj1O6Ak5CGc1iKz9o8XyTMjudRt2ddCjfOtxsuwSlTbVtQXJGIpgKviX1sgh4pPvGh7BVAFP+mdAK4F+mEugDnuj47GO/K5KGGDRCL56kh9+h28l4q/+fZvp7DhtmSN2EzrVAdQFskF8yY/6Xit/aAvjeKm03DcjbylSXbG26EJefaLHlwYFq2mUFRMak25wuuCZS71GF3RC3Sl/bMoxBKRYkyfYtGafeaYTFNGn8Dbd+hfVUCz31ebI8cvmlQR5b5AbCre3T7HTVgw8FKbAxWRf1Fio56PnqHsj+sT1KVj255Zo1F8iD9GrgERSVAlkh5bY/CKszQ8ZSd01c9Qp2a47/gR7XAAbxhzGHP+cSOlrqDlJ24fbPtcpVsM0llqKUcxpmoOBFNboRmE1QqnSmAf9ww=="));
ghKeys.get(2).getKey());
} }
@Test @Test
@@ -71,11 +71,11 @@ public class GHUserTest extends AbstractGitHubWireMockTest {
Iterator<GHRepository> itr = user.listRepositories().iterator(); Iterator<GHRepository> itr = user.listRepositories().iterator();
int i = 0; int i = 0;
for (; i < 115; i++) { for (; i < 115; i++) {
assertTrue(itr.hasNext()); assertThat(itr.hasNext(), is(true));
GHRepository r = itr.next(); GHRepository r = itr.next();
// System.out.println(r.getFullName()); // System.out.println(r.getFullName());
assertNotNull(r.getUrl()); assertThat(r.getUrl(), notNullValue());
assertNotEquals(0L, r.getId()); assertThat(r.getId(), not(0L));
} }
assertThat(i, equalTo(115)); assertThat(i, equalTo(115));
@@ -87,11 +87,11 @@ public class GHUserTest extends AbstractGitHubWireMockTest {
Iterator<GHRepository> itr = user.listRepositories().withPageSize(62).iterator(); Iterator<GHRepository> itr = user.listRepositories().withPageSize(62).iterator();
int i = 0; int i = 0;
for (; i < 115; i++) { for (; i < 115; i++) {
assertTrue(itr.hasNext()); assertThat(itr.hasNext(), is(true));
GHRepository r = itr.next(); GHRepository r = itr.next();
// System.out.println(r.getFullName()); // System.out.println(r.getFullName());
assertNotNull(r.getUrl()); assertThat(r.getUrl(), notNullValue());
assertNotEquals(0L, r.getId()); assertThat(r.getId(), not(0L));
} }
assertThat(i, equalTo(115)); assertThat(i, equalTo(115));
@@ -108,7 +108,7 @@ public class GHUserTest extends AbstractGitHubWireMockTest {
.create(); .create();
try { try {
Assert.assertNotNull(repository); assertThat(repository, notNullValue());
GHUser ghUser = gitHub.getUser(login); GHUser ghUser = gitHub.getUser(login);
assertThat(ghUser.getTotalPrivateRepoCount().orElse(-1), greaterThan(0)); assertThat(ghUser.getTotalPrivateRepoCount().orElse(-1), greaterThan(0));
} finally { } finally {
@@ -120,8 +120,8 @@ public class GHUserTest extends AbstractGitHubWireMockTest {
public void verifyBioAndHireable() throws IOException { public void verifyBioAndHireable() throws IOException {
GHUser u = gitHub.getUser("Chew"); GHUser u = gitHub.getUser("Chew");
assertThat(u.getBio(), equalTo("I like to program things and I hope to program something cool one day :D")); assertThat(u.getBio(), equalTo("I like to program things and I hope to program something cool one day :D"));
assertTrue(u.isHireable()); assertThat(u.isHireable(), is(true));
assertNotNull(u.getTwitterUsername()); assertThat(u.getTwitterUsername(), notNullValue());
assertThat(u.getBlog(), equalTo("https://chew.pw")); assertThat(u.getBlog(), equalTo("https://chew.pw"));
assertThat(u.getCompany(), equalTo("@Memerator")); assertThat(u.getCompany(), equalTo("@Memerator"));
assertThat(u.getFollowersCount(), equalTo(29)); assertThat(u.getFollowersCount(), equalTo(29));

View File

@@ -2,6 +2,8 @@ package org.kohsuke.github;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.Matchers.*;
/** /**
* @author Sourabh Sarvotham Parkala * @author Sourabh Sarvotham Parkala
*/ */
@@ -11,121 +13,126 @@ public class GHVerificationReasonTest extends AbstractGitHubWireMockTest {
public void testExpiredKey() throws Exception { public void testExpiredKey() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f01"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f01");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.EXPIRED_KEY); assertThat(commit.getCommitShortInfo().getVerification().getReason(),
equalTo(GHVerification.Reason.EXPIRED_KEY));
} }
@Test @Test
public void testNotSigningKey() throws Exception { public void testNotSigningKey() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f02"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f02");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.NOT_SIGNING_KEY); assertThat(commit.getCommitShortInfo().getVerification().getReason(),
equalTo(GHVerification.Reason.NOT_SIGNING_KEY));
} }
@Test @Test
public void testGpgverifyError() throws Exception { public void testGpgverifyError() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f03"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f03");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.GPGVERIFY_ERROR); assertThat(commit.getCommitShortInfo().getVerification().getReason(),
equalTo(GHVerification.Reason.GPGVERIFY_ERROR));
} }
@Test @Test
public void testGpgverifyUnavailable() throws Exception { public void testGpgverifyUnavailable() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f04"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f04");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), assertThat(commit.getCommitShortInfo().getVerification().getReason(),
GHVerification.Reason.GPGVERIFY_UNAVAILABLE); equalTo(GHVerification.Reason.GPGVERIFY_UNAVAILABLE));
} }
@Test @Test
public void testUnsigned() throws Exception { public void testUnsigned() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f05"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f05");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.UNSIGNED); assertThat(commit.getCommitShortInfo().getVerification().getReason(), equalTo(GHVerification.Reason.UNSIGNED));
} }
@Test @Test
public void testUnknownSignatureType() throws Exception { public void testUnknownSignatureType() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f06"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f06");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), assertThat(commit.getCommitShortInfo().getVerification().getReason(),
GHVerification.Reason.UNKNOWN_SIGNATURE_TYPE); equalTo(GHVerification.Reason.UNKNOWN_SIGNATURE_TYPE));
} }
@Test @Test
public void testNoUser() throws Exception { public void testNoUser() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f07"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f07");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.NO_USER); assertThat(commit.getCommitShortInfo().getVerification().getReason(), equalTo(GHVerification.Reason.NO_USER));
} }
@Test @Test
public void testUnverifiedEmail() throws Exception { public void testUnverifiedEmail() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f08"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f08");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.UNVERIFIED_EMAIL); assertThat(commit.getCommitShortInfo().getVerification().getReason(),
equalTo(GHVerification.Reason.UNVERIFIED_EMAIL));
} }
@Test @Test
public void testBadEmail() throws Exception { public void testBadEmail() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f09"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f09");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.BAD_EMAIL); assertThat(commit.getCommitShortInfo().getVerification().getReason(), equalTo(GHVerification.Reason.BAD_EMAIL));
} }
@Test @Test
public void testUnknownKey() throws Exception { public void testUnknownKey() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f10"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f10");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.UNKNOWN_KEY); assertThat(commit.getCommitShortInfo().getVerification().getReason(),
equalTo(GHVerification.Reason.UNKNOWN_KEY));
} }
@Test @Test
public void testMalformedSignature() throws Exception { public void testMalformedSignature() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f11"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f11");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), assertThat(commit.getCommitShortInfo().getVerification().getReason(),
GHVerification.Reason.MALFORMED_SIGNATURE); equalTo(GHVerification.Reason.MALFORMED_SIGNATURE));
} }
@Test @Test
public void testInvalid() throws Exception { public void testInvalid() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f12"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f12");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertFalse(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(false));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.INVALID); assertThat(commit.getCommitShortInfo().getVerification().getReason(), equalTo(GHVerification.Reason.INVALID));
} }
@Test @Test
public void testValid() throws Exception { public void testValid() throws Exception {
GHRepository r = gitHub.getRepository("hub4j/github-api"); GHRepository r = gitHub.getRepository("hub4j/github-api");
GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f13"); GHCommit commit = r.getCommit("86a2e245aa6d71d54923655066049d9e21a15f13");
assertEquals(commit.getCommitShortInfo().getAuthor().getName(), "Sourabh Parkala"); assertThat(commit.getCommitShortInfo().getAuthor().getName(), equalTo("Sourabh Parkala"));
assertTrue(commit.getCommitShortInfo().getVerification().isVerified()); assertThat(commit.getCommitShortInfo().getVerification().isVerified(), is(true));
assertEquals(commit.getCommitShortInfo().getVerification().getReason(), GHVerification.Reason.VALID); assertThat(commit.getCommitShortInfo().getVerification().getReason(), equalTo(GHVerification.Reason.VALID));
assertNotNull(commit.getCommitShortInfo().getVerification().getPayload()); assertThat(commit.getCommitShortInfo().getVerification().getPayload(), notNullValue());
assertNotNull(commit.getCommitShortInfo().getVerification().getSignature()); assertThat(commit.getCommitShortInfo().getVerification().getSignature(), notNullValue());
} }
} }

View File

@@ -1,7 +1,6 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.awaitility.Awaitility; import org.awaitility.Awaitility;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.kohsuke.github.GHWorkflowJob.Step; import org.kohsuke.github.GHWorkflowJob.Step;
@@ -20,11 +19,7 @@ import java.util.stream.Collectors;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
public class GHWorkflowRunTest extends AbstractGitHubWireMockTest { public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
@@ -72,30 +67,30 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
latestPreexistingWorkflowRunId).orElseThrow( latestPreexistingWorkflowRunId).orElseThrow(
() -> new IllegalStateException("We must have a valid workflow run starting from here")); () -> new IllegalStateException("We must have a valid workflow run starting from here"));
assertEquals(workflow.getId(), workflowRun.getWorkflowId()); assertThat(workflowRun.getWorkflowId(), equalTo(workflow.getId()));
assertNotNull(workflowRun.getId()); assertThat(workflowRun.getId(), notNullValue());
assertNotNull(workflowRun.getNodeId()); assertThat(workflowRun.getNodeId(), notNullValue());
assertEquals(REPO_NAME, workflowRun.getRepository().getFullName()); assertThat(workflowRun.getRepository().getFullName(), equalTo(REPO_NAME));
assertTrue(workflowRun.getUrl().getPath().contains("/actions/runs/")); assertThat(workflowRun.getUrl().getPath(), containsString("/actions/runs/"));
assertTrue(workflowRun.getHtmlUrl().getPath().contains("/actions/runs/")); assertThat(workflowRun.getHtmlUrl().getPath(), containsString("/actions/runs/"));
assertTrue(workflowRun.getJobsUrl().getPath().endsWith("/jobs")); assertThat(workflowRun.getJobsUrl().getPath(), endsWith("/jobs"));
assertTrue(workflowRun.getLogsUrl().getPath().endsWith("/logs")); assertThat(workflowRun.getLogsUrl().getPath(), endsWith("/logs"));
assertTrue(workflowRun.getCheckSuiteUrl().getPath().contains("/check-suites/")); assertThat(workflowRun.getCheckSuiteUrl().getPath(), containsString("/check-suites/"));
assertTrue(workflowRun.getArtifactsUrl().getPath().endsWith("/artifacts")); assertThat(workflowRun.getArtifactsUrl().getPath(), endsWith("/artifacts"));
assertTrue(workflowRun.getCancelUrl().getPath().endsWith("/cancel")); assertThat(workflowRun.getCancelUrl().getPath(), endsWith("/cancel"));
assertTrue(workflowRun.getRerunUrl().getPath().endsWith("/rerun")); assertThat(workflowRun.getRerunUrl().getPath(), endsWith("/rerun"));
assertTrue(workflowRun.getWorkflowUrl().getPath().contains("/actions/workflows/")); assertThat(workflowRun.getWorkflowUrl().getPath(), containsString("/actions/workflows/"));
assertEquals(MAIN_BRANCH, workflowRun.getHeadBranch()); assertThat(workflowRun.getHeadBranch(), equalTo(MAIN_BRANCH));
assertNotNull(workflowRun.getHeadCommit().getId()); assertThat(workflowRun.getHeadCommit().getId(), notNullValue());
assertNotNull(workflowRun.getHeadCommit().getTreeId()); assertThat(workflowRun.getHeadCommit().getTreeId(), notNullValue());
assertNotNull(workflowRun.getHeadCommit().getMessage()); assertThat(workflowRun.getHeadCommit().getMessage(), notNullValue());
assertNotNull(workflowRun.getHeadCommit().getTimestamp()); assertThat(workflowRun.getHeadCommit().getTimestamp(), notNullValue());
assertNotNull(workflowRun.getHeadCommit().getAuthor().getEmail()); assertThat(workflowRun.getHeadCommit().getAuthor().getEmail(), notNullValue());
assertNotNull(workflowRun.getHeadCommit().getCommitter().getEmail()); assertThat(workflowRun.getHeadCommit().getCommitter().getEmail(), notNullValue());
assertEquals(GHEvent.WORKFLOW_DISPATCH, workflowRun.getEvent()); assertThat(workflowRun.getEvent(), equalTo(GHEvent.WORKFLOW_DISPATCH));
assertEquals(Status.COMPLETED, workflowRun.getStatus()); assertThat(workflowRun.getStatus(), equalTo(Status.COMPLETED));
assertEquals(Conclusion.SUCCESS, workflowRun.getConclusion()); assertThat(workflowRun.getConclusion(), equalTo(Conclusion.SUCCESS));
assertNotNull(workflowRun.getHeadSha()); assertThat(workflowRun.getHeadSha(), notNullValue());
} }
@Test @Test
@@ -119,7 +114,7 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
latestPreexistingWorkflowRunId).orElseThrow( latestPreexistingWorkflowRunId).orElseThrow(
() -> new IllegalStateException("We must have a valid workflow run starting from here")); () -> new IllegalStateException("We must have a valid workflow run starting from here"));
assertNotNull(workflowRun.getId()); assertThat(workflowRun.getId(), notNullValue());
workflowRun.cancel(); workflowRun.cancel();
long cancelledWorkflowRunId = workflowRun.getId(); long cancelledWorkflowRunId = workflowRun.getId();
@@ -129,7 +124,7 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
// let's check that it has been properly cancelled // let's check that it has been properly cancelled
workflowRun = repo.getWorkflowRun(cancelledWorkflowRunId); workflowRun = repo.getWorkflowRun(cancelledWorkflowRunId);
assertEquals(Conclusion.CANCELLED, workflowRun.getConclusion()); assertThat(workflowRun.getConclusion(), equalTo(Conclusion.CANCELLED));
// now let's rerun it // now let's rerun it
workflowRun.rerun(); workflowRun.rerun();
@@ -162,13 +157,13 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
latestPreexistingWorkflowRunId).orElseThrow( latestPreexistingWorkflowRunId).orElseThrow(
() -> new IllegalStateException("We must have a valid workflow run starting from here")); () -> new IllegalStateException("We must have a valid workflow run starting from here"));
assertNotNull(workflowRunToDelete.getId()); assertThat(workflowRunToDelete.getId(), notNullValue());
workflowRunToDelete.delete(); workflowRunToDelete.delete();
try { try {
repo.getWorkflowRun(workflowRunToDelete.getId()); repo.getWorkflowRun(workflowRunToDelete.getId());
Assert.fail("The workflow " + workflowRunToDelete.getId() + " should have been deleted."); fail("The workflow " + workflowRunToDelete.getId() + " should have been deleted.");
} catch (GHFileNotFoundException e) { } catch (GHFileNotFoundException e) {
// success // success
} }
@@ -194,11 +189,11 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
latestPreexistingWorkflowRunId).orElseThrow( latestPreexistingWorkflowRunId).orElseThrow(
() -> new IllegalStateException("We must have a valid workflow run starting from here")); () -> new IllegalStateException("We must have a valid workflow run starting from here"));
assertEquals(workflow.getId(), workflowRun.getWorkflowId()); assertThat(workflowRun.getWorkflowId(), equalTo(workflow.getId()));
assertEquals(SECOND_BRANCH, workflowRun.getHeadBranch()); assertThat(workflowRun.getHeadBranch(), equalTo(SECOND_BRANCH));
assertEquals(GHEvent.WORKFLOW_DISPATCH, workflowRun.getEvent()); assertThat(workflowRun.getEvent(), equalTo(GHEvent.WORKFLOW_DISPATCH));
assertEquals(Status.COMPLETED, workflowRun.getStatus()); assertThat(workflowRun.getStatus(), equalTo(Status.COMPLETED));
assertEquals(Conclusion.SUCCESS, workflowRun.getConclusion()); assertThat(workflowRun.getConclusion(), equalTo(Conclusion.SUCCESS));
} }
@Test @Test
@@ -232,7 +227,7 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
try { try {
workflowRun.downloadLogs((is) -> ""); workflowRun.downloadLogs((is) -> "");
Assert.fail("Downloading logs should not be possible as they were deleted"); fail("Downloading logs should not be possible as they were deleted");
} catch (GHFileNotFoundException e) { } catch (GHFileNotFoundException e) {
assertThat(e.getMessage(), containsString("Not Found")); assertThat(e.getMessage(), containsString("Not Found"));
} }
@@ -313,7 +308,7 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
try { try {
repo.getArtifact(artifact1.getId()); repo.getArtifact(artifact1.getId());
Assert.fail("Getting the artifact should fail as it was deleted"); fail("Getting the artifact should fail as it was deleted");
} catch (GHFileNotFoundException e) { } catch (GHFileNotFoundException e) {
assertThat(e.getMessage(), containsString("Not Found")); assertThat(e.getMessage(), containsString("Not Found"));
} }
@@ -371,7 +366,7 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
return; return;
} }
GHRepository nonRecordingRepo = getGitHubBeforeAfter().getRepository(REPO_NAME); GHRepository nonRecordingRepo = getNonRecordingGitHub().getRepository(REPO_NAME);
Awaitility.await().pollInterval(Duration.ofSeconds(5)).atMost(Duration.ofSeconds(60)).until(() -> { Awaitility.await().pollInterval(Duration.ofSeconds(5)).atMost(Duration.ofSeconds(60)).until(() -> {
return condition.apply(nonRecordingRepo); return condition.apply(nonRecordingRepo);
@@ -456,26 +451,26 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
} }
private static void checkArtifactProperties(GHArtifact artifact, String artifactName) throws IOException { private static void checkArtifactProperties(GHArtifact artifact, String artifactName) throws IOException {
assertNotNull(artifact.getId()); assertThat(artifact.getId(), notNullValue());
assertNotNull(artifact.getNodeId()); assertThat(artifact.getNodeId(), notNullValue());
assertEquals(REPO_NAME, artifact.getRepository().getFullName()); assertThat(artifact.getRepository().getFullName(), equalTo(REPO_NAME));
assertThat(artifact.getName(), is(artifactName)); assertThat(artifact.getName(), is(artifactName));
assertThat(artifact.getArchiveDownloadUrl().getPath(), containsString("actions/artifacts")); assertThat(artifact.getArchiveDownloadUrl().getPath(), containsString("actions/artifacts"));
assertNotNull(artifact.getCreatedAt()); assertThat(artifact.getCreatedAt(), notNullValue());
assertNotNull(artifact.getUpdatedAt()); assertThat(artifact.getUpdatedAt(), notNullValue());
assertNotNull(artifact.getExpiresAt()); assertThat(artifact.getExpiresAt(), notNullValue());
assertThat(artifact.getSizeInBytes(), greaterThan(0L)); assertThat(artifact.getSizeInBytes(), greaterThan(0L));
assertFalse(artifact.isExpired()); assertThat(artifact.isExpired(), is(false));
} }
private static void checkJobProperties(long workflowRunId, GHWorkflowJob job, String jobName) throws IOException { private static void checkJobProperties(long workflowRunId, GHWorkflowJob job, String jobName) throws IOException {
assertNotNull(job.getId()); assertThat(job.getId(), notNullValue());
assertNotNull(job.getNodeId()); assertThat(job.getNodeId(), notNullValue());
assertEquals(REPO_NAME, job.getRepository().getFullName()); assertThat(job.getRepository().getFullName(), equalTo(REPO_NAME));
assertThat(job.getName(), is(jobName)); assertThat(job.getName(), is(jobName));
assertNotNull(job.getStartedAt()); assertThat(job.getStartedAt(), notNullValue());
assertNotNull(job.getCompletedAt()); assertThat(job.getCompletedAt(), notNullValue());
assertNotNull(job.getHeadSha()); assertThat(job.getHeadSha(), notNullValue());
assertThat(job.getStatus(), is(Status.COMPLETED)); assertThat(job.getStatus(), is(Status.COMPLETED));
assertThat(job.getConclusion(), is(Conclusion.SUCCESS)); assertThat(job.getConclusion(), is(Conclusion.SUCCESS));
assertThat(job.getRunId(), is(workflowRunId)); assertThat(job.getRunId(), is(workflowRunId));
@@ -500,7 +495,7 @@ public class GHWorkflowRunTest extends AbstractGitHubWireMockTest {
assertThat(step.getNumber(), is(number)); assertThat(step.getNumber(), is(number));
assertThat(step.getStatus(), is(Status.COMPLETED)); assertThat(step.getStatus(), is(Status.COMPLETED));
assertThat(step.getConclusion(), is(Conclusion.SUCCESS)); assertThat(step.getConclusion(), is(Conclusion.SUCCESS));
assertNotNull(step.getStartedAt()); assertThat(step.getStartedAt(), notNullValue());
assertNotNull(step.getCompletedAt()); assertThat(step.getCompletedAt(), notNullValue());
} }
} }

View File

@@ -12,6 +12,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.hamcrest.Matchers.equalTo;
public class GHWorkflowTest extends AbstractGitHubWireMockTest { public class GHWorkflowTest extends AbstractGitHubWireMockTest {
@@ -23,7 +24,7 @@ public class GHWorkflowTest extends AbstractGitHubWireMockTest {
@After @After
public void cleanup() throws Exception { public void cleanup() throws Exception {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
repo = getGitHubBeforeAfter().getRepository(REPO_NAME); repo = getNonRecordingGitHub().getRepository(REPO_NAME);
// we need to make sure the workflow is enabled before the tests // we need to make sure the workflow is enabled before the tests
GHWorkflow workflow = repo.getWorkflow("test-workflow.yml"); GHWorkflow workflow = repo.getWorkflow("test-workflow.yml");
@@ -42,35 +43,36 @@ public class GHWorkflowTest extends AbstractGitHubWireMockTest {
public void testBasicInformation() throws IOException { public void testBasicInformation() throws IOException {
GHWorkflow workflow = repo.getWorkflow("test-workflow.yml"); GHWorkflow workflow = repo.getWorkflow("test-workflow.yml");
assertEquals("test-workflow", workflow.getName()); assertThat(workflow.getName(), equalTo("test-workflow"));
assertEquals(REPO_NAME, workflow.getRepository().getFullName()); assertThat(workflow.getRepository().getFullName(), equalTo(REPO_NAME));
assertEquals(".github/workflows/test-workflow.yml", workflow.getPath()); assertThat(workflow.getPath(), equalTo(".github/workflows/test-workflow.yml"));
assertEquals("active", workflow.getState()); assertThat(workflow.getState(), equalTo("active"));
assertEquals("/repos/hub4j-test-org/GHWorkflowTest/actions/workflows/6817859", workflow.getUrl().getPath()); assertThat(workflow.getUrl().getPath(),
assertEquals("/hub4j-test-org/GHWorkflowTest/blob/main/.github/workflows/test-workflow.yml", equalTo("/repos/hub4j-test-org/GHWorkflowTest/actions/workflows/6817859"));
workflow.getHtmlUrl().getPath()); assertThat(workflow.getHtmlUrl().getPath(),
assertEquals("/hub4j-test-org/GHWorkflowTest/workflows/test-workflow/badge.svg", equalTo("/hub4j-test-org/GHWorkflowTest/blob/main/.github/workflows/test-workflow.yml"));
workflow.getBadgeUrl().getPath()); assertThat(workflow.getBadgeUrl().getPath(),
equalTo("/hub4j-test-org/GHWorkflowTest/workflows/test-workflow/badge.svg"));
GHWorkflow workflowById = repo.getWorkflow(workflow.getId()); GHWorkflow workflowById = repo.getWorkflow(workflow.getId());
assertEquals(workflow.getNodeId(), workflowById.getNodeId()); assertThat(workflowById.getNodeId(), equalTo(workflow.getNodeId()));
} }
@Test @Test
public void testDisableEnable() throws IOException { public void testDisableEnable() throws IOException {
GHWorkflow workflow = repo.getWorkflow("test-workflow.yml"); GHWorkflow workflow = repo.getWorkflow("test-workflow.yml");
assertEquals("active", workflow.getState()); assertThat(workflow.getState(), equalTo("active"));
workflow.disable(); workflow.disable();
workflow = repo.getWorkflow("test-workflow.yml"); workflow = repo.getWorkflow("test-workflow.yml");
assertEquals("disabled_manually", workflow.getState()); assertThat(workflow.getState(), equalTo("disabled_manually"));
workflow.enable(); workflow.enable();
workflow = repo.getWorkflow("test-workflow.yml"); workflow = repo.getWorkflow("test-workflow.yml");
assertEquals("active", workflow.getState()); assertThat(workflow.getState(), equalTo("active"));
} }
@Test @Test
@@ -94,15 +96,16 @@ public class GHWorkflowTest extends AbstractGitHubWireMockTest {
List<GHWorkflow> workflows = repo.listWorkflows().toList(); List<GHWorkflow> workflows = repo.listWorkflows().toList();
GHWorkflow workflow = workflows.get(0); GHWorkflow workflow = workflows.get(0);
assertEquals(6817859L, workflow.getId()); assertThat(workflow.getId(), equalTo(6817859L));
assertEquals("MDg6V29ya2Zsb3c2ODE3ODU5", workflow.getNodeId()); assertThat(workflow.getNodeId(), equalTo("MDg6V29ya2Zsb3c2ODE3ODU5"));
assertEquals("test-workflow", workflow.getName()); assertThat(workflow.getName(), equalTo("test-workflow"));
assertEquals(".github/workflows/test-workflow.yml", workflow.getPath()); assertThat(workflow.getPath(), equalTo(".github/workflows/test-workflow.yml"));
assertEquals("active", workflow.getState()); assertThat(workflow.getState(), equalTo("active"));
assertEquals("/repos/hub4j-test-org/GHWorkflowTest/actions/workflows/6817859", workflow.getUrl().getPath()); assertThat(workflow.getUrl().getPath(),
assertEquals("/hub4j-test-org/GHWorkflowTest/blob/main/.github/workflows/test-workflow.yml", equalTo("/repos/hub4j-test-org/GHWorkflowTest/actions/workflows/6817859"));
workflow.getHtmlUrl().getPath()); assertThat(workflow.getHtmlUrl().getPath(),
assertEquals("/hub4j-test-org/GHWorkflowTest/workflows/test-workflow/badge.svg", equalTo("/hub4j-test-org/GHWorkflowTest/blob/main/.github/workflows/test-workflow.yml"));
workflow.getBadgeUrl().getPath()); assertThat(workflow.getBadgeUrl().getPath(),
equalTo("/hub4j-test-org/GHWorkflowTest/workflows/test-workflow/badge.svg"));
} }
} }

View File

@@ -10,11 +10,7 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
/** /**
* Unit test for {@link GitHub}. * Unit test for {@link GitHub}.
@@ -28,37 +24,36 @@ public class GitHubConnectionTest extends AbstractGitHubWireMockTest {
@Test @Test
public void testOffline() throws Exception { public void testOffline() throws Exception {
GitHub hub = GitHub.offline(); GitHub hub = GitHub.offline();
assertEquals("https://api.github.invalid/test", assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(),
equalTo("https://api.github.invalid/test"));
GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString()); assertThat(hub.isAnonymous(), is(true));
assertTrue(hub.isAnonymous());
try { try {
hub.getRateLimit(); hub.getRateLimit();
fail("Offline instance should always fail"); fail("Offline instance should always fail");
} catch (IOException e) { } catch (IOException e) {
assertEquals("Offline", e.getMessage()); assertThat(e.getMessage(), equalTo("Offline"));
} }
} }
@Test @Test
public void testGitHubServerWithHttp() throws Exception { public void testGitHubServerWithHttp() throws Exception {
GitHub hub = GitHub.connectToEnterprise("http://enterprise.kohsuke.org/api/v3", "bogus", "bogus"); GitHub hub = GitHub.connectToEnterprise("http://enterprise.kohsuke.org/api/v3", "bogus", "bogus");
assertEquals("http://enterprise.kohsuke.org/api/v3/test", assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(),
GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString()); equalTo("http://enterprise.kohsuke.org/api/v3/test"));
} }
@Test @Test
public void testGitHubServerWithHttps() throws Exception { public void testGitHubServerWithHttps() throws Exception {
GitHub hub = GitHub.connectToEnterprise("https://enterprise.kohsuke.org/api/v3", "bogus", "bogus"); GitHub hub = GitHub.connectToEnterprise("https://enterprise.kohsuke.org/api/v3", "bogus", "bogus");
assertEquals("https://enterprise.kohsuke.org/api/v3/test", assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(),
GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString()); equalTo("https://enterprise.kohsuke.org/api/v3/test"));
} }
@Test @Test
public void testGitHubServerWithoutServer() throws Exception { public void testGitHubServerWithoutServer() throws Exception {
GitHub hub = GitHub.connectUsingPassword("kohsuke", "bogus"); GitHub hub = GitHub.connectUsingPassword("kohsuke", "bogus");
assertEquals("https://api.github.com/test", assertThat(GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString(),
GitHubRequest.getApiURL(hub.getClient().getApiUrl(), "/test").toString()); equalTo("https://api.github.com/test"));
} }
@Test @Test
@@ -148,13 +143,13 @@ public class GitHubConnectionTest extends AbstractGitHubWireMockTest {
GitHubBuilder builder = new GitHubBuilder().withAppInstallationToken("bogus app token"); GitHubBuilder builder = new GitHubBuilder().withAppInstallationToken("bogus app token");
assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class)); assertThat(builder.authorizationProvider, instanceOf(UserAuthorizationProvider.class));
assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus app token")); assertThat(builder.authorizationProvider.getEncodedAuthorization(), equalTo("token bogus app token"));
assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), equalTo("")); assertThat(((UserAuthorizationProvider) builder.authorizationProvider).getLogin(), is(emptyString()));
// test authorization header is set as in the RFC6749 // test authorization header is set as in the RFC6749
GitHub github = builder.build(); GitHub github = builder.build();
// change this to get a request // change this to get a request
assertEquals("token bogus app token", github.getClient().getEncodedAuthorization()); assertThat(github.getClient().getEncodedAuthorization(), equalTo("token bogus app token"));
assertEquals("", github.getClient().login); assertThat(github.getClient().login, is(emptyString()));
} }
@Test @Test
@@ -164,10 +159,24 @@ public class GitHubConnectionTest extends AbstractGitHubWireMockTest {
// GitHub hub = GitHub.connectAnonymously(); // GitHub hub = GitHub.connectAnonymously();
GitHub hub = GitHub.connectToEnterpriseAnonymously(mockGitHub.apiServer().baseUrl()); GitHub hub = GitHub.connectToEnterpriseAnonymously(mockGitHub.apiServer().baseUrl());
hub.checkApiUrlValidity();
try { try {
hub.checkApiUrlValidity(); hub.checkApiUrlValidity();
fail();
} catch (IOException ioe) { } catch (IOException ioe) {
assertTrue(ioe.getMessage().contains("private mode enabled")); assertThat(ioe.getMessage(), containsString("doesn't look like GitHub API URL"));
}
try {
hub.checkApiUrlValidity();
fail();
} catch (IOException ioe) {
assertThat(ioe.getMessage(), containsString("private mode enabled"));
}
try {
hub.getClient().requireCredential();
fail();
} catch (Exception e) {
assertThat(e.getMessage(), containsString("This operation requires a credential"));
} }
} }

View File

@@ -139,8 +139,8 @@ public class GitHubStaticTest extends AbstractGitHubWireMockTest {
assertThat(rateLimit_none, equalTo(rateLimit_core)); assertThat(rateLimit_none, equalTo(rateLimit_core));
assertThat(rateLimit_none, not(sameInstance(rateLimit_core))); assertThat(rateLimit_none, not(sameInstance(rateLimit_core)));
assertTrue(rateLimit_none.hashCode() == rateLimit_core.hashCode()); assertThat(rateLimit_none.hashCode(), equalTo(rateLimit_core.hashCode()));
assertTrue(rateLimit_none.equals(rateLimit_core)); assertThat(rateLimit_none, equalTo(rateLimit_core));
assertThat(rateLimit_none, not(equalTo(rateLimit_search))); assertThat(rateLimit_none, not(equalTo(rateLimit_search)));

View File

@@ -7,9 +7,7 @@ import org.kohsuke.github.example.dataobject.ReadOnlyObjects;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.kohsuke.github.GHMarketplaceAccountType.ORGANIZATION; import static org.kohsuke.github.GHMarketplaceAccountType.ORGANIZATION;
/** /**
@@ -69,19 +67,19 @@ public class GitHubTest extends AbstractGitHubWireMockTest {
PagedSearchIterable<GHUser> r = gitHub.searchUsers().q("tom").repos(">42").followers(">1000").list(); PagedSearchIterable<GHUser> r = gitHub.searchUsers().q("tom").repos(">42").followers(">1000").list();
GHUser u = r.iterator().next(); GHUser u = r.iterator().next();
// System.out.println(u.getName()); // System.out.println(u.getName());
assertNotNull(u.getId()); assertThat(u.getId(), notNullValue());
assertTrue(r.getTotalCount() > 0); assertThat(r.getTotalCount(), greaterThan(0));
} }
@Test @Test
public void testListAllRepositories() throws Exception { public void testListAllRepositories() throws Exception {
Iterator<GHRepository> itr = gitHub.listAllPublicRepositories().iterator(); Iterator<GHRepository> itr = gitHub.listAllPublicRepositories().iterator();
for (int i = 0; i < 115; i++) { for (int i = 0; i < 115; i++) {
assertTrue(itr.hasNext()); assertThat(itr.hasNext(), is(true));
GHRepository r = itr.next(); GHRepository r = itr.next();
// System.out.println(r.getFullName()); // System.out.println(r.getFullName());
assertNotNull(r.getUrl()); assertThat(r.getUrl(), notNullValue());
assertNotEquals(0L, r.getId()); assertThat(r.getId(), not(0L));
} }
// ensure the iterator throws as expected // ensure the iterator throws as expected
@@ -100,13 +98,60 @@ public class GitHubTest extends AbstractGitHubWireMockTest {
.in("file") .in("file")
.language("js") .language("js")
.repo("jquery/jquery") .repo("jquery/jquery")
// ignored unless sort is also set
.order(GHDirection.DESC)
.list(); .list();
GHContent c = r.iterator().next(); GHContent c = r.iterator().next();
// System.out.println(c.getName()); // System.out.println(c.getName());
assertNotNull(c.getDownloadUrl()); assertThat(c.getDownloadUrl(), notNullValue());
assertNotNull(c.getOwner()); assertThat(c.getOwner(), notNullValue());
assertEquals("jquery/jquery", c.getOwner().getFullName()); assertThat(c.getOwner().getFullName(), equalTo("jquery/jquery"));
assertTrue(r.getTotalCount() > 0); assertThat(r.getTotalCount(), greaterThan(5));
PagedSearchIterable<GHContent> r2 = gitHub.searchContent()
.q("addClass")
.in("file")
.language("js")
.repo("jquery/jquery")
// resets query sort back to default
.sort(GHContentSearchBuilder.Sort.INDEXED)
.sort(GHContentSearchBuilder.Sort.BEST_MATCH)
// ignored unless sort is also set to non-default
.order(GHDirection.ASC)
.list();
GHContent c2 = r2.iterator().next();
assertThat(c2.getPath(), equalTo(c.getPath()));
assertThat(r2.getTotalCount(), equalTo(r.getTotalCount()));
PagedSearchIterable<GHContent> r3 = gitHub.searchContent()
.q("addClass")
.in("file")
.language("js")
.repo("jquery/jquery")
.sort(GHContentSearchBuilder.Sort.INDEXED)
.order(GHDirection.ASC)
.list();
GHContent c3 = r3.iterator().next();
assertThat(c3.getPath(), not(equalTo(c2.getPath())));
assertThat(r3.getTotalCount(), equalTo(r2.getTotalCount()));
PagedSearchIterable<GHContent> r4 = gitHub.searchContent()
.q("addClass")
.in("file")
.language("js")
.repo("jquery/jquery")
.sort(GHContentSearchBuilder.Sort.INDEXED)
.order(GHDirection.DESC)
.list();
GHContent c4 = r4.iterator().next();
assertThat(c4.getPath(), not(equalTo(c2.getPath())));
assertThat(c4.getPath(), not(equalTo(c3.getPath())));
assertThat(r4.getTotalCount(), equalTo(r2.getTotalCount()));
} }
@Test @Test
@@ -114,20 +159,20 @@ public class GitHubTest extends AbstractGitHubWireMockTest {
PagedIterable<GHAuthorization> list = gitHub.listMyAuthorizations(); PagedIterable<GHAuthorization> list = gitHub.listMyAuthorizations();
for (GHAuthorization auth : list) { for (GHAuthorization auth : list) {
assertNotNull(auth.getAppName()); assertThat(auth.getAppName(), notNullValue());
} }
} }
@Test @Test
public void getMeta() throws IOException { public void getMeta() throws IOException {
GHMeta meta = gitHub.getMeta(); GHMeta meta = gitHub.getMeta();
assertTrue(meta.isVerifiablePasswordAuthentication()); assertThat(meta.isVerifiablePasswordAuthentication(), is(true));
assertEquals(19, meta.getApi().size()); assertThat(meta.getApi().size(), equalTo(19));
assertEquals(19, meta.getGit().size()); assertThat(meta.getGit().size(), equalTo(19));
assertEquals(3, meta.getHooks().size()); assertThat(meta.getHooks().size(), equalTo(3));
assertEquals(6, meta.getImporter().size()); assertThat(meta.getImporter().size(), equalTo(6));
assertEquals(6, meta.getPages().size()); assertThat(meta.getPages().size(), equalTo(6));
assertEquals(19, meta.getWeb().size()); assertThat(meta.getWeb().size(), equalTo(19));
// Also test examples here // Also test examples here
Class[] examples = new Class[]{ ReadOnlyObjects.GHMetaPublic.class, ReadOnlyObjects.GHMetaPackage.class, Class[] examples = new Class[]{ ReadOnlyObjects.GHMetaPublic.class, ReadOnlyObjects.GHMetaPackage.class,
@@ -138,58 +183,58 @@ public class GitHubTest extends AbstractGitHubWireMockTest {
ReadOnlyObjects.GHMetaExample metaExample = gitHub.createRequest() ReadOnlyObjects.GHMetaExample metaExample = gitHub.createRequest()
.withUrlPath("/meta") .withUrlPath("/meta")
.fetch((Class<ReadOnlyObjects.GHMetaExample>) metaClass); .fetch((Class<ReadOnlyObjects.GHMetaExample>) metaClass);
assertTrue(metaExample.isVerifiablePasswordAuthentication()); assertThat(metaExample.isVerifiablePasswordAuthentication(), is(true));
assertEquals(19, metaExample.getApi().size()); assertThat(metaExample.getApi().size(), equalTo(19));
assertEquals(19, metaExample.getGit().size()); assertThat(metaExample.getGit().size(), equalTo(19));
assertEquals(3, metaExample.getHooks().size()); assertThat(metaExample.getHooks().size(), equalTo(3));
assertEquals(6, metaExample.getImporter().size()); assertThat(metaExample.getImporter().size(), equalTo(6));
assertEquals(6, metaExample.getPages().size()); assertThat(metaExample.getPages().size(), equalTo(6));
assertEquals(19, metaExample.getWeb().size()); assertThat(metaExample.getWeb().size(), equalTo(19));
} }
} }
@Test @Test
public void getMyMarketplacePurchases() throws IOException { public void getMyMarketplacePurchases() throws IOException {
List<GHMarketplaceUserPurchase> userPurchases = gitHub.getMyMarketplacePurchases().toList(); List<GHMarketplaceUserPurchase> userPurchases = gitHub.getMyMarketplacePurchases().toList();
assertEquals(2, userPurchases.size()); assertThat(userPurchases.size(), equalTo(2));
for (GHMarketplaceUserPurchase userPurchase : userPurchases) { for (GHMarketplaceUserPurchase userPurchase : userPurchases) {
assertFalse(userPurchase.isOnFreeTrial()); assertThat(userPurchase.isOnFreeTrial(), is(false));
assertNull(userPurchase.getFreeTrialEndsOn()); assertThat(userPurchase.getFreeTrialEndsOn(), nullValue());
assertEquals("monthly", userPurchase.getBillingCycle()); assertThat(userPurchase.getBillingCycle(), equalTo("monthly"));
GHMarketplacePlan plan = userPurchase.getPlan(); GHMarketplacePlan plan = userPurchase.getPlan();
// GHMarketplacePlan - Non-nullable fields // GHMarketplacePlan - Non-nullable fields
assertNotNull(plan.getUrl()); assertThat(plan.getUrl(), notNullValue());
assertNotNull(plan.getAccountsUrl()); assertThat(plan.getAccountsUrl(), notNullValue());
assertNotNull(plan.getName()); assertThat(plan.getName(), notNullValue());
assertNotNull(plan.getDescription()); assertThat(plan.getDescription(), notNullValue());
assertNotNull(plan.getPriceModel()); assertThat(plan.getPriceModel(), notNullValue());
assertNotNull(plan.getState()); assertThat(plan.getState(), notNullValue());
// GHMarketplacePlan - primitive fields // GHMarketplacePlan - primitive fields
assertNotEquals(0L, plan.getId()); assertThat(plan.getId(), not(0L));
assertNotEquals(0L, plan.getNumber()); assertThat(plan.getNumber(), not(0L));
assertTrue(plan.getMonthlyPriceInCents() >= 0); assertThat(plan.getMonthlyPriceInCents(), greaterThanOrEqualTo(0L));
// GHMarketplacePlan - list // GHMarketplacePlan - list
assertEquals(2, plan.getBullets().size()); assertThat(plan.getBullets().size(), equalTo(2));
GHMarketplaceAccount account = userPurchase.getAccount(); GHMarketplaceAccount account = userPurchase.getAccount();
// GHMarketplaceAccount - Non-nullable fields // GHMarketplaceAccount - Non-nullable fields
assertNotNull(account.getLogin()); assertThat(account.getLogin(), notNullValue());
assertNotNull(account.getUrl()); assertThat(account.getUrl(), notNullValue());
assertNotNull(account.getType()); assertThat(account.getType(), notNullValue());
// GHMarketplaceAccount - primitive fields // GHMarketplaceAccount - primitive fields
assertNotEquals(0L, account.getId()); assertThat(account.getId(), not(0L));
/* logical combination tests */ /* logical combination tests */
// Rationale: organization_billing_email is only set when account type is ORGANIZATION. // Rationale: organization_billing_email is only set when account type is ORGANIZATION.
if (account.getType() == ORGANIZATION) if (account.getType() == ORGANIZATION)
assertNotNull(account.getOrganizationBillingEmail()); assertThat(account.getOrganizationBillingEmail(), notNullValue());
else else
assertNull(account.getOrganizationBillingEmail()); assertThat(account.getOrganizationBillingEmail(), nullValue());
} }
} }
@@ -214,13 +259,11 @@ public class GitHubTest extends AbstractGitHubWireMockTest {
// getResponseHeaderFields is deprecated but we'll use it for testing. // getResponseHeaderFields is deprecated but we'll use it for testing.
assertThat(org.getResponseHeaderFields(), notNullValue()); assertThat(org.getResponseHeaderFields(), notNullValue());
// Header field names must be case-insensitive assertThat("Header field names must be case-insensitive",
assertThat(org.getResponseHeaderFields().containsKey("CacHe-ContrOl"), is(true)); org.getResponseHeaderFields().containsKey("CacHe-ContrOl"));
// The KeySet from header fields should also be case-insensitive
assertThat(org.getResponseHeaderFields().keySet().contains("CacHe-ControL"), is(true));
assertThat(org.getResponseHeaderFields().keySet().contains("CacHe-ControL"), is(true));
assertThat("KeySet from header fields should also be case-insensitive",
org.getResponseHeaderFields().keySet().contains("CacHe-ControL"));
assertThat(org.getResponseHeaderFields().get("cachE-cOntrol").get(0), is("private, max-age=60, s-maxage=60")); assertThat(org.getResponseHeaderFields().get("cachE-cOntrol").get(0), is("private, max-age=60, s-maxage=60"));
// GitHub has started changing their headers to all lowercase. // GitHub has started changing their headers to all lowercase.

View File

@@ -7,8 +7,6 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** /**
* @author Kevin Harrington mad.hephaestus@gmail.com * @author Kevin Harrington mad.hephaestus@gmail.com
@@ -17,7 +15,7 @@ public class Github2faTest extends AbstractGitHubWireMockTest {
@Test @Test
public void test2faToken() throws IOException { public void test2faToken() throws IOException {
assertFalse("Test only valid when not proxying", mockGitHub.isUseProxy()); assertThat("Test only valid when not proxying", mockGitHub.isUseProxy(), is(false));
List<String> asList = Arrays List<String> asList = Arrays
.asList("repo", "gist", "write:packages", "read:packages", "delete:packages", "user", "delete_repo"); .asList("repo", "gist", "write:packages", "read:packages", "delete:packages", "user", "delete_repo");
@@ -33,10 +31,7 @@ public class Github2faTest extends AbstractGitHubWireMockTest {
}); });
assertThat(token, notNullValue()); assertThat(token, notNullValue());
assertThat(token.getScopes(), contains(asList.toArray()));
for (int i = 0; i < asList.size(); i++) {
assertTrue(token.getScopes().get(i).contentEquals(asList.get(i)));
}
assertThat(token.getToken(), equalTo("63042a99d88bf138e6d6cf5788e0dc4e7a5d7309")); assertThat(token.getToken(), equalTo("63042a99d88bf138e6d6cf5788e0dc4e7a5d7309"));
assertThat(token.getTokenLastEight(), equalTo("7a5d7309")); assertThat(token.getTokenLastEight(), equalTo("7a5d7309"));

View File

@@ -10,8 +10,7 @@ import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.List; import java.util.List;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
public class LifecycleTest extends AbstractGitHubWireMockTest { public class LifecycleTest extends AbstractGitHubWireMockTest {
@Test @Test
@@ -22,7 +21,7 @@ public class LifecycleTest extends AbstractGitHubWireMockTest {
// GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); // GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG);
GHRepository repository = getTempRepository(); GHRepository repository = getTempRepository();
assertTrue(repository.getReleases().isEmpty()); assertThat(repository.getReleases(), is(empty()));
GHMilestone milestone = repository.createMilestone("Initial Release", "first one"); GHMilestone milestone = repository.createMilestone("Initial Release", "first one");
GHIssue issue = repository.createIssue("Test Issue") GHIssue issue = repository.createIssue("Test Issue")
@@ -45,22 +44,22 @@ public class LifecycleTest extends AbstractGitHubWireMockTest {
private void updateAsset(GHRelease release, GHAsset asset) throws IOException { private void updateAsset(GHRelease release, GHAsset asset) throws IOException {
asset.setLabel("test label"); asset.setLabel("test label");
assertEquals("test label", release.getAssets().get(0).getLabel()); assertThat(release.getAssets().get(0).getLabel(), equalTo("test label"));
} }
private void deleteAsset(GHRelease release, GHAsset asset) throws IOException { private void deleteAsset(GHRelease release, GHAsset asset) throws IOException {
asset.delete(); asset.delete();
assertEquals(0, release.getAssets().size()); assertThat(release.getAssets(), is(empty()));
} }
private GHAsset uploadAsset(GHRelease release) throws IOException { private GHAsset uploadAsset(GHRelease release) throws IOException {
GHAsset asset = release.uploadAsset(new File("LICENSE.txt"), "application/text"); GHAsset asset = release.uploadAsset(new File("LICENSE.txt"), "application/text");
assertNotNull(asset); assertThat(asset, notNullValue());
List<GHAsset> cachedAssets = release.assets(); List<GHAsset> cachedAssets = release.assets();
assertEquals(0, cachedAssets.size()); assertThat(cachedAssets, is(empty()));
List<GHAsset> assets = release.getAssets(); List<GHAsset> assets = release.getAssets();
assertEquals(1, assets.size()); assertThat(assets.size(), equalTo(1));
assertEquals("LICENSE.txt", assets.get(0).getName()); assertThat(assets.get(0).getName(), equalTo("LICENSE.txt"));
assertThat(assets.get(0).getSize(), equalTo(1104L)); assertThat(assets.get(0).getSize(), equalTo(1104L));
assertThat(assets.get(0).getContentType(), equalTo("application/text")); assertThat(assets.get(0).getContentType(), equalTo("application/text"));
assertThat(assets.get(0).getState(), equalTo("uploaded")); assertThat(assets.get(0).getState(), equalTo("uploaded"));
@@ -78,16 +77,16 @@ public class LifecycleTest extends AbstractGitHubWireMockTest {
.body("How exciting! To be able to programmatically create releases is a dream come true!") .body("How exciting! To be able to programmatically create releases is a dream come true!")
.create(); .create();
List<GHRelease> releases = repository.getReleases(); List<GHRelease> releases = repository.getReleases();
assertEquals(1, releases.size()); assertThat(releases.size(), equalTo(1));
GHRelease release = releases.get(0); GHRelease release = releases.get(0);
assertEquals("Test Release", release.getName()); assertThat(release.getName(), equalTo("Test Release"));
assertThat(release.getBody(), startsWith("How exciting!")); assertThat(release.getBody(), startsWith("How exciting!"));
assertThat(release.getOwner(), sameInstance(repository)); assertThat(release.getOwner(), sameInstance(repository));
assertThat(release.getZipballUrl(), assertThat(release.getZipballUrl(),
endsWith("/repos/hub4j-test-org/temp-testCreateRepository/zipball/release_tag")); endsWith("/repos/hub4j-test-org/temp-testCreateRepository/zipball/release_tag"));
assertThat(release.getTarballUrl(), assertThat(release.getTarballUrl(),
endsWith("/repos/hub4j-test-org/temp-testCreateRepository/tarball/release_tag")); endsWith("/repos/hub4j-test-org/temp-testCreateRepository/tarball/release_tag"));
assertThat(release.getTargetCommitish(), equalTo("master")); assertThat(release.getTargetCommitish(), equalTo("main"));
assertThat(release.getHtmlUrl().toString(), assertThat(release.getHtmlUrl().toString(),
endsWith("/hub4j-test-org/temp-testCreateRepository/releases/tag/release_tag")); endsWith("/hub4j-test-org/temp-testCreateRepository/releases/tag/release_tag"));

View File

@@ -1,6 +1,6 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.junit.Assert; import org.hamcrest.Matchers;
import org.junit.Test; import org.junit.Test;
import org.kohsuke.github.GHRepositoryTraffic.DailyInfo; import org.kohsuke.github.GHRepositoryTraffic.DailyInfo;
@@ -14,24 +14,24 @@ public class RepositoryTrafficTest extends AbstractGitHubWireMockTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T extends GHRepositoryTraffic> void checkResponse(T expected, T actual) { private <T extends GHRepositoryTraffic> void checkResponse(T expected, T actual) {
Assert.assertEquals(expected.getCount(), actual.getCount()); assertThat(actual.getCount(), Matchers.equalTo(expected.getCount()));
Assert.assertEquals(expected.getUniques(), actual.getUniques()); assertThat(actual.getUniques(), Matchers.equalTo(expected.getUniques()));
List<? extends DailyInfo> expectedList = expected.getDailyInfo(); List<? extends DailyInfo> expectedList = expected.getDailyInfo();
List<? extends DailyInfo> actualList = actual.getDailyInfo(); List<? extends DailyInfo> actualList = actual.getDailyInfo();
Iterator<? extends DailyInfo> expectedIt; Iterator<? extends DailyInfo> expectedIt;
Iterator<? extends DailyInfo> actualIt; Iterator<? extends DailyInfo> actualIt;
Assert.assertEquals(expectedList.size(), actualList.size()); assertThat(actualList.size(), Matchers.equalTo(expectedList.size()));
expectedIt = expectedList.iterator(); expectedIt = expectedList.iterator();
actualIt = actualList.iterator(); actualIt = actualList.iterator();
while (expectedIt.hasNext() && actualIt.hasNext()) { while (expectedIt.hasNext() && actualIt.hasNext()) {
DailyInfo expectedDailyInfo = expectedIt.next(); DailyInfo expectedDailyInfo = expectedIt.next();
DailyInfo actualDailyInfo = actualIt.next(); DailyInfo actualDailyInfo = actualIt.next();
Assert.assertEquals(expectedDailyInfo.getCount(), actualDailyInfo.getCount()); assertThat(actualDailyInfo.getCount(), Matchers.equalTo(expectedDailyInfo.getCount()));
Assert.assertEquals(expectedDailyInfo.getUniques(), actualDailyInfo.getUniques()); assertThat(actualDailyInfo.getUniques(), Matchers.equalTo(expectedDailyInfo.getUniques()));
Assert.assertEquals(expectedDailyInfo.getTimestamp(), actualDailyInfo.getTimestamp()); assertThat(actualDailyInfo.getTimestamp(), Matchers.equalTo(expectedDailyInfo.getTimestamp()));
} }
} }
@@ -100,12 +100,12 @@ public class RepositoryTrafficTest extends AbstractGitHubWireMockTest {
GHRepository repo = gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository(repositoryName); GHRepository repo = gitHub.getOrganization(GITHUB_API_TEST_ORG).getRepository(repositoryName);
try { try {
repo.getViewTraffic(); repo.getViewTraffic();
Assert.fail(errorMsg); fail(errorMsg);
} catch (HttpException ex) { } catch (HttpException ex) {
} }
try { try {
repo.getCloneTraffic(); repo.getCloneTraffic();
Assert.fail(errorMsg); fail(errorMsg);
} catch (HttpException ex) { } catch (HttpException ex) {
} }
} }

View File

@@ -97,7 +97,7 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
try { try {
gitHub.checkApiUrlValidity(); gitHub.checkApiUrlValidity();
} catch (IOException ioe) { } catch (IOException ioe) {
assertTrue(ioe.getMessage().contains("private mode enabled")); assertThat(ioe.getMessage(), containsString("private mode enabled"));
} }
Thread.sleep(100); Thread.sleep(100);
} }
@@ -127,8 +127,8 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
} }
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertTrue(capturedLog.contains("will try 2 more time")); assertThat(capturedLog.contains("will try 2 more time"), is(true));
assertTrue(capturedLog.contains("will try 1 more time")); assertThat(capturedLog.contains("will try 1 more time"), is(true));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 6)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 6));
} }
@@ -156,8 +156,8 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
} }
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertTrue(capturedLog.contains("will try 2 more time")); assertThat(capturedLog.contains("will try 2 more time"), is(true));
assertTrue(capturedLog.contains("will try 1 more time")); assertThat(capturedLog.contains("will try 1 more time"), is(true));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 6)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 6));
} }
@@ -206,8 +206,8 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
GHBranch branch = repo.getBranch("test/timeout"); GHBranch branch = repo.getBranch("test/timeout");
assertThat(branch, notNullValue()); assertThat(branch, notNullValue());
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertTrue(capturedLog.contains("will try 2 more time")); assertThat(capturedLog.contains("will try 2 more time"), is(true));
assertTrue(capturedLog.contains("will try 1 more time")); assertThat(capturedLog.contains("will try 1 more time"), is(true));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 6)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 6));
} }
@@ -232,8 +232,8 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause(), instanceOf(IOException.class));
assertThat(e.getCause().getMessage(), is("Custom")); assertThat(e.getCause().getMessage(), is("Custom"));
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertFalse(capturedLog.contains("will try 2 more time")); assertThat(capturedLog.contains("will try 2 more time"), is(false));
assertFalse(capturedLog.contains("will try 1 more time")); assertThat(capturedLog.contains("will try 1 more time"), is(false));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount));
} }
@@ -253,8 +253,8 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
assertThat(e, instanceOf(FileNotFoundException.class)); assertThat(e, instanceOf(FileNotFoundException.class));
assertThat(e.getMessage(), is("Custom")); assertThat(e.getMessage(), is("Custom"));
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertFalse(capturedLog.contains("will try 2 more time")); assertThat(capturedLog.contains("will try 2 more time"), is(false));
assertFalse(capturedLog.contains("will try 1 more time")); assertThat(capturedLog.contains("will try 1 more time"), is(false));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount));
} }
} }
@@ -279,8 +279,8 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause(), instanceOf(IOException.class));
assertThat(e.getCause().getMessage(), is("Custom")); assertThat(e.getCause().getMessage(), is("Custom"));
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertFalse(capturedLog.contains("will try 2 more time")); assertThat(capturedLog.contains("will try 2 more time"), is(false));
assertFalse(capturedLog.contains("will try 1 more time")); assertThat(capturedLog.contains("will try 1 more time"), is(false));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 1)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 1));
} }
@@ -297,8 +297,8 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
assertThat(e.getCause(), instanceOf(FileNotFoundException.class)); assertThat(e.getCause(), instanceOf(FileNotFoundException.class));
assertThat(e.getCause().getMessage(), containsString("hub4j-test-org-missing")); assertThat(e.getCause().getMessage(), containsString("hub4j-test-org-missing"));
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertFalse(capturedLog.contains("will try 2 more time")); assertThat(capturedLog.contains("will try 2 more time"), is(false));
assertFalse(capturedLog.contains("will try 1 more time")); assertThat(capturedLog.contains("will try 1 more time"), is(false));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 1)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 1));
} }
@@ -313,8 +313,8 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
.fetchHttpStatusCode(), .fetchHttpStatusCode(),
equalTo(404)); equalTo(404));
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertFalse(capturedLog.contains("will try 2 more time")); assertThat(capturedLog.contains("will try 2 more time"), is(false));
assertFalse(capturedLog.contains("will try 1 more time")); assertThat(capturedLog.contains("will try 1 more time"), is(false));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 1)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 1));
} }
@@ -373,16 +373,16 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
baseRequestCount = this.mockGitHub.getRequestCount(); baseRequestCount = this.mockGitHub.getRequestCount();
assertThat(this.gitHub.getOrganization(GITHUB_API_TEST_ORG), is(notNullValue())); assertThat(this.gitHub.getOrganization(GITHUB_API_TEST_ORG), is(notNullValue()));
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
assertTrue(capturedLog.contains("will try 2 more time")); assertThat(capturedLog, containsString("will try 2 more time"));
assertTrue(capturedLog.contains("will try 1 more time")); assertThat(capturedLog, containsString("will try 1 more time"));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + expectedRequestCount)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + expectedRequestCount));
resetTestCapturedLog(); resetTestCapturedLog();
baseRequestCount = this.mockGitHub.getRequestCount(); baseRequestCount = this.mockGitHub.getRequestCount();
this.gitHub.createRequest().withUrlPath("/orgs/" + GITHUB_API_TEST_ORG).send(); this.gitHub.createRequest().withUrlPath("/orgs/" + GITHUB_API_TEST_ORG).send();
capturedLog = getTestCapturedLog(); capturedLog = getTestCapturedLog();
assertTrue(capturedLog.contains("will try 2 more time")); assertThat(capturedLog, containsString("will try 2 more time"));
assertTrue(capturedLog.contains("will try 1 more time")); assertThat(capturedLog, containsString("will try 1 more time"));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + expectedRequestCount)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + expectedRequestCount));
} }
@@ -399,13 +399,13 @@ public class RequesterRetryTest extends AbstractGitHubWireMockTest {
equalTo(200)); equalTo(200));
String capturedLog = getTestCapturedLog(); String capturedLog = getTestCapturedLog();
if (expectedRequestCount > 0) { if (expectedRequestCount > 0) {
assertTrue(capturedLog.contains("will try 2 more time")); assertThat(capturedLog, containsString("will try 2 more time"));
assertTrue(capturedLog.contains("will try 1 more time")); assertThat(capturedLog, containsString("will try 1 more time"));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + expectedRequestCount)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + expectedRequestCount));
} else { } else {
// Success without retries // Success without retries
assertFalse(capturedLog.contains("will try 2 more time")); assertThat(capturedLog, not(containsString("will try 2 more time")));
assertFalse(capturedLog.contains("will try 1 more time")); assertThat(capturedLog, not(containsString("will try 1 more time")));
assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 1)); assertThat(this.mockGitHub.getRequestCount(), equalTo(baseRequestCount + 1));
} }
} }

View File

@@ -4,10 +4,7 @@ import org.hamcrest.Matchers;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
@@ -133,7 +130,7 @@ public class WireMockStatusReporterTest extends AbstractGitHubWireMockTest {
assumeTrue("Test only valid when Snapshotting (-Dtest.github.takeSnapshot to enable)", assumeTrue("Test only valid when Snapshotting (-Dtest.github.takeSnapshot to enable)",
mockGitHub.isTakeSnapshot()); mockGitHub.isTakeSnapshot());
assertTrue("When taking a snapshot, proxy should automatically be enabled", mockGitHub.isUseProxy()); assertThat("When taking a snapshot, proxy should automatically be enabled", mockGitHub.isUseProxy());
} }
@Ignore("Not implemented yet") @Ignore("Not implemented yet")

View File

@@ -43,11 +43,11 @@ public class GitHubCachingTest extends AbstractGitHubWireMockTest {
@Before @Before
public void setupRepo() throws Exception { public void setupRepo() throws Exception {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
for (GHPullRequest pr : getRepository(this.getGitHubBeforeAfter()).getPullRequests(GHIssueState.OPEN)) { for (GHPullRequest pr : getRepository(this.getNonRecordingGitHub()).getPullRequests(GHIssueState.OPEN)) {
pr.close(); pr.close();
} }
try { try {
GHRef ref = getRepository(this.getGitHubBeforeAfter()).getRef(testRefName); GHRef ref = getRepository(this.getNonRecordingGitHub()).getRef(testRefName);
ref.delete(); ref.delete();
} catch (IOException e) { } catch (IOException e) {
} }

View File

@@ -73,7 +73,7 @@ public class OkHttpConnectorTest extends AbstractGitHubWireMockTest {
@Before @Before
public void setupRepo() throws Exception { public void setupRepo() throws Exception {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
GHRepository repo = getRepository(getGitHubBeforeAfter()); GHRepository repo = getRepository(getNonRecordingGitHub());
repo.setDescription("Resetting"); repo.setDescription("Resetting");
// Let things settle a bit between tests when working against the live site // Let things settle a bit between tests when working against the live site
@@ -252,7 +252,7 @@ public class OkHttpConnectorTest extends AbstractGitHubWireMockTest {
// Get Tricky - make a change via a different client // Get Tricky - make a change via a different client
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
GHRepository altRepo = getRepository(getGitHubBeforeAfter()); GHRepository altRepo = getRepository(getNonRecordingGitHub());
altRepo.setDescription("Tricky"); altRepo.setDescription("Tricky");
} }

View File

@@ -45,11 +45,11 @@ public class GitHubCachingTest extends AbstractGitHubWireMockTest {
@Before @Before
public void setupRepo() throws Exception { public void setupRepo() throws Exception {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
for (GHPullRequest pr : getRepository(this.getGitHubBeforeAfter()).getPullRequests(GHIssueState.OPEN)) { for (GHPullRequest pr : getRepository(this.getNonRecordingGitHub()).getPullRequests(GHIssueState.OPEN)) {
pr.close(); pr.close();
} }
try { try {
GHRef ref = getRepository(this.getGitHubBeforeAfter()).getRef(testRefName); GHRef ref = getRepository(this.getNonRecordingGitHub()).getRef(testRefName);
ref.delete(); ref.delete();
} catch (IOException e) { } catch (IOException e) {
} }

View File

@@ -79,7 +79,7 @@ public class OkHttpConnectorTest extends AbstractGitHubWireMockTest {
@Before @Before
public void setupRepo() throws Exception { public void setupRepo() throws Exception {
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
GHRepository repo = getRepository(getGitHubBeforeAfter()); GHRepository repo = getRepository(getNonRecordingGitHub());
repo.setDescription("Resetting"); repo.setDescription("Resetting");
// Let things settle a bit between tests when working against the live site // Let things settle a bit between tests when working against the live site
@@ -261,7 +261,7 @@ public class OkHttpConnectorTest extends AbstractGitHubWireMockTest {
// Get Tricky - make a change via a different client // Get Tricky - make a change via a different client
if (mockGitHub.isUseProxy()) { if (mockGitHub.isUseProxy()) {
GHRepository altRepo = getRepository(getGitHubBeforeAfter()); GHRepository altRepo = getRepository(getNonRecordingGitHub());
altRepo.setDescription("Tricky"); altRepo.setDescription("Tricky");
} }

View File

@@ -2,19 +2,24 @@ package org.kohsuke.github.internal;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNull; import static org.hamcrest.Matchers.*;
public class EnumUtilsTest { public class EnumUtilsTest {
@Test @Test
public void testGetEnum() { public void testGetEnum() {
assertNull(EnumUtils.getNullableEnumOrDefault(TestEnum.class, null, TestEnum.UNKNOWN)); assertThat(EnumUtils.getNullableEnumOrDefault(TestEnum.class, null, TestEnum.UNKNOWN), nullValue());
assertEquals(TestEnum.UNKNOWN, EnumUtils.getNullableEnumOrDefault(TestEnum.class, "foobar", TestEnum.UNKNOWN)); assertThat(EnumUtils.getNullableEnumOrDefault(TestEnum.class, "foobar", TestEnum.UNKNOWN),
assertEquals(TestEnum.VALUE_1, EnumUtils.getNullableEnumOrDefault(TestEnum.class, "VALUE_1", TestEnum.UNKNOWN)); equalTo(TestEnum.UNKNOWN));
assertEquals(TestEnum.VALUE_1, EnumUtils.getNullableEnumOrDefault(TestEnum.class, "value_1", TestEnum.UNKNOWN)); assertThat(EnumUtils.getNullableEnumOrDefault(TestEnum.class, "VALUE_1", TestEnum.UNKNOWN),
assertEquals(TestEnum.VALUE_2, EnumUtils.getNullableEnumOrDefault(TestEnum.class, "VALUE_2", TestEnum.UNKNOWN)); equalTo(TestEnum.VALUE_1));
assertEquals(TestEnum.VALUE_2, EnumUtils.getNullableEnumOrDefault(TestEnum.class, "value_2", TestEnum.UNKNOWN)); assertThat(EnumUtils.getNullableEnumOrDefault(TestEnum.class, "value_1", TestEnum.UNKNOWN),
equalTo(TestEnum.VALUE_1));
assertThat(EnumUtils.getNullableEnumOrDefault(TestEnum.class, "VALUE_2", TestEnum.UNKNOWN),
equalTo(TestEnum.VALUE_2));
assertThat(EnumUtils.getNullableEnumOrDefault(TestEnum.class, "vAlUe_2", TestEnum.UNKNOWN),
equalTo(TestEnum.VALUE_2));
} }
private enum TestEnum { private enum TestEnum {

View File

@@ -159,6 +159,9 @@ public class GitHubWireMockRule extends WireMockMultiServerRule {
if (server != null) { if (server != null) {
server.snapshotRecord(recordSpec().forTarget(target) server.snapshotRecord(recordSpec().forTarget(target)
// "X-HTTP-Method-Override" is used to send http methods not supported by
// HttpURLConnection without using hacky Java reflection techniques
.captureHeader("X-HTTP-Method-Override")
// "If-None-Match" header used for ETag matching for caching connections // "If-None-Match" header used for ETag matching for caching connections
.captureHeader("If-None-Match") .captureHeader("If-None-Match")
// "If-Modified-Since" header used for ETag matching for caching connections // "If-Modified-Since" header used for ETag matching for caching connections

View File

@@ -90,7 +90,7 @@
"forks": 0, "forks": 0,
"open_issues": 0, "open_issues": 0,
"watchers": 0, "watchers": 0,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -90,7 +90,7 @@
"forks": 0, "forks": 0,
"open_issues": 0, "open_issues": 0,
"watchers": 0, "watchers": 0,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -90,7 +90,7 @@
"forks": 0, "forks": 0,
"open_issues": 0, "open_issues": 0,
"watchers": 0, "watchers": 0,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -96,7 +96,7 @@
"forks": 433, "forks": 433,
"open_issues": 64, "open_issues": 64,
"watchers": 565, "watchers": 565,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -96,7 +96,7 @@
"forks": 5807, "forks": 5807,
"open_issues": 74, "open_issues": 74,
"watchers": 14167, "watchers": 14167,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": false, "admin": false,
"push": false, "push": false,

View File

@@ -4,15 +4,15 @@
"path": "core/move-l10n.groovy", "path": "core/move-l10n.groovy",
"sha": "8d002348827a6c76ec3b4832278384c74a91d692", "sha": "8d002348827a6c76ec3b4832278384c74a91d692",
"size": 1560, "size": 1560,
"url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/move-l10n.groovy?ref=master", "url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/move-l10n.groovy?ref=main",
"html_url": "https://github.com/jenkinsci/jenkins/blob/master/core/move-l10n.groovy", "html_url": "https://github.com/jenkinsci/jenkins/blob/main/core/move-l10n.groovy",
"git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/8d002348827a6c76ec3b4832278384c74a91d692", "git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/8d002348827a6c76ec3b4832278384c74a91d692",
"download_url": "https://raw.githubusercontent.com/jenkinsci/jenkins/master/core/move-l10n.groovy", "download_url": "https://raw.githubusercontent.com/jenkinsci/jenkins/main/core/move-l10n.groovy",
"type": "file", "type": "file",
"_links": { "_links": {
"self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/move-l10n.groovy?ref=master", "self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/move-l10n.groovy?ref=main",
"git": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/8d002348827a6c76ec3b4832278384c74a91d692", "git": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/8d002348827a6c76ec3b4832278384c74a91d692",
"html": "https://github.com/jenkinsci/jenkins/blob/master/core/move-l10n.groovy" "html": "https://github.com/jenkinsci/jenkins/blob/main/core/move-l10n.groovy"
} }
}, },
{ {
@@ -20,15 +20,15 @@
"path": "core/pom.xml", "path": "core/pom.xml",
"sha": "0402553742ec270b65e5ea4c0851088659987183", "sha": "0402553742ec270b65e5ea4c0851088659987183",
"size": 28950, "size": 28950,
"url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/pom.xml?ref=master", "url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/pom.xml?ref=main",
"html_url": "https://github.com/jenkinsci/jenkins/blob/master/core/pom.xml", "html_url": "https://github.com/jenkinsci/jenkins/blob/main/core/pom.xml",
"git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/0402553742ec270b65e5ea4c0851088659987183", "git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/0402553742ec270b65e5ea4c0851088659987183",
"download_url": "https://raw.githubusercontent.com/jenkinsci/jenkins/master/core/pom.xml", "download_url": "https://raw.githubusercontent.com/jenkinsci/jenkins/main/core/pom.xml",
"type": "file", "type": "file",
"_links": { "_links": {
"self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/pom.xml?ref=master", "self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/pom.xml?ref=main",
"git": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/0402553742ec270b65e5ea4c0851088659987183", "git": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/0402553742ec270b65e5ea4c0851088659987183",
"html": "https://github.com/jenkinsci/jenkins/blob/master/core/pom.xml" "html": "https://github.com/jenkinsci/jenkins/blob/main/core/pom.xml"
} }
}, },
{ {
@@ -36,15 +36,15 @@
"path": "core/report-l10n.rb", "path": "core/report-l10n.rb",
"sha": "d48bf4d2f9ed5de92f6d4a9864ecc168d15e3420", "sha": "d48bf4d2f9ed5de92f6d4a9864ecc168d15e3420",
"size": 17290, "size": 17290,
"url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/report-l10n.rb?ref=master", "url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/report-l10n.rb?ref=main",
"html_url": "https://github.com/jenkinsci/jenkins/blob/master/core/report-l10n.rb", "html_url": "https://github.com/jenkinsci/jenkins/blob/main/core/report-l10n.rb",
"git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/d48bf4d2f9ed5de92f6d4a9864ecc168d15e3420", "git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/d48bf4d2f9ed5de92f6d4a9864ecc168d15e3420",
"download_url": "https://raw.githubusercontent.com/jenkinsci/jenkins/master/core/report-l10n.rb", "download_url": "https://raw.githubusercontent.com/jenkinsci/jenkins/main/core/report-l10n.rb",
"type": "file", "type": "file",
"_links": { "_links": {
"self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/report-l10n.rb?ref=master", "self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/report-l10n.rb?ref=main",
"git": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/d48bf4d2f9ed5de92f6d4a9864ecc168d15e3420", "git": "https://api.github.com/repos/jenkinsci/jenkins/git/blobs/d48bf4d2f9ed5de92f6d4a9864ecc168d15e3420",
"html": "https://github.com/jenkinsci/jenkins/blob/master/core/report-l10n.rb" "html": "https://github.com/jenkinsci/jenkins/blob/main/core/report-l10n.rb"
} }
}, },
{ {
@@ -52,15 +52,15 @@
"path": "core/src", "path": "core/src",
"sha": "11d50acb5fba7764e8ef1c230aac16aa9aa0ef31", "sha": "11d50acb5fba7764e8ef1c230aac16aa9aa0ef31",
"size": 0, "size": 0,
"url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src?ref=master", "url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src?ref=main",
"html_url": "https://github.com/jenkinsci/jenkins/tree/master/core/src", "html_url": "https://github.com/jenkinsci/jenkins/tree/main/core/src",
"git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/11d50acb5fba7764e8ef1c230aac16aa9aa0ef31", "git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/11d50acb5fba7764e8ef1c230aac16aa9aa0ef31",
"download_url": null, "download_url": null,
"type": "dir", "type": "dir",
"_links": { "_links": {
"self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src?ref=master", "self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src?ref=main",
"git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/11d50acb5fba7764e8ef1c230aac16aa9aa0ef31", "git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/11d50acb5fba7764e8ef1c230aac16aa9aa0ef31",
"html": "https://github.com/jenkinsci/jenkins/tree/master/core/src" "html": "https://github.com/jenkinsci/jenkins/tree/main/core/src"
} }
} }
] ]

View File

@@ -4,15 +4,15 @@
"path": "core/src/filter", "path": "core/src/filter",
"sha": "5f087f4c3dd2690948371b4f867087d36fdbb19d", "sha": "5f087f4c3dd2690948371b4f867087d36fdbb19d",
"size": 0, "size": 0,
"url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/filter?ref=master", "url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/filter?ref=main",
"html_url": "https://github.com/jenkinsci/jenkins/tree/master/core/src/filter", "html_url": "https://github.com/jenkinsci/jenkins/tree/main/core/src/filter",
"git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/5f087f4c3dd2690948371b4f867087d36fdbb19d", "git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/5f087f4c3dd2690948371b4f867087d36fdbb19d",
"download_url": null, "download_url": null,
"type": "dir", "type": "dir",
"_links": { "_links": {
"self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/filter?ref=master", "self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/filter?ref=main",
"git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/5f087f4c3dd2690948371b4f867087d36fdbb19d", "git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/5f087f4c3dd2690948371b4f867087d36fdbb19d",
"html": "https://github.com/jenkinsci/jenkins/tree/master/core/src/filter" "html": "https://github.com/jenkinsci/jenkins/tree/main/core/src/filter"
} }
}, },
{ {
@@ -20,15 +20,15 @@
"path": "core/src/main", "path": "core/src/main",
"sha": "7334485bc5155447be2692f1d4acf9c717335d7b", "sha": "7334485bc5155447be2692f1d4acf9c717335d7b",
"size": 0, "size": 0,
"url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/main?ref=master", "url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/main?ref=main",
"html_url": "https://github.com/jenkinsci/jenkins/tree/master/core/src/main", "html_url": "https://github.com/jenkinsci/jenkins/tree/main/core/src/main",
"git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/7334485bc5155447be2692f1d4acf9c717335d7b", "git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/7334485bc5155447be2692f1d4acf9c717335d7b",
"download_url": null, "download_url": null,
"type": "dir", "type": "dir",
"_links": { "_links": {
"self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/main?ref=master", "self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/main?ref=main",
"git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/7334485bc5155447be2692f1d4acf9c717335d7b", "git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/7334485bc5155447be2692f1d4acf9c717335d7b",
"html": "https://github.com/jenkinsci/jenkins/tree/master/core/src/main" "html": "https://github.com/jenkinsci/jenkins/tree/main/core/src/main"
} }
}, },
{ {
@@ -36,15 +36,15 @@
"path": "core/src/site", "path": "core/src/site",
"sha": "59d5107eeacdac5a50a2e2eb3592d79c9a8f8743", "sha": "59d5107eeacdac5a50a2e2eb3592d79c9a8f8743",
"size": 0, "size": 0,
"url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/site?ref=master", "url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/site?ref=main",
"html_url": "https://github.com/jenkinsci/jenkins/tree/master/core/src/site", "html_url": "https://github.com/jenkinsci/jenkins/tree/main/core/src/site",
"git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/59d5107eeacdac5a50a2e2eb3592d79c9a8f8743", "git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/59d5107eeacdac5a50a2e2eb3592d79c9a8f8743",
"download_url": null, "download_url": null,
"type": "dir", "type": "dir",
"_links": { "_links": {
"self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/site?ref=master", "self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/site?ref=main",
"git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/59d5107eeacdac5a50a2e2eb3592d79c9a8f8743", "git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/59d5107eeacdac5a50a2e2eb3592d79c9a8f8743",
"html": "https://github.com/jenkinsci/jenkins/tree/master/core/src/site" "html": "https://github.com/jenkinsci/jenkins/tree/main/core/src/site"
} }
}, },
{ {
@@ -52,15 +52,15 @@
"path": "core/src/test", "path": "core/src/test",
"sha": "d600ddfd8eebaf8b605d9f99d3a9f117fac2eb2b", "sha": "d600ddfd8eebaf8b605d9f99d3a9f117fac2eb2b",
"size": 0, "size": 0,
"url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/test?ref=master", "url": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/test?ref=main",
"html_url": "https://github.com/jenkinsci/jenkins/tree/master/core/src/test", "html_url": "https://github.com/jenkinsci/jenkins/tree/main/core/src/test",
"git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/d600ddfd8eebaf8b605d9f99d3a9f117fac2eb2b", "git_url": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/d600ddfd8eebaf8b605d9f99d3a9f117fac2eb2b",
"download_url": null, "download_url": null,
"type": "dir", "type": "dir",
"_links": { "_links": {
"self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/test?ref=master", "self": "https://api.github.com/repos/jenkinsci/jenkins/contents/core/src/test?ref=main",
"git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/d600ddfd8eebaf8b605d9f99d3a9f117fac2eb2b", "git": "https://api.github.com/repos/jenkinsci/jenkins/git/trees/d600ddfd8eebaf8b605d9f99d3a9f117fac2eb2b",
"html": "https://github.com/jenkinsci/jenkins/tree/master/core/src/test" "html": "https://github.com/jenkinsci/jenkins/tree/main/core/src/test"
} }
} }
] ]

View File

@@ -2,7 +2,7 @@
"id": "0566ab8b-d260-47cb-a6e6-fafa6fc2836c", "id": "0566ab8b-d260-47cb-a6e6-fafa6fc2836c",
"name": "repos_jenkinsci_jenkins_contents_core_src", "name": "repos_jenkinsci_jenkins_contents_core_src",
"request": { "request": {
"url": "/repos/jenkinsci/jenkins/contents/core/src?ref=master", "url": "/repos/jenkinsci/jenkins/contents/core/src?ref=main",
"method": "GET", "method": "GET",
"headers": { "headers": {
"Accept": { "Accept": {

View File

@@ -827,15 +827,15 @@
"last_read_at": "2019-09-11T00:03:20Z", "last_read_at": "2019-09-11T00:03:20Z",
"subject": { "subject": {
"title": "[CPLT2-5785] Define jenkins.hook.url when appropriate", "title": "[CPLT2-5785] Define jenkins.hook.url when appropriate",
"url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/pulls/15", "url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/pulls/15",
"latest_comment_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/pulls/15", "latest_comment_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/pulls/15",
"type": "PullRequest" "type": "PullRequest"
}, },
"repository": { "repository": {
"id": 202214807, "id": 202214807,
"node_id": "MDEwOlJlcG9zaXRvcnkyMDIyMTQ4MDc=", "node_id": "MDEwOlJlcG9zaXRvcnkyMDIyMTQ4MDc=",
"name": "managed-master-hibernation-plugin", "name": "managed-main-hibernation-plugin",
"full_name": "cloudbees/managed-master-hibernation-plugin", "full_name": "cloudbees/managed-main-hibernation-plugin",
"private": true, "private": true,
"owner": { "owner": {
"login": "cloudbees", "login": "cloudbees",
@@ -857,46 +857,46 @@
"type": "Organization", "type": "Organization",
"site_admin": false "site_admin": false
}, },
"html_url": "https://github.com/cloudbees/managed-master-hibernation-plugin", "html_url": "https://github.com/cloudbees/managed-main-hibernation-plugin",
"description": "CPLT2-5737: Allows a managed master to indicate that it is ready to be hibernated.", "description": "CPLT2-5737: Allows a managed main to indicate that it is ready to be hibernated.",
"fork": false, "fork": false,
"url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin", "url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin",
"forks_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/forks", "forks_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/forks",
"keys_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/keys{/key_id}", "keys_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/keys{/key_id}",
"collaborators_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/collaborators{/collaborator}", "collaborators_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/collaborators{/collaborator}",
"teams_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/teams", "teams_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/teams",
"hooks_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/hooks", "hooks_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/hooks",
"issue_events_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/issues/events{/number}", "issue_events_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/issues/events{/number}",
"events_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/events", "events_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/events",
"assignees_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/assignees{/user}", "assignees_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/assignees{/user}",
"branches_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/branches{/branch}", "branches_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/branches{/branch}",
"tags_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/tags", "tags_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/tags",
"blobs_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/git/blobs{/sha}", "blobs_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/git/blobs{/sha}",
"git_tags_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/git/tags{/sha}", "git_tags_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/git/tags{/sha}",
"git_refs_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/git/refs{/sha}", "git_refs_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/git/refs{/sha}",
"trees_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/git/trees{/sha}", "trees_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/git/trees{/sha}",
"statuses_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/statuses/{sha}", "statuses_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/statuses/{sha}",
"languages_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/languages", "languages_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/languages",
"stargazers_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/stargazers", "stargazers_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/stargazers",
"contributors_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/contributors", "contributors_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/contributors",
"subscribers_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/subscribers", "subscribers_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/subscribers",
"subscription_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/subscription", "subscription_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/subscription",
"commits_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/commits{/sha}", "commits_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/commits{/sha}",
"git_commits_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/git/commits{/sha}", "git_commits_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/git/commits{/sha}",
"comments_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/comments{/number}", "comments_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/comments{/number}",
"issue_comment_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/issues/comments{/number}", "issue_comment_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/issues/comments{/number}",
"contents_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/contents/{+path}", "contents_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/contents/{+path}",
"compare_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/compare/{base}...{head}", "compare_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/compare/{base}...{head}",
"merges_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/merges", "merges_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/merges",
"archive_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/{archive_format}{/ref}", "archive_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/{archive_format}{/ref}",
"downloads_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/downloads", "downloads_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/downloads",
"issues_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/issues{/number}", "issues_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/issues{/number}",
"pulls_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/pulls{/number}", "pulls_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/pulls{/number}",
"milestones_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/milestones{/number}", "milestones_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/milestones{/number}",
"notifications_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/notifications{?since,all,participating}", "notifications_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/notifications{?since,all,participating}",
"labels_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/labels{/name}", "labels_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/labels{/name}",
"releases_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/releases{/id}", "releases_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/releases{/id}",
"deployments_url": "https://api.github.com/repos/cloudbees/managed-master-hibernation-plugin/deployments" "deployments_url": "https://api.github.com/repos/cloudbees/managed-main-hibernation-plugin/deployments"
}, },
"url": "https://api.github.com/notifications/threads/581645707", "url": "https://api.github.com/notifications/threads/581645707",
"subscription_url": "https://api.github.com/notifications/threads/581645707/subscription" "subscription_url": "https://api.github.com/notifications/threads/581645707/subscription"

View File

@@ -4024,7 +4024,7 @@
"updated_at": "2019-10-14T21:06:40Z", "updated_at": "2019-10-14T21:06:40Z",
"last_read_at": "2019-10-18T20:02:08Z", "last_read_at": "2019-10-18T20:02:08Z",
"subject": { "subject": {
"title": "CSDOCS-206 - Adjust Jenkinsfile to only deploy master commits", "title": "CSDOCS-206 - Adjust Jenkinsfile to only deploy main commits",
"url": "https://api.github.com/repos/cloudbees/docsite-engine/pulls/121", "url": "https://api.github.com/repos/cloudbees/docsite-engine/pulls/121",
"latest_comment_url": "https://api.github.com/repos/cloudbees/docsite-engine/issues/comments/541921810", "latest_comment_url": "https://api.github.com/repos/cloudbees/docsite-engine/issues/comments/541921810",
"type": "PullRequest" "type": "PullRequest"

View File

@@ -3,7 +3,6 @@
"name": "notifications_threads_523050578", "name": "notifications_threads_523050578",
"request": { "request": {
"url": "/notifications/threads/523050578", "url": "/notifications/threads/523050578",
"method": "PATCH",
"bodyPatterns": [ "bodyPatterns": [
{ {
"equalToJson": "{}", "equalToJson": "{}",
@@ -11,7 +10,11 @@
"ignoreExtraElements": true "ignoreExtraElements": true
} }
], ],
"method": "POST",
"headers": { "headers": {
"X-HTTP-Method-Override": {
"equalTo": "PATCH"
},
"Accept": { "Accept": {
"equalTo": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2" "equalTo": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"
} }

View File

@@ -96,7 +96,7 @@
"forks": 456, "forks": 456,
"open_issues": 57, "open_issues": 57,
"watchers": 613, "watchers": 613,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -96,7 +96,7 @@
"forks": 5807, "forks": 5807,
"open_issues": 74, "open_issues": 74,
"watchers": 14167, "watchers": 14167,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": false, "admin": false,
"push": false, "push": false,

View File

@@ -96,7 +96,7 @@
"forks": 5807, "forks": 5807,
"open_issues": 74, "open_issues": 74,
"watchers": 14167, "watchers": 14167,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": false, "admin": false,
"push": false, "push": false,

View File

@@ -779,7 +779,7 @@
"created_at": "2011-02-10T14:10:23Z", "created_at": "2011-02-10T14:10:23Z",
"updated_at": "2011-02-10T14:10:23Z", "updated_at": "2011-02-10T14:10:23Z",
"author_association": "MEMBER", "author_association": "MEMBER",
"body": "We are not forgetting to merge this, JENKINS-8592, branch into master?\n" "body": "We are not forgetting to merge this, JENKINS-8592, branch into main?\n"
}, },
{ {
"url": "https://api.github.com/repos/jenkinsci/jenkins/comments/267069", "url": "https://api.github.com/repos/jenkinsci/jenkins/comments/267069",

View File

@@ -96,7 +96,7 @@
"forks": 456, "forks": 456,
"open_issues": 58, "open_issues": 58,
"watchers": 613, "watchers": 613,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -96,7 +96,7 @@
"forks": 456, "forks": 456,
"open_issues": 58, "open_issues": 58,
"watchers": 613, "watchers": 613,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -96,7 +96,7 @@
"forks": 456, "forks": 456,
"open_issues": 58, "open_issues": 58,
"watchers": 613, "watchers": 613,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -96,7 +96,7 @@
"forks": 456, "forks": 456,
"open_issues": 58, "open_issues": 58,
"watchers": 613, "watchers": 613,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

View File

@@ -96,7 +96,7 @@
"forks": 456, "forks": 456,
"open_issues": 58, "open_issues": 58,
"watchers": 613, "watchers": 613,
"default_branch": "master", "default_branch": "main",
"permissions": { "permissions": {
"admin": true, "admin": true,
"push": true, "push": true,

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