下面列出了怎么用org.junit.jupiter.api.extension.ExtendWith的API类实例代码及写法,或者点击链接到github查看源代码。
@AllureFeatures.Links
@ExtendWith(SystemPropertyExtension.class)
@SystemProperty(name = "allure.link.issue.pattern", value = "https://example.org/issue/{}")
@SystemProperty(name = "allure.link.tms.pattern", value = "https://example.org/tms/{}")
@Test
void shouldAddLinks() {
final AllureResults results = runFeature("features/tags.feature");
final List<TestResult> testResults = results.getTestResults();
assertThat(testResults)
.flatExtracting(TestResult::getLinks)
.extracting(Link::getName, Link::getType, Link::getUrl)
.contains(
tuple("OAT-4444", "tms", "https://example.org/tms/OAT-4444"),
tuple("BUG-22400", "issue", "https://example.org/issue/BUG-22400")
);
}
@AllureFeatures.Links
@ExtendWith(SystemPropertyExtension.class)
@SystemProperty(name = "allure.link.issue.pattern", value = "https://example.org/issue/{}")
@SystemProperty(name = "allure.link.tms.pattern", value = "https://example.org/tms/{}")
@Test
void shouldAddLinks() {
final AllureResultsWriterStub writer = new AllureResultsWriterStub();
runFeature(writer, "features/tags.feature");
final List<TestResult> testResults = writer.getTestResults();
assertThat(testResults)
.flatExtracting(TestResult::getLinks)
.extracting(Link::getName, Link::getType, Link::getUrl)
.contains(
tuple("OAT-4444", "tms", "https://example.org/tms/OAT-4444"),
tuple("BUG-22400", "issue", "https://example.org/issue/BUG-22400")
);
}
@AllureFeatures.Links
@ExtendWith(SystemPropertyExtension.class)
@SystemProperty(name = "allure.link.issue.pattern", value = "https://example.org/issue/{}")
@SystemProperty(name = "allure.link.tms.pattern", value = "https://example.org/tms/{}")
@Test
void shouldAddLinks() {
final AllureResults results = runFeature("features/tags.feature");
final List<TestResult> testResults = results.getTestResults();
assertThat(testResults)
.flatExtracting(TestResult::getLinks)
.extracting(Link::getName, Link::getType, Link::getUrl)
.contains(
tuple("OAT-4444", "tms", "https://example.org/tms/OAT-4444"),
tuple("BUG-22400", "issue", "https://example.org/issue/BUG-22400")
);
}
@AllureFeatures.Links
@ExtendWith(SystemPropertyExtension.class)
@SystemProperty(name = "allure.link.issue.pattern", value = "https://example.org/issue/{}")
@SystemProperty(name = "allure.link.tms.pattern", value = "https://example.org/tms/{}")
@Test
void shouldAddLinks() {
final AllureResultsWriterStub writer = new AllureResultsWriterStub();
runFeature(writer, "features/tags.feature");
final List<TestResult> testResults = writer.getTestResults();
assertThat(testResults)
.flatExtracting(TestResult::getLinks)
.extracting(Link::getName, Link::getType, Link::getUrl)
.contains(
tuple("OAT-4444", "tms", "https://example.org/tms/OAT-4444"),
tuple("BUG-22400", "issue", "https://example.org/issue/BUG-22400")
);
}
@AllureFeatures.Links
@ExtendWith(SystemPropertyExtension.class)
@SystemProperty(name = "allure.link.issue.pattern", value = "https://example.org/issue/{}")
@SystemProperty(name = "allure.link.tms.pattern", value = "https://example.org/tms/{}")
@Test
void shouldAddLinks() {
final AllureResults results = runFeature("features/tags.feature");
assertThat(results.getTestResults())
.flatExtracting(TestResult::getLinks)
.extracting(Link::getName, Link::getType, Link::getUrl)
.contains(
tuple("OAT-4444", "tms", "https://example.org/tms/OAT-4444"),
tuple("BUG-22400", "issue", "https://example.org/issue/BUG-22400")
);
}
/**
* Validate that when offline and no corresponding P4 changelist, an IDE change list is not
* decorated.
*/
@ExtendWith(TemporaryFolderExtension.class)
@Test
void offlineNoP4ChangeDecorateChangeListWithDefault(TemporaryFolder tmp) {
// Setup offline mode
ClientConfigRoot root = vcs.addClientConfigRoot(tmp, "client");
assertNotNull(root.getClientRootDir());
vcs.goOffline(root);
assertFalse(vcs.registry.isOnline(root.getClientConfig().getClientServerRef()));
P4ChangelistId defaultP4Changelist = vcs.addDefaultChangelist(root);
MockLocalChangeList changeList =
vcs.addIdeChangelist("new change", "a test change", false);
P4ChangeListDecorator decorator = new P4ChangeListDecorator(vcs.getMockProject());
MockColoredTreeCellRenderer renderer = new MockColoredTreeCellRenderer();
decorator.decorateChangeList(changeList, renderer, false, false, false);
assertEmpty(renderer.appendedText);
}
@Test
@ExtendWith(UnleashExceptionExtension.class)
public void given_empty_body() throws URISyntaxException {
stubFor(get(urlEqualTo("/api/client/features"))
.withHeader("Accept", equalTo("application/json"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")));
URI uri = new URI("http://localhost:"+serverMock.port() + "/api/");
UnleashConfig config = UnleashConfig.builder().appName("test").unleashAPI(uri).build();
HttpToggleFetcher httpToggleFetcher = new HttpToggleFetcher(config);
httpToggleFetcher.fetchToggles();
verify(getRequestedFor(urlMatching("/api/client/features"))
.withHeader("Content-Type", matching("application/json")));
}
@Test
@ExtendWith(UnleashExceptionExtension.class)
public void given_json_without_feature_field() throws Exception {
stubFor(get(urlEqualTo("/api/client/features"))
.withHeader("Accept", equalTo("application/json"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{}")));
URI uri = new URI("http://localhost:"+serverMock.port() + "/api/");
UnleashConfig config = UnleashConfig.builder().appName("test").unleashAPI(uri).build();
HttpToggleFetcher httpToggleFetcher = new HttpToggleFetcher(config);
httpToggleFetcher.fetchToggles();
verify(getRequestedFor(urlMatching("/api/client/features"))
.withHeader("Content-Type", matching("application/json")));
}
@Test
@ExtendWith(TempDirectory.class)
public void testOfflineScanWithSnippetMatching(@TempDirectory.TempDir final Path tempOutputDirectory) throws Exception {
final String projectName = "synopsys-detect-junit";
final String projectVersionName = "offline-scan";
assertProjectVersionReady(projectName, projectVersionName);
final List<String> detectArgs = getInitialArgs(projectName, projectVersionName);
detectArgs.add("--detect.output.path=" + tempOutputDirectory.toString());
detectArgs.add("--detect.blackduck.signature.scanner.snippet.matching=SNIPPET_MATCHING");
detectArgs.add("--detect.blackduck.signature.scanner.dry.run=true");
Application.main(detectArgs.toArray(new String[0]));
assertDirectoryStructureForOfflineScan(tempOutputDirectory);
}
@Test
@ExtendWith(CustomExtension.class)
@ExplicitParamInjection
public void testParametersNeedExtraAnnotation(@Default Foo foo, Bar bar, @MyQualifier BeanWithQualifier bean) {
// Bar should be resolved by another extension
Assertions.assertNotNull(bar);
Assertions.assertEquals(CustomExtension.class.getSimpleName(), bar.ping());
// Foo should be resolved as usual
Assertions.assertNotNull(foo);
Assertions.assertEquals(Foo.class.getSimpleName(), foo.ping());
// BeanWithQualifier should be resolved
Assertions.assertNotNull(bean);
Assertions.assertEquals(BeanWithQualifier.class.getSimpleName(), bean.ping());
}
@Test
@ExtendWith(CustomExtension.class)
public void testParametersNeedExtraAnnotation(@Default Foo foo, Bar bar, @MyQualifier BeanWithQualifier bean) {
// Bar should be resolved by another extension
Assertions.assertNotNull(bar);
Assertions.assertEquals(CustomExtension.class.getSimpleName(), bar.ping());
// Foo should be resolved as usual
Assertions.assertNotNull(foo);
Assertions.assertEquals(Foo.class.getSimpleName(), foo.ping());
// BeanWithQualifier should be resolved
Assertions.assertNotNull(bean);
Assertions.assertEquals(BeanWithQualifier.class.getSimpleName(), bean.ping());
}
@Test
@ExtendWith(CustomExtension.class)
public void testParametersNeedExtraAnnotation(@Default Foo foo, Bar bar, @MyQualifier BeanWithQualifier bean) {
// Bar should be resolved by another extension
Assertions.assertNotNull(bar);
Assertions.assertEquals(CustomExtension.class.getSimpleName(), bar.ping());
// Foo should be resolved as usual
Assertions.assertNotNull(foo);
Assertions.assertEquals(Foo.class.getSimpleName(), foo.ping());
// BeanWithQualifier should be resolved
Assertions.assertNotNull(bean);
Assertions.assertEquals(BeanWithQualifier.class.getSimpleName(), bean.ping());
}
@Test
@ExtendWith(FooBarExtension.class)
void doesNotResolveEveryParameter(String string, String[] fooBar, Injector injector) {
assertThat(string).isEqualTo(TestModule.STRING);
assertThat(fooBar).asList().containsExactly("foo", "bar").inOrder();
assertNull(injector.getExistingBinding(Key.get(String[].class)));
}
@TestTemplate
@ExtendWith(UserIdGeneratorTestInvocationContextProvider.class)
public void whenUserIdRequested_thenUserIdIsReturnedInCorrectFormat(UserIdGeneratorTestCase testCase) {
UserIdGenerator userIdGenerator = new UserIdGeneratorImpl(testCase.isFeatureEnabled());
String actualUserId = userIdGenerator.generate(testCase.getFirstName(), testCase.getLastName());
assertThat(actualUserId).isEqualTo(testCase.getExpectedUserId());
}
@TestFactory
@ExtendWith(RandomIntegerResolver.class)
Stream<DynamicTest> dynamic(int randomized) {
return Stream.of(
dynamicTest("#1", () -> System.out.println("Random integer: " + randomized)),
dynamicTest("#2", () -> System.out.println("Random integer: " + randomized))
);
}
@ParameterizedTest
@MethodSource
@ExtendWith(RandomIntegerResolver.class)
void parameterized(String param, int randomized) {
System.out.println("Random integer: " + randomized);
assertTrue(true);
}
/**
* Verify that a newly created IDE changelist does not trigger the creation or association of a Perforce
* changelist.
*/
@ExtendWith({ TemporaryFolderExtension.class, ErrorCollectorExtension.class })
@Test
void offlineCreateNewIdeChangelist(TemporaryFolder tmp, Errors errors)
throws InterruptedException {
vcs.idea.useInlineThreading(errors.get());
// Setup offline mode
ClientConfigRoot root = vcs.addClientConfigRoot(tmp, "client");
assertNotNull(root.getClientRootDir());
vcs.goOffline(root);
assertFalse(vcs.registry.isOnline(root.getClientConfig().getClientServerRef()));
// Add the pending add action.
MockLocalChangeList changeList =
vcs.addIdeChangelist("Test change", "A test change", false);
// Run the test.
P4ChangelistListener listener = new P4ChangelistListener(vcs.idea.getMockProject());
listener.changeListAdded(changeList);
Pair<IdeChangelistMap, IdeFileMap>
cacheState = vcs.cacheComponent.getServerOpenedCache();
assertEmpty(cacheState.first.getP4ChangesFor(changeList));
// TODO any additional validations?
}
/**
* Validate that when offline and no corresponding P4 changelist, an IDE change list is not
* decorated.
*/
@ExtendWith(TemporaryFolderExtension.class)
@Test
void offlineNoP4ChangeDecorateChangeList(TemporaryFolder tmp) {
MockLocalChangeList changeList =
vcs.addIdeChangelist("new change", "a test change", false);
P4ChangeListDecorator decorator = new P4ChangeListDecorator(vcs.getMockProject());
MockColoredTreeCellRenderer renderer = new MockColoredTreeCellRenderer();
decorator.decorateChangeList(changeList, renderer, false, false, false);
assertEmpty(renderer.appendedText);
}
@ExtendWith(TemporaryFolderExtension.class)
@Test
void testSplitFilePath_simple(TemporaryFolder tmpDir) {
FilePath src = VcsUtil.getFilePath(tmpDir.newFile("a/test.txt"));
FilePath dest = VcsUtil.getFilePath(tmpDir.newFile("b/test.txt"));
P4RemoteFileImpl local = new P4RemoteFileImpl("//depot/x/y/a/test.txt", "//depot/x/y/a/test.txt", null);
P4RemoteFileImpl remote = new P4RemoteFileImpl("//depot/x/y/b/test.txt", "//depot/x/y/b/test.txt", null);
assertEquals(
dest,
RemoteFileUtil.createRelativePath(src, local, remote)
);
}
@ExtendWith(TemporaryFolderExtension.class)
@Test
void forPort_rsh(TemporaryFolder tmpDir) {
// This is what the TestServer uses as the protocol.
String port = "p4jrsh://"
+ tmpDir.newFile("p4d").getAbsolutePath()
+ " -r "
+ tmpDir.newFile("root").getAbsolutePath()
+ ' '
+ " -L log -i --java";
P4ServerName name = P4ServerName.forPort(port);
assertNotNull(name);
assertThat(name.getServerProtocol(), is(IServerAddress.Protocol.P4JRSHNTS));
}
@ExtendWith(TemporaryFolderExtension.class)
@Test
void createJob_error(TemporaryFolder tmpDir)
throws IOException {
idea.useInlineThreading(null);
final ServerConfig config = ServerConfig.createFrom(
new MockConfigPart()
// By using the RSH port, it means that the connection will be kept open
// (NTS connection). By keeping the connection open until explicitly
// disconnected, this will indirectly be testing that the
// SimpleConnectionManager closes the connection.
.withServerName(server.getRshUrl())
.withUsername(server.getUser())
.withNoPassword()
);
final MockP4RequestErrorHandler errorHandler = new MockP4RequestErrorHandler();
SimpleConnectionManager mgr = new SimpleConnectionManager(
tmpDir.newFile("out"), 1000, "v1",
errorHandler);
ConnectCommandRunner runner = new ConnectCommandRunner(idea.getMockProject(), mgr);
// Should run without needing a blockingGet, because of the inline thread handler.
runner.getJobSpec(new OptionalClientServerConfig(config, null))
.mapActionAsync((jobSpec) ->
// Do not set any expected details.
runner.perform(new OptionalClientServerConfig(config, null),
new CreateJobAction(new P4JobImpl("j", "x", null)))
)
.whenCompleted((x) -> fail("Did not throw an error"))
.whenServerError((ex) -> {
assertNotNull(ex);
assertThat(ex.getCause(), instanceOf(RequestException.class));
// FIXME add better assertions
});
assertSize(1, errorHandler.getExceptions());
assertThat(errorHandler.getExceptions().get(0), instanceOf(RequestException.class));
}
@ExtendWith(TemporaryFolderExtension.class)
@Test
void createChangelist(TemporaryFolder tmpDir) throws IOException {
idea.useInlineThreading(null);
MockConfigPart part = new MockConfigPart()
// By using the RSH port, it means that the connection will be kept open
// (NTS connection). By keeping the connection open until explicitly
// disconnected, this will indirectly be testing that the
// SimpleConnectionManager closes the connection.
.withServerName(server.getRshUrl())
.withUsername(server.getUser())
.withNoPassword()
.withClientname("client1");
final ServerConfig serverConfig = ServerConfig.createFrom(part);
final ClientConfig clientConfig = ClientConfig.createFrom(serverConfig, part);
final File clientRoot = tmpDir.newFile("clientRoot");
touchFile(clientRoot, "[email protected]");
final TestableP4RequestErrorHandler errorHandler = new TestableP4RequestErrorHandler(idea.getMockProject());
setupClient(clientConfig, tmpDir, clientRoot, errorHandler)
.map((cm) -> new ConnectCommandRunner(idea.getMockProject(), cm))
.futureMap((runner, sink) ->
runner.perform(clientConfig,
new CreateChangelistAction(clientConfig.getClientServerRef(), "simple",
"local-id"))
.whenCompleted(sink::resolve)
.whenServerError(sink::reject)
)
.whenCompleted((r) -> {
assertThat(r, instanceOf(CreateChangelistResult.class));
CreateChangelistResult res = (CreateChangelistResult) r;
assertSame(clientConfig, res.getClientConfig());
assertEquals(1, res.getChangelistId());
})
.whenFailed(Assertions::fail);
}
@ExtendWith(TemporaryFolderExtension.class)
@Test
void fetchFiles_noFiles(TemporaryFolder tmpDir) throws IOException {
idea.useInlineThreading(null);
MockConfigPart part = new MockConfigPart()
// By using the RSH port, it means that the connection will be kept open
// (NTS connection). By keeping the connection open until explicitly
// disconnected, this will indirectly be testing that the
// SimpleConnectionManager closes the connection.
.withServerName(server.getRshUrl())
.withUsername(server.getUser())
.withNoPassword()
.withClientname("client1");
final ServerConfig serverConfig = ServerConfig.createFrom(part);
final ClientConfig clientConfig = ClientConfig.createFrom(serverConfig, part);
final File clientRoot = tmpDir.newFile("clientRoot");
touchFile(clientRoot, "[email protected]");
final TestableP4RequestErrorHandler errorHandler = new TestableP4RequestErrorHandler(idea.getMockProject());
setupClient(clientConfig, tmpDir, clientRoot, errorHandler)
.map((cm) -> new ConnectCommandRunner(idea.getMockProject(), cm))
.futureMap((runner, sink) ->
runner.perform(clientConfig,
new FetchFilesAction(Collections.singletonList(VcsUtil.getFilePath(clientRoot)),
null, false))
.whenCompleted(sink::resolve)
.whenServerError(sink::reject)
)
.whenCompleted((r) -> {
// Special code is present to handle an empty sync.
FetchFilesResult res = (FetchFilesResult) r;
assertEquals("", res.getMessage());
assertEmpty(res.getFiles());
})
.whenFailed(Assertions::fail);
}
@ExtendWith(TemporaryFolderExtension.class)
@Test
void getClientsForUser_nonExistent(TemporaryFolder tmpDir) throws IOException {
idea.useInlineThreading(null);
MockConfigPart part = new MockConfigPart()
// By using the RSH port, it means that the connection will be kept open
// (NTS connection). By keeping the connection open until explicitly
// disconnected, this will indirectly be testing that the
// SimpleConnectionManager closes the connection.
.withServerName(server.getRshUrl())
.withUsername(server.getUser())
.withNoPassword()
.withClientname("client1");
final ServerConfig serverConfig = ServerConfig.createFrom(part);
final ClientConfig clientConfig = ClientConfig.createFrom(serverConfig, part);
final File clientRoot = tmpDir.newFile("clientRoot");
final TestableP4RequestErrorHandler errorHandler = new TestableP4RequestErrorHandler(idea.getMockProject());
setupClient(clientConfig, tmpDir, clientRoot, errorHandler)
.map((cm) -> new ConnectCommandRunner(idea.getMockProject(), cm))
.futureMap((runner, sink) ->
runner.getClientsForUser(new OptionalClientServerConfig(clientConfig),
new ListClientsForUserQuery("not-a-user", 50))
.whenCompleted(sink::resolve)
.whenServerError(sink::reject)
)
.whenCompleted((r) -> {
assertThat(r, instanceOf(ListClientsForUserResult.class));
ListClientsForUserResult res = (ListClientsForUserResult) r;
assertSame(serverConfig, res.getServerConfig());
assertEquals("not-a-user", res.getRequestedUser());
assertEmpty(res.getClients());
})
.whenFailed(Assertions::fail);
}
@ExtendWith(TemporaryFolderExtension.class)
@Test
void getSetState(TemporaryFolder tmpDir)
throws PrimitiveMap.UnmarshalException {
ProjectCacheStore.State state = new ProjectCacheStore.State();
ClientServerRef ref = new ClientServerRef(
P4ServerName.forPortNotNull("test:1234"),
"client1"
);
state.clientState = Collections.singletonList(new ClientQueryCacheStore(ref).getState());
state.serverState = Collections.singletonList(new ServerQueryCacheStore(ref.getServerName()).getState());
MockFilePath fp = new MockFilePath(tmpDir.newFile("test-file.txt"));
ActionStore.State actionState = ActionStore.getState(
ActionStore.getSourceId(ref),
new MoveFilesToChangelistAction(new P4ChangelistIdImpl(1, ref),
Collections.singletonList(fp)));
state.pendingActions = Collections.singletonList(actionState);
Element serialized = XmlSerializer.serialize(state);
ProjectCacheStore.State unmarshalled = XmlSerializer.deserialize(serialized, ProjectCacheStore.State.class);
assertNotNull(unmarshalled);
assertSize(1, unmarshalled.clientState);
assertSize(1, unmarshalled.serverState);
assertSize(1, unmarshalled.pendingActions);
assertNotNull(unmarshalled.pendingActions.get(0));
ActionStore.PendingAction moveAction = ActionStore.read(unmarshalled.pendingActions.get(0));
assertThat(moveAction.clientAction, instanceOf(MoveFilesToChangelistAction.class));
}
@TestTemplate
@ExtendWith(SuccessInvocationContextProvider.class)
void success(Class clazz, URL expectedResourceUrl, String generatedClassName, String[] options)
throws Exception {
addOption(options);
addProcessor(new EntityProcessor());
addCompilationUnit(clazz);
compile();
assertEqualsGeneratedSourceWithResource(expectedResourceUrl, generatedClassName);
assertTrue(getCompiledResult());
}
@TestTemplate
@ExtendWith(ErrorInvocationContextProvider.class)
void error(Class clazz, Message message, String... options) throws Exception {
addOption(options);
addProcessor(new EntityProcessor());
addCompilationUnit(clazz);
compile();
assertFalse(getCompiledResult());
assertMessage(message);
}
@TestTemplate
@ExtendWith(SuccessInvocationContextProvider.class)
void success(Class<?> clazz, URL expectedResourceUrl, String generatedClassName, String[] options)
throws Exception {
addOption(options);
addProcessor(new EntityProcessor());
addCompilationUnit(clazz);
compile();
assertEqualsGeneratedSourceWithResource(expectedResourceUrl, generatedClassName);
assertTrue(getCompiledResult());
}
@TestTemplate
@ExtendWith(SuccessPrefixInvocationContextProvider.class)
void success_prefix(
Class<?> clazz, URL expectedResourceUrl, String generatedClassName, String[] options)
throws Exception {
addOption(options);
addProcessor(new EntityProcessor());
addCompilationUnit(clazz);
compile();
assertEqualsGeneratedSourceWithResource(expectedResourceUrl, generatedClassName);
assertTrue(getCompiledResult());
}
@TestTemplate
@ExtendWith(ErrorInvocationContextProvider.class)
void error(Class<?> clazz, Message message, String... options) throws Exception {
addOption(options);
addProcessor(new EntityProcessor());
addCompilationUnit(clazz);
compile();
assertFalse(getCompiledResult());
assertMessage(message);
}