Class JenkinsRule
- java.lang.Object
-
- org.jvnet.hudson.test.JenkinsRule
-
- All Implemented Interfaces:
hudson.ExtensionPoint,hudson.model.Action,hudson.model.ModelObject,hudson.model.RootAction,org.junit.rules.MethodRule,org.junit.rules.TestRule
- Direct Known Subclasses:
GroovyJenkinsRule,NodeProvisionerRule,RealJenkinsRule.CustomJenkinsRule
public class JenkinsRule extends Object implements org.junit.rules.TestRule, org.junit.rules.MethodRule, hudson.model.RootAction
JUnit rule to allow test cases to fire up a Jenkins instance.- Since:
- 1.436
- Author:
- Stephen Connolly
- See Also:
- Wiki article about unit testing in Jenkins,
RestartableJenkinsRule
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classJenkinsRule.BreakExceptionstatic classJenkinsRule.DummySecurityRealmstatic classJenkinsRule.JSONWebResponseConvenience wrapper for JSON responses.static classJenkinsRule.TestBuildWrapperclassJenkinsRule.WebClientExtendsWebClientand provide convenience methods for accessing Hudson.
-
Field Summary
Fields Modifier and Type Field Description JenkinsComputerConnectorTestercomputerConnectorTesterStringcontextPathWhere in theServeris Jenkins deployed?protected TestEnvironmentenvprotected HudsonHomeLoaderhomeLoaderhudson.model.HudsonhudsonDeprecated.jenkins.model.Jenkinsjenkinsprotected JavaScriptDebuggerjsDebuggerJavaScript "debugger" that provides you information about the JavaScript call stack and the current values of the local variables in those stack frame.protected intlocalPortTCP/IP port that the server is listening on.static org.eclipse.jetty.http.MimeTypesMIME_TYPESstatic List<hudson.tools.ToolProperty<?>>NO_PROPERTIESprotected List<JenkinsRecipe.Runner>recipesprotected org.eclipse.jetty.server.Serverserverstatic intSLAVE_DEBUG_PORTSpecify this to a TCP/IP port number to have slaves started with the debugger.protected List<LenientRunnable>tearDownsprotected org.junit.runner.DescriptiontestDescriptioninttimeoutNumber of seconds until the test times out.booleanuseLocalPluginManagerDeprecated.UsepluginManager
-
Constructor Summary
Constructors Constructor Description JenkinsRule()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static void_configureJenkinsForTest(jenkins.model.Jenkins jenkins)Configures a Jenkins instance for test.static void_configureUpdateCenter(jenkins.model.Jenkins jenkins)Internal method used to configure update center to avoid network traffic.static org.eclipse.jetty.security.LoginService_configureUserRealm()Creates aHashLoginServicewith three users: alice, bob and charlie The password is same as the usernamestatic org.eclipse.jetty.server.Server_createWebServer(String contextPath, Consumer<Integer> portSetter, ClassLoader classLoader, int localPort, Supplier<org.eclipse.jetty.security.LoginService> loginServiceSupplier)Creates a web server on which Jenkins can runstatic org.eclipse.jetty.server.Server_createWebServer(String contextPath, Consumer<Integer> portSetter, ClassLoader classLoader, int localPort, Supplier<org.eclipse.jetty.security.LoginService> loginServiceSupplier, BiConsumer<org.eclipse.jetty.webapp.WebAppContext,org.eclipse.jetty.server.Server> contextAndServerConsumer)Creates a web server on which Jenkins can runstatic void_stopJenkins(org.eclipse.jetty.server.Server server, List<LenientRunnable> tearDowns, jenkins.model.Jenkins jenkins)Internal method to stop Jenkins instance.voidafter()Override to tear down your specific external resource.org.junit.runners.model.Statementapply(org.junit.runners.model.Statement base, org.junit.runner.Description description)org.junit.runners.model.Statementapply(org.junit.runners.model.Statement base, org.junit.runners.model.FrameworkMethod method, Object target)Backward compatibility with JUnit 4.8.voidassertAllImageLoadSuccessfully(org.htmlunit.html.HtmlPage p)Makes sure that all the images in the page loads successfully.<R extends hudson.model.Run>
RassertBuildStatus(hudson.model.Result status, Future<? extends R> r)<R extends hudson.model.Run>
RassertBuildStatus(hudson.model.Result status, R r)Asserts that the outcome of the build is a specific outcome.<R extends hudson.model.Run>
RassertBuildStatusSuccess(Future<? extends R> r)<R extends hudson.model.Run>
RassertBuildStatusSuccess(R r)voidassertEqualBeans(Object lhs, Object rhs, String properties)Asserts that two JavaBeans are equal as far as the given list of properties are concerned.voidassertEqualDataBoundBeans(Object lhs, Object rhs)Works likeassertEqualBeans(Object, Object, String)but figure out the properties viaDataBoundConstructorandDataBoundSettervoidassertEqualDataBoundBeans(List<?> lhs, List<?> rhs)Makes sure that two collections are identical viaassertEqualDataBoundBeans(Object, Object)voidassertGoodStatus(org.htmlunit.Page page)Assert that the specified page can be served with a "good" HTTP status, eg, the page is not missing and can be served without a server errorvoidassertHelpExists(Class<? extends hudson.model.Describable> type, String properties)Asserts that help files exist for the specified properties of the given instance.voidassertLogContains(String substring, hudson.model.Run run)Asserts that the console output of the build contains the given substring.voidassertLogNotContains(String substring, hudson.model.Run run)Asserts that the console output of the build does not contain the given substring.voidassertStringContains(String haystack, String needle)voidassertStringContains(String message, String haystack, String needle)voidassertXPath(org.htmlunit.html.DomNode page, String xpath)Asserts that the XPath matches the contents of a DomNode page.voidassertXPath(org.htmlunit.html.HtmlPage page, String xpath)Asserts that the XPath matches.voidassertXPathResultsContainText(org.htmlunit.html.DomNode page, String xpath, String needle)voidassertXPathValue(org.htmlunit.html.DomNode page, String xpath, String expectedValue)voidassertXPathValueContains(org.htmlunit.html.DomNode page, String xpath, String needle)voidbefore()Override to set up your specific external resource.<J extends hudson.model.Job<J,R> & jenkins.model.ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends hudson.model.Run<J,R> & hudson.model.Queue.Executable>
RbuildAndAssertStatus(hudson.model.Result status, J job)Runs specified job and asserts that in finished with given build result.hudson.model.FreeStyleBuildbuildAndAssertSuccess(hudson.model.FreeStyleProject job)Avoids need for cumbersomethis.<J,R>buildAndAssertSuccess(...)type hints under JDK 7 javac (and supposedly also IntelliJ).<J extends hudson.model.Job<J,R> & jenkins.model.ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends hudson.model.Run<J,R> & hudson.model.Queue.Executable>
RbuildAndAssertSuccess(J job)voidconfigRoundtrip()Hits the Hudson system configuration and submits without any modification.<B extends hudson.tasks.Builder>
BconfigRoundtrip(B before)Performs a configuration round-trip testing for a builder.<C extends hudson.slaves.ComputerConnector>
CconfigRoundtrip(C before)hudson.model.UserconfigRoundtrip(hudson.model.User u)<N extends hudson.model.Node>
NconfigRoundtrip(N node)<P extends hudson.model.Item>
PconfigRoundtrip(P job)Loads a configuration page and submits it without any modifications, to perform a round-trip configuration test.<V extends hudson.model.View>
VconfigRoundtrip(V view)protected voidconfigureUpdateCenter()Configures the update center setting for the test.protected org.eclipse.jetty.security.LoginServiceconfigureUserRealm()Configures a security realm for a test.StringcreateApiToken(hudson.model.User user)Use the new API token system introduced in 2.129 to generate a token for the given user.hudson.slaves.ComputerLaunchercreateComputerLauncher(hudson.EnvVars env)Creates a launcher for starting a local agent.JenkinsRule.DummySecurityRealmcreateDummySecurityRealm()Creates a testSecurityRealmthat recognizes username==password as valid.MockFoldercreateFolder(String name)Creates a simple folder that other jobs can be placed in.hudson.model.FreeStyleProjectcreateFreeStyleProject()hudson.model.FreeStyleProjectcreateFreeStyleProject(String name)hudson.Launcher.LocalLaunchercreateLocalLauncher()CreatesLauncher.LocalLauncher.hudson.slaves.DumbSlavecreateOnlineSlave()Create a new slave on the local host and wait for it to come online before returning.hudson.slaves.DumbSlavecreateOnlineSlave(hudson.model.Label l)Create a new slave on the local host and wait for it to come online before returning.hudson.slaves.DumbSlavecreateOnlineSlave(hudson.model.Label l, hudson.EnvVars env)Create a new slave on the local host and wait for it to come online before returningPretendSlavecreatePretendSlave(FakeLauncher faker)<T extends hudson.model.TopLevelItem>
TcreateProject(Class<T> type)Creates a new job with an unique name.<T extends hudson.model.TopLevelItem>
TcreateProject(Class<T> type, String name)Creates a new job.hudson.slaves.DumbSlavecreateSlave()Creates and attaches a new outbound agent.hudson.slaves.DumbSlavecreateSlave(boolean waitForChannelConnect)hudson.slaves.DumbSlavecreateSlave(hudson.EnvVars env)hudson.slaves.DumbSlavecreateSlave(hudson.model.Label l)Creates and launches a new slave on the local host.hudson.slaves.DumbSlavecreateSlave(hudson.model.Label l, hudson.EnvVars env)hudson.slaves.DumbSlavecreateSlave(String labels, hudson.EnvVars env)Creates a slave with certain additional environment variableshudson.slaves.DumbSlavecreateSlave(String nodeName, String labels, hudson.EnvVars env)hudson.model.TaskListenercreateTaskListener()Creates aTaskListenerconnected to stdout.FilecreateTmpDir()Deprecated.UseTemporaryFolderinstead.protected StringcreateUniqueProjectName()JenkinsRule.WebClientcreateWebClient()Create a web client instance using the browser version returned byBrowserVersion.getDefault()with support for the Fetch API.protected javax.servlet.ServletContextcreateWebServer()Prepares a webapp hosting environment to getServletContextimplementation that we need for testing.protected javax.servlet.ServletContextcreateWebServer(BiConsumer<org.eclipse.jetty.webapp.WebAppContext,org.eclipse.jetty.server.Server> contextAndServerConsumer)Prepares a webapp hosting environment to getServletContextimplementation that we need for testing.voiddisconnectSlave(hudson.slaves.DumbSlave slave)<V> VexecuteOnServer(Callable<V> c)Executes the given closure on the server, by the servlet request handling thread, in the context of an HTTP request.Constructor<?>findDataBoundConstructor(Class<?> c)org.htmlunit.html.HtmlInputfindPreviousInputElement(org.htmlunit.html.HtmlElement current, String name)<T extends hudson.model.Descriptor<?>>
Tget(Class<T> d)Gets the descriptor instance of the current Hudson by its type.org.htmlunit.html.HtmlButtongetButtonByCaption(org.htmlunit.html.HtmlForm f, String s)StringgetDisplayName()StringgetIconFileName()jenkins.model.JenkinsgetInstance()JenkinsRule.JSONWebResponsegetJSON(String path)Get JSON from a Jenkins relative endpoint.static StringgetLog(hudson.model.Run run)Get entire log file as plain text.hudson.PluginManagergetPluginManager()org.junit.runner.DescriptiongetTestDescription()URLgetURL()Returns the URL of the webapp top page.StringgetUrlName()FilegetWebAppRoot()voidinteractiveBreak()Blocks until the ENTER key is hit.booleanisGoodHttpStatus(int status)Determines whether the specified HTTP status code is generally "good"booleanisSomethingHappening()Returns true if Hudson is building something or going to build something.<T> Tlast(List<T> items)Returns the last item in the list.protected hudson.model.HudsonnewHudson()Creates a new instance ofJenkins.voidpause()Pauses the execution until ENTER is hit in the console.JenkinsRule.JSONWebResponsepostJSON(String path, Object json)POST a JSON payload to a URL on the underlying Jenkins instance using the crumb.voidrecipe()Called during thebefore()to give a test case an opportunity to control the test environment in which Hudson is run.voidrecipeLoadCurrentPlugin()If this test harness is launched for a Jenkins plugin, locate thetarget/test-classes/the.jpland add a recipe to install that to the new Jenkins.org.htmlunit.Pagesearch(String q)Performs a search from the search box.voidsetPluginManager(hudson.PluginManager pluginManager)Sets thePluginManagerto be used when creating a newJenkinsinstance.voidsetQuietPeriod(int qp)voidshowAgentLogs(hudson.model.Slave s, Map<String,Level> loggers)Forward agent logs to standard error of the test process.voidshowAgentLogs(hudson.model.Slave s, LoggerRule loggerRule)Same asshowAgentLogs(Slave, Map)but taking a preconfigured list of loggers as a convenience.org.htmlunit.html.HtmlPagesubmit(org.htmlunit.html.HtmlForm form)Submits the form.org.htmlunit.html.HtmlPagesubmit(org.htmlunit.html.HtmlForm form, String name)Submits the form by clicking the submit button of the given name.<R extends hudson.model.Run<?,?>>
RwaitForCompletion(R r)Waits for a build to complete.<R extends hudson.model.Run<?,?>>
RwaitForMessage(String message, R r)Waits for a build log to contain a specified string.voidwaitOnline(hudson.model.Slave s)Waits for a newly created slave to come online.voidwaitUntilNoActivity()Waits until Hudson finishes building everything, including those in the queue.voidwaitUntilNoActivityUpTo(int timeout)Waits until Hudson finishes building everything, including those in the queue, or fail the test if the specified timeout milliseconds isJenkinsRulewith(hudson.PluginManager pluginManager)JenkinsRulewith(HudsonHomeLoader homeLoader)JenkinsRulewithExistingHome(File source)JenkinsRulewithNewHome()JenkinsRulewithPresetData(String name)Declares that this test case expects to start with one of the preset data sets.protected ObjectwriteReplace()Sometimes a part of a test case may ends up creeping into the serialization tree ofSaveable.save(), so detect that and flag that as an error.
-
-
-
Field Detail
-
env
protected TestEnvironment env
-
testDescription
protected org.junit.runner.Description testDescription
-
hudson
@Deprecated public hudson.model.Hudson hudson
Deprecated.Points to the same object asjenkinsdoes.
-
jenkins
public jenkins.model.Jenkins jenkins
-
homeLoader
protected HudsonHomeLoader homeLoader
-
localPort
protected int localPort
TCP/IP port that the server is listening on.
-
server
protected org.eclipse.jetty.server.Server server
-
contextPath
public String contextPath
Where in theServeris Jenkins deployed?Just like
ServletContext.getContextPath(), starts with '/' but doesn't end with '/'. UnlikeJenkinsRule.WebClient.getContextPath()this is not a complete URL.
-
tearDowns
protected List<LenientRunnable> tearDowns
-
recipes
protected List<JenkinsRecipe.Runner> recipes
-
jsDebugger
protected JavaScriptDebugger jsDebugger
JavaScript "debugger" that provides you information about the JavaScript call stack and the current values of the local variables in those stack frame.Unlike Java debugger, which you as a human interfaces directly and interactively, this JavaScript debugger is to be interfaced by your program (or through the expression evaluation capability of your Java debugger.)
-
useLocalPluginManager
@Deprecated public boolean useLocalPluginManager
Deprecated.UsepluginManagerIf this test case has additionalWithPluginannotations, set to true. This will cause a freshPluginManagerto be created for this test. Leaving this to false enables the test harness to use a pre-loaded plugin manager, which runs faster.
-
timeout
public int timeout
Number of seconds until the test times out. TheWithTimeoutrule can be used to specify this value per test. In case of debugging session, the default timeout behavior is removed. Otherwise it's set to 3 minutes.
-
computerConnectorTester
public JenkinsComputerConnectorTester computerConnectorTester
-
NO_PROPERTIES
public static final List<hudson.tools.ToolProperty<?>> NO_PROPERTIES
-
SLAVE_DEBUG_PORT
public static final int SLAVE_DEBUG_PORT
Specify this to a TCP/IP port number to have slaves started with the debugger.
-
MIME_TYPES
public static final org.eclipse.jetty.http.MimeTypes MIME_TYPES
-
-
Method Detail
-
getInstance
public jenkins.model.Jenkins getInstance()
-
before
public void before() throws ThrowableOverride to set up your specific external resource.- Throws:
Throwable- if setup fails (which will disableafter
-
_configureJenkinsForTest
public static void _configureJenkinsForTest(jenkins.model.Jenkins jenkins) throws ExceptionConfigures a Jenkins instance for test.- Parameters:
jenkins- jenkins instance which has to be configured- Throws:
Exception- if unable to configure- Since:
- 2.50
-
configureUpdateCenter
protected void configureUpdateCenter() throws ExceptionConfigures the update center setting for the test. By default, we load updates from local proxy to avoid network traffic as much as possible.- Throws:
Exception
-
_configureUpdateCenter
public static void _configureUpdateCenter(jenkins.model.Jenkins jenkins) throws ExceptionInternal method used to configure update center to avoid network traffic.- Parameters:
jenkins- the Jenkins to configure- Throws:
Exception- Since:
- 2.50
-
after
public void after() throws ExceptionOverride to tear down your specific external resource.- Throws:
Exception
-
_stopJenkins
public static void _stopJenkins(org.eclipse.jetty.server.Server server, List<LenientRunnable> tearDowns, jenkins.model.Jenkins jenkins)Internal method to stop Jenkins instance.- Parameters:
server- server on which Jenkins is running.tearDowns- tear down methods for testsjenkins- the jenkins instance- Since:
- 2.50
-
apply
public org.junit.runners.model.Statement apply(org.junit.runners.model.Statement base, org.junit.runners.model.FrameworkMethod method, Object target)Backward compatibility with JUnit 4.8.- Specified by:
applyin interfaceorg.junit.rules.MethodRule
-
apply
public org.junit.runners.model.Statement apply(org.junit.runners.model.Statement base, org.junit.runner.Description description)- Specified by:
applyin interfaceorg.junit.rules.TestRule
-
getIconFileName
public String getIconFileName()
- Specified by:
getIconFileNamein interfacehudson.model.Action
-
getDisplayName
public String getDisplayName()
- Specified by:
getDisplayNamein interfacehudson.model.Action- Specified by:
getDisplayNamein interfacehudson.model.ModelObject
-
getUrlName
public String getUrlName()
- Specified by:
getUrlNamein interfacehudson.model.Action
-
newHudson
protected hudson.model.Hudson newHudson() throws ExceptionCreates a new instance ofJenkins. If the derived class wants to create it in a different way, you can override it.- Throws:
Exception
-
getPluginManager
public hudson.PluginManager getPluginManager()
-
setPluginManager
public void setPluginManager(hudson.PluginManager pluginManager)
Sets thePluginManagerto be used when creating a newJenkinsinstance.- Parameters:
pluginManager- null to let Jenkins create a new instance of default plugin manager, like it normally does when running as a webapp outside the test.
-
with
public JenkinsRule with(hudson.PluginManager pluginManager)
-
createWebServer
protected javax.servlet.ServletContext createWebServer() throws ExceptionPrepares a webapp hosting environment to getServletContextimplementation that we need for testing.- Throws:
Exception
-
createWebServer
protected javax.servlet.ServletContext createWebServer(@CheckForNull BiConsumer<org.eclipse.jetty.webapp.WebAppContext,org.eclipse.jetty.server.Server> contextAndServerConsumer) throws ExceptionPrepares a webapp hosting environment to getServletContextimplementation that we need for testing.- Parameters:
contextAndServerConsumer- configures theWebAppContextand theServerfor the instance, before they are started- Throws:
Exception- Since:
- 2.63
-
_createWebServer
public static org.eclipse.jetty.server.Server _createWebServer(String contextPath, Consumer<Integer> portSetter, ClassLoader classLoader, int localPort, Supplier<org.eclipse.jetty.security.LoginService> loginServiceSupplier) throws Exception
Creates a web server on which Jenkins can run- Parameters:
contextPath- the context path at which to put JenkinsportSetter- the port on which the server runs will be set using this functionclassLoader- the class loader for theWebAppContextlocalPort- port on which the server runsloginServiceSupplier- configures theLoginServicefor the instance- Returns:
- the
Server - Throws:
Exception- Since:
- 2.50
-
_createWebServer
public static org.eclipse.jetty.server.Server _createWebServer(String contextPath, Consumer<Integer> portSetter, ClassLoader classLoader, int localPort, Supplier<org.eclipse.jetty.security.LoginService> loginServiceSupplier, @CheckForNull BiConsumer<org.eclipse.jetty.webapp.WebAppContext,org.eclipse.jetty.server.Server> contextAndServerConsumer) throws Exception
Creates a web server on which Jenkins can run- Parameters:
contextPath- the context path at which to put JenkinsportSetter- the port on which the server runs will be set using this functionclassLoader- the class loader for theWebAppContextlocalPort- port on which the server runsloginServiceSupplier- configures theLoginServicefor the instancecontextAndServerConsumer- configures theWebAppContextand theServerfor the instance, before they are started- Returns:
- the
Server - Throws:
Exception- Since:
- 2.50
-
configureUserRealm
protected org.eclipse.jetty.security.LoginService configureUserRealm()
Configures a security realm for a test.
-
_configureUserRealm
public static org.eclipse.jetty.security.LoginService _configureUserRealm()
Creates aHashLoginServicewith three users: alice, bob and charlie The password is same as the username- Returns:
- a new login service
- Since:
- 2.50
-
createProject
public <T extends hudson.model.TopLevelItem> T createProject(Class<T> type, String name) throws IOException
Creates a new job.- Parameters:
type- Top level item type.name- Item name.- Throws:
IllegalArgumentException- if the project of the given name already exists.IOException
-
createProject
public <T extends hudson.model.TopLevelItem> T createProject(Class<T> type) throws IOException
Creates a new job with an unique name.- Parameters:
type- Top level item type.- Throws:
IOException
-
createFreeStyleProject
public hudson.model.FreeStyleProject createFreeStyleProject() throws IOException- Throws:
IOException
-
createFreeStyleProject
public hudson.model.FreeStyleProject createFreeStyleProject(String name) throws IOException
- Throws:
IOException
-
createFolder
public MockFolder createFolder(String name) throws IOException
Creates a simple folder that other jobs can be placed in.- Throws:
IOException- Since:
- 1.494
-
createUniqueProjectName
protected String createUniqueProjectName()
-
createLocalLauncher
public hudson.Launcher.LocalLauncher createLocalLauncher()
CreatesLauncher.LocalLauncher. Useful for launching processes.
-
createTmpDir
@Deprecated public File createTmpDir() throws IOException
Deprecated.UseTemporaryFolderinstead.Allocates a new temporary directory for the duration of this test.- Throws:
IOException
-
createSlave
@NonNull public hudson.slaves.DumbSlave createSlave(boolean waitForChannelConnect) throws Exception- Throws:
Exception
-
disconnectSlave
public void disconnectSlave(hudson.slaves.DumbSlave slave) throws Exception- Throws:
Exception
-
createSlave
@NonNull public hudson.slaves.DumbSlave createSlave() throws ExceptionCreates and attaches a new outbound agent.- Throws:
Exception- See Also:
InboundAgentRule
-
createSlave
@NonNull public hudson.slaves.DumbSlave createSlave(@CheckForNull hudson.model.Label l) throws ExceptionCreates and launches a new slave on the local host.- Throws:
Exception
-
createDummySecurityRealm
public JenkinsRule.DummySecurityRealm createDummySecurityRealm()
Creates a testSecurityRealmthat recognizes username==password as valid.- See Also:
MockAuthorizationStrategy
-
getURL
public URL getURL() throws IOException
Returns the URL of the webapp top page. URL ends with '/'.- Throws:
IOException
-
createSlave
@NonNull public hudson.slaves.DumbSlave createSlave(@CheckForNull hudson.EnvVars env) throws Exception- Throws:
Exception
-
createSlave
@NonNull public hudson.slaves.DumbSlave createSlave(@CheckForNull hudson.model.Label l, @CheckForNull hudson.EnvVars env) throws Exception- Throws:
Exception
-
createSlave
@NonNull public hudson.slaves.DumbSlave createSlave(@CheckForNull String labels, @CheckForNull hudson.EnvVars env) throws ExceptionCreates a slave with certain additional environment variables- Throws:
Exception
-
createSlave
@NonNull public hudson.slaves.DumbSlave createSlave(@NonNull String nodeName, @CheckForNull String labels, @CheckForNull hudson.EnvVars env) throws Exception- Throws:
Exception
-
createPretendSlave
public PretendSlave createPretendSlave(FakeLauncher faker) throws Exception
- Throws:
Exception
-
createComputerLauncher
@NonNull public hudson.slaves.ComputerLauncher createComputerLauncher(@CheckForNull hudson.EnvVars env) throws URISyntaxException, IOExceptionCreates a launcher for starting a local agent. This is an outbound agent usingSimpleCommandLauncher.- Parameters:
env- Environment variables to add to the slave process. Can benull.- Throws:
URISyntaxExceptionIOException- See Also:
InboundAgentRule
-
createOnlineSlave
@NonNull public hudson.slaves.DumbSlave createOnlineSlave() throws ExceptionCreate a new slave on the local host and wait for it to come online before returning.- Throws:
Exception
-
createOnlineSlave
@NonNull public hudson.slaves.DumbSlave createOnlineSlave(@CheckForNull hudson.model.Label l) throws ExceptionCreate a new slave on the local host and wait for it to come online before returning.- Throws:
Exception
-
createOnlineSlave
@NonNull public hudson.slaves.DumbSlave createOnlineSlave(@CheckForNull hudson.model.Label l, @CheckForNull hudson.EnvVars env) throws ExceptionCreate a new slave on the local host and wait for it to come online before returning- Throws:
Exception- See Also:
waitOnline(hudson.model.Slave)
-
createApiToken
@NonNull public String createApiToken(@NonNull hudson.model.User user)
Use the new API token system introduced in 2.129 to generate a token for the given user.
-
waitOnline
public void waitOnline(hudson.model.Slave s) throws ExceptionWaits for a newly created slave to come online.- Throws:
Exception- See Also:
createSlave()
-
showAgentLogs
public void showAgentLogs(hudson.model.Slave s, LoggerRule loggerRule) throws ExceptionSame asshowAgentLogs(Slave, Map)but taking a preconfigured list of loggers as a convenience.- Throws:
Exception
-
showAgentLogs
public void showAgentLogs(hudson.model.Slave s, Map<String,Level> loggers) throws ExceptionForward agent logs to standard error of the test process. Otherwise log messages would be sent only toComputer.getLogText()etc., or discarded entirely (if belowLevel.INFO).- Parameters:
s- an online agentloggers-Logger.getName()tied to log level- Throws:
Exception
-
interactiveBreak
public void interactiveBreak() throws ExceptionBlocks until the ENTER key is hit. This is useful during debugging a test so that one can inspect the state of Hudson through the web browser.- Throws:
Exception
-
last
public <T> T last(List<T> items)
Returns the last item in the list.
-
pause
public void pause() throws IOExceptionPauses the execution until ENTER is hit in the console.This is often very useful so that you can interact with Hudson from an browser, while developing a test case.
- Throws:
IOException
-
search
public org.htmlunit.Page search(String q) throws Exception
Performs a search from the search box.- Throws:
Exception
-
getJSON
public JenkinsRule.JSONWebResponse getJSON(@NonNull String path) throws IOException
Get JSON from a Jenkins relative endpoint. Create a new default webclient. If you want to configure the webclient, for example to set a token for authentication, or accept other HTTP responses than 200, you can useJenkinsRule.WebClient.getJSON(String)directly.- Parameters:
path- relative path, should not start with '/'- Returns:
- The JSON response from server.
- Throws:
IOException
-
postJSON
public JenkinsRule.JSONWebResponse postJSON(@NonNull String path, @NonNull Object json) throws IOException, SAXException
POST a JSON payload to a URL on the underlying Jenkins instance using the crumb.- Parameters:
path- The url path on Jenkins.json- An object that produces a JSON string from it'stoStringmethod.- Returns:
- A JSON response.
- Throws:
IOExceptionSAXException
-
configRoundtrip
public void configRoundtrip() throws ExceptionHits the Hudson system configuration and submits without any modification.- Throws:
Exception
-
configRoundtrip
public <P extends hudson.model.Item> P configRoundtrip(P job) throws ExceptionLoads a configuration page and submits it without any modifications, to perform a round-trip configuration test.- Throws:
Exception
-
configRoundtrip
public <B extends hudson.tasks.Builder> B configRoundtrip(B before) throws ExceptionPerforms a configuration round-trip testing for a builder.- Throws:
Exception
-
configRoundtrip
public <P extends hudson.tasks.Publisher> P configRoundtrip(P before) throws ExceptionPerforms a configuration round-trip testing for a publisher.- Throws:
Exception
-
configRoundtrip
public <C extends hudson.slaves.ComputerConnector> C configRoundtrip(C before) throws Exception- Throws:
Exception
-
configRoundtrip
public hudson.model.User configRoundtrip(hudson.model.User u) throws Exception- Throws:
Exception
-
configRoundtrip
public <N extends hudson.model.Node> N configRoundtrip(N node) throws Exception- Throws:
Exception
-
configRoundtrip
public <V extends hudson.model.View> V configRoundtrip(V view) throws Exception- Throws:
Exception
-
configRoundtrip
public <C extends hudson.slaves.Cloud> C configRoundtrip(C cloud) throws ExceptionPerforms a configuration round-trip testing for a cloud. The given cloud is added to the cloud list of Jenkins.If a cloud with the same name already exists, then this old one will be replaced by the given one.
- Throws:
Exception
-
assertBuildStatus
public <R extends hudson.model.Run> R assertBuildStatus(hudson.model.Result status, R r) throws ExceptionAsserts that the outcome of the build is a specific outcome.- Throws:
Exception
-
assertBuildStatus
public <R extends hudson.model.Run> R assertBuildStatus(hudson.model.Result status, Future<? extends R> r) throws Exception- Throws:
Exception
-
isGoodHttpStatus
public boolean isGoodHttpStatus(int status)
Determines whether the specified HTTP status code is generally "good"
-
assertGoodStatus
public void assertGoodStatus(org.htmlunit.Page page)
Assert that the specified page can be served with a "good" HTTP status, eg, the page is not missing and can be served without a server error
-
assertBuildStatusSuccess
public <R extends hudson.model.Run> R assertBuildStatusSuccess(R r) throws Exception- Throws:
Exception
-
assertBuildStatusSuccess
public <R extends hudson.model.Run> R assertBuildStatusSuccess(Future<? extends R> r) throws Exception
- Throws:
Exception
-
buildAndAssertSuccess
@NonNull public <J extends hudson.model.Job<J,R> & jenkins.model.ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends hudson.model.Run<J,R> & hudson.model.Queue.Executable> R buildAndAssertSuccess(@NonNull J job) throws Exception- Throws:
Exception
-
buildAndAssertStatus
@NonNull public <J extends hudson.model.Job<J,R> & jenkins.model.ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends hudson.model.Run<J,R> & hudson.model.Queue.Executable> R buildAndAssertStatus(@NonNull hudson.model.Result status, @NonNull J job) throws ExceptionRuns specified job and asserts that in finished with given build result.- Throws:
Exception- Since:
- TODO
-
buildAndAssertSuccess
@NonNull public hudson.model.FreeStyleBuild buildAndAssertSuccess(@NonNull hudson.model.FreeStyleProject job) throws ExceptionAvoids need for cumbersomethis.<J,R>buildAndAssertSuccess(...)type hints under JDK 7 javac (and supposedly also IntelliJ).- Throws:
Exception
-
assertLogContains
public void assertLogContains(String substring, hudson.model.Run run) throws IOException
Asserts that the console output of the build contains the given substring.- Throws:
IOException
-
assertLogNotContains
public void assertLogNotContains(String substring, hudson.model.Run run) throws IOException
Asserts that the console output of the build does not contain the given substring.- Throws:
IOException
-
getLog
public static String getLog(hudson.model.Run run) throws IOException
Get entire log file as plain text.Run.getLog()is deprecated for reasons that are irrelevant in tests, and also does not strip console annotations which are a distraction in test output.- Throws:
IOException
-
waitForCompletion
public <R extends hudson.model.Run<?,?>> R waitForCompletion(R r) throws InterruptedExceptionWaits for a build to complete. Useful in conjunction withBuildWatcher.- Returns:
- the same build, once done
- Throws:
InterruptedException- Since:
- 1.607
-
waitForMessage
public <R extends hudson.model.Run<?,?>> R waitForMessage(String message, R r) throws IOException, InterruptedException
Waits for a build log to contain a specified string. Useful in conjunction withBuildWatcher.- Returns:
- the same build, once it does
- Throws:
IOExceptionInterruptedException- Since:
- 1.607
-
assertXPath
public void assertXPath(org.htmlunit.html.HtmlPage page, String xpath)Asserts that the XPath matches.
-
assertXPath
public void assertXPath(org.htmlunit.html.DomNode page, String xpath)Asserts that the XPath matches the contents of a DomNode page. This variant of assertXPath(HtmlPage page, String xpath) allows us to examine XmlPages.
-
assertXPathValue
public void assertXPathValue(org.htmlunit.html.DomNode page, String xpath, String expectedValue)
-
assertXPathValueContains
public void assertXPathValueContains(org.htmlunit.html.DomNode page, String xpath, String needle)
-
assertXPathResultsContainText
public void assertXPathResultsContainText(org.htmlunit.html.DomNode page, String xpath, String needle)
-
assertAllImageLoadSuccessfully
public void assertAllImageLoadSuccessfully(org.htmlunit.html.HtmlPage p)
Makes sure that all the images in the page loads successfully. (By default, HtmlUnit doesn't load images.)
-
assertStringContains
public void assertStringContains(String message, String haystack, String needle)
-
assertHelpExists
public void assertHelpExists(Class<? extends hudson.model.Describable> type, String properties) throws Exception
Asserts that help files exist for the specified properties of the given instance.- Parameters:
type- The describable class type that should have the associated help files.properties- ','-separated list of properties whose help files should exist.- Throws:
Exception
-
submit
public org.htmlunit.html.HtmlPage submit(org.htmlunit.html.HtmlForm form) throws ExceptionSubmits the form. PlainHtmlForm.submit(SubmittableElement)doesn't work correctly due to the use of YUI in Jenkins.- Throws:
Exception
-
submit
public org.htmlunit.html.HtmlPage submit(org.htmlunit.html.HtmlForm form, String name) throws ExceptionSubmits the form by clicking the submit button of the given name.- Parameters:
name- This corresponds to the @name of<f:submit />- Throws:
Exception
-
findPreviousInputElement
public org.htmlunit.html.HtmlInput findPreviousInputElement(org.htmlunit.html.HtmlElement current, String name)
-
getButtonByCaption
public org.htmlunit.html.HtmlButton getButtonByCaption(org.htmlunit.html.HtmlForm f, String s)
-
createTaskListener
public hudson.model.TaskListener createTaskListener()
Creates aTaskListenerconnected to stdout.
-
assertEqualBeans
public void assertEqualBeans(Object lhs, Object rhs, String properties) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException
Asserts that two JavaBeans are equal as far as the given list of properties are concerned.This method takes two objects that have properties (getXyz, isXyz, or just the public xyz field), and makes sure that the property values for each given property are equals (by using
MatcherAssert.assertThat(Object, org.hamcrest.Matcher))Property values can be null on both objects, and that is OK, but passing in a property that doesn't exist will fail an assertion.
This method is very convenient for comparing a large number of properties on two objects, for example to verify that the configuration is identical after a config screen roundtrip.
- Parameters:
lhs- One of the two objects to be compared.rhs- The other object to be comparedproperties- ','-separated list of property names that are compared.- Throws:
InvocationTargetExceptionIllegalAccessExceptionNoSuchMethodException- Since:
- 1.297
-
setQuietPeriod
public void setQuietPeriod(int qp)
-
assertEqualDataBoundBeans
public void assertEqualDataBoundBeans(Object lhs, Object rhs) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException
Works likeassertEqualBeans(Object, Object, String)but figure out the properties viaDataBoundConstructorandDataBoundSetter
-
assertEqualDataBoundBeans
public void assertEqualDataBoundBeans(List<?> lhs, List<?> rhs) throws Exception
Makes sure that two collections are identical viaassertEqualDataBoundBeans(Object, Object)- Throws:
Exception
-
findDataBoundConstructor
public Constructor<?> findDataBoundConstructor(Class<?> c)
-
get
public <T extends hudson.model.Descriptor<?>> T get(Class<T> d)
Gets the descriptor instance of the current Hudson by its type.
-
isSomethingHappening
public boolean isSomethingHappening()
Returns true if Hudson is building something or going to build something.
-
waitUntilNoActivity
public void waitUntilNoActivity() throws ExceptionWaits until Hudson finishes building everything, including those in the queue.- Throws:
Exception
-
waitUntilNoActivityUpTo
public void waitUntilNoActivityUpTo(int timeout) throws ExceptionWaits until Hudson finishes building everything, including those in the queue, or fail the test if the specified timeout milliseconds is- Throws:
Exception
-
recipe
public void recipe() throws ExceptionCalled during thebefore()to give a test case an opportunity to control the test environment in which Hudson is run.One could override this method and call a series of
withXXXmethods, or you can use the annotations withRecipemeta-annotation.- Throws:
Exception
-
recipeLoadCurrentPlugin
public void recipeLoadCurrentPlugin() throws ExceptionIf this test harness is launched for a Jenkins plugin, locate thetarget/test-classes/the.jpland add a recipe to install that to the new Jenkins.This file is created by
maven-hpi-pluginat the testCompile phase when the current packaging isjpi.- Throws:
Exception
-
withNewHome
public JenkinsRule withNewHome()
-
withExistingHome
public JenkinsRule withExistingHome(File source) throws Exception
- Throws:
Exception
-
withPresetData
public JenkinsRule withPresetData(String name)
Declares that this test case expects to start with one of the preset data sets. Seetest/src/main/preset-data/for available datasets and what they mean.
-
with
public JenkinsRule with(HudsonHomeLoader homeLoader)
-
executeOnServer
public <V> V executeOnServer(Callable<V> c) throws Exception
Executes the given closure on the server, by the servlet request handling thread, in the context of an HTTP request.In
JenkinsRule, a thread that's executing the test code is different from the thread that carries out HTTP requests made throughJenkinsRule.WebClient. But sometimes you want to make assertions and other calls with side-effect from within the request handling thread.This method allows you to do just that. It is useful for testing some methods that require
StaplerRequestandStaplerResponse, or getting the credential of the current user (viaJenkins.getAuthentication(), and so on.- Parameters:
c- The closure to be executed on the server.- Returns:
- The return value from the closure.
- Throws:
Exception- If a closure throws any exception, that exception will be carried forward.
-
writeReplace
protected Object writeReplace()
Sometimes a part of a test case may ends up creeping into the serialization tree ofSaveable.save(), so detect that and flag that as an error.
-
createWebClient
public JenkinsRule.WebClient createWebClient()
Create a web client instance using the browser version returned byBrowserVersion.getDefault()with support for the Fetch API.
-
getTestDescription
public org.junit.runner.Description getTestDescription()
-
-