/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at legal-notices/CDDLv1_0.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
*
* Copyright 2006-2010 Sun Microsystems, Inc.
* Portions Copyright 2011-2015 ForgeRock AS
* Portions Copyright 2013 Manuel Gaupp
*/
/**
* This class defines some utility functions which can be used by test cases.
*/
@SuppressWarnings("javadoc")
public final class TestCaseUtils {
/** The name of the system property that specifies the server build root. */
/**
* The name of the system property that specifies an existing OpenDS
* installation root (inside or outside of the source tree).
*/
"org.opends.server.InstalledRoot";
/**
* The name of the system property that specifies an LDIF file
* with changes compare to the default config.ldif.
*/
"org.opends.server.ConfigChangeFile";
/**
* The name of the system property that specifies if the test instance
* directory needs to be wiped out before starting the setup or not. This will
* let the caller the possibility to copy some files (ie extensions) inside
* the test instance directory before the server starts up.
*/
"org.opends.server.CleanupDirectories";
/**
* The name of the system property that specifies the ldap port.
* Set this property when running the server if you want to use a given
* port number, otherwise a port is chosen randomly at test startup time.
*/
"org.opends.server.LdapPort";
/**
* The name of the system property that specifies the admin port. Set this
* property when running the server if you want to use a given port number,
* otherwise a port is chosen randomly at test startup time.
*/
"org.opends.server.AdminPort";
/**
* If this System property is set to true, then the classes/ directory
* will be copied into the server package setup for the tests. This allows
* the server tools (e.g. ldapsearch) to be used on a live server, but it
* takes a while to copy all of the files, so we don't do it by default.
*/
"org.opends.test.copyClassesToTestPackage";
/**
* The string representation of the DN that will be used as the base entry for
* the test backend. This must not be changed, as there are a number of test
* cases that depend on this specific value of "o=test".
*/
/** The backend if for the test backend. */
/**
* The string representation of the OpenDMK jar file location
* that will be used as base to determine if snmp is included or not.
*/
"org.opends.server.snmp.opendmk";
/** The test text writer for the Debug Logger. */
/** The test text writer for the Error Logger. */
/** The test text writer for the Access Logger. */
/** The test text writer for the HTTP Access Logger. */
/**
* Indicates whether the server has already been started. The value of this
* constant must not be altered by anything outside the
* <CODE>startServer</CODE> method.
*/
public static boolean SERVER_STARTED;
/**
* This is used to store the schema as it was before starting the fake server
* (for example, it could have been the real schema) so test tearDown can set it back.
*/
/** The LDAP port the server is bound to on start. */
private static int serverLdapPort;
/** The Administration port the server is bound to on start. */
private static int serverAdminPort;
/** The JMX port the server is bound to on start. */
private static int serverJmxPort;
/** The LDAPS port the server is bound to on start. */
private static int serverLdapsPort;
/** Incremented by one each time the server has restarted. */
private static int serverRestarts;
/** The config directory in the test environment. */
/**
* Setup in-memory versions of everything needed to run unit tests with the
* {@link DirectoryServer} class.
* <p>
* This method is trying hard to provide sensible defaults and core data you
* would expect from a normal install, including AttributeTypes, etc.
*
* @see #shutdownFakeServer() Matching method that must be called in the test
* tear down.
*/
{
}
{
{
}
return schema;
}
/**
* Starts the Directory Server so that it will be available for use while
* running the unit tests. This will only actually start the server once, so
* subsequent attempts to start it will be ignored because it will already be
* available.
*
* @throws Exception If an unexpected problem occurs.
*/
{
try {
if (SERVER_STARTED)
{
return;
}
// Retrieves the location of a typical installation directory to use as a
// source to build our test instance.
// Get the build root and use it to create a test package directory.
if (installedRoot == null) {
} else {
}
if (cleanupRequired) {
}
//db_verify is second jeb backend used by the jeb verify test cases
//db_rebuild is the third jeb backend used by the jeb rebuild test cases
//db_unindexed is the forth backend used by the unindexed search privilege
//test cases
"config", "db", "import-tmp", "db_verify",
"ldif", "locks", "logs", "db_rebuild",
"db_unindexed", "db_index_test",
"db_import_test"};
for (String s : installSubDirectories)
{
}
for (String s : instanceSubDirectories)
{
}
// Copy the configuration, schema, and MakeLDIF resources into the
// appropriate place under the test package.
// Set the class variable
// Snmp resource
"resource");
{
}
if (installedRoot != null)
{
// Get the instance location
}
else
{
// copy upgrade directory
// Update the install.loc file
{
}
if (opendmkJar.exists())
{
}
{
try
{
} catch (Exception e) {}
}
// Make the shell scripts in the bin directory executable, if possible.
if (OperatingSystem.isUnixBased())
{
try
{
{
{
}
}
} catch (Exception e) {}
}
}
// Find some free ports for the listeners and write them to the
// config-chamges.ldif file.
+ "config-changes.ldif";
{
{
}
}
// Create a configuration for the server.
config.setForceDaemonThreads(true);
// Initialize the configuration framework for DSConfig.
// Enable more verbose error logger.
// Writing the buildinfo with the current version.
{
}
// Save config.ldif for when we restart the server
SERVER_STARTED = true;
initializeTestBackend(true);
} catch (Exception e) {
throw e;
}
}
{
{
return findFreePort();
}
// Check this port is free
return portNb;
}
/**
* Similar to startServer, but it will restart the server each time it is
* called. Since this is somewhat expensive, it should be called under
* two circumstances. Either in an @AfterClass method for a test that
* makes lots of configuration changes to the server, or in a @BeforeClass
* method for a test that is very sensitive to running in a clean server.
*
* @throws IOException If a problem occurs while interacting with the
* filesystem to prepare the test package root.
*
* @throws InitializationException If a problem occurs while starting the
* server.
*
* @throws ConfigException If there is a problem with the server
* configuration.
*/
public static synchronized void restartServer()
{
if (!SERVER_STARTED) {
startServer();
return;
}
try {
initializeTestBackend(true);
// This generates too much noise, so it's disabled by default.
// outputLogContentsIfError("Potential problem during in-core restart. You be the judge.");
// Keep track of these so we can report how long they took in the test summary
} catch (Exception e) {
throw e;
}
}
}
{
if (backend instanceof BackendImpl) {
}
}
}
{
}
{
if (testConfigDir == null) {
throw new RuntimeException("The testConfigDir variable is not set yet!");
}
return testConfigDir;
}
{
}
{
}
// Sometimes this fails because config.ldif is in use, so we wait
// and try it again.
try {
} catch (IOException e) {
sleep(1000);
}
}
/**
* Bring the server to a quiescent state. This includes waiting for all
* operations to complete. This can be used in a @BeforeMethod setup method
* to make sure that the server has finished processing all operations
* from previous tests.
*/
public static void quiesceServer()
{
}
/**
* This can be made public if quiesceServer becomes too heavy-weight in
* some circumstance.
*/
private static void waitForOpsToComplete()
{
try {
final long NO_TIMEOUT = -1;
} catch (Exception e) {
// Ignore it, maybe the server hasn't been started.
}
}
/**
* Binds to the given socket port on the local host.
* @return the bounded Server socket.
*
* @throws IOException in case of underlying exception.
* @throws SocketException in case of underlying exception.
*/
throws IOException
{
serverLdapSocket.setReuseAddress(true);
return serverLdapSocket;
}
/**
* Find and binds to a free server socket port on the local host.
* @return the bounded Server socket.
*
* @throws IOException in case of underlying exception.
* @throws SocketException in case of underlying exception.
*/
{
return bindPort(0);
}
/**
* Find a free port on the local host.
*
* @throws IOException
* in case of underlying exception.
* @return the free port number found
*/
{
}
/**
* Find nb free ports on the local host.
*
* @param nb
* the number of free ports to find
* @throws IOException
* in case of underlying exception.
* @return an array with the free port numbers found
*/
{
try
{
for (int i = 0; i < nb; i++)
{
}
return ports;
}
finally
{
}
}
/**
* Finds a free server socket port on the local host.
*
* @return The free port.
*/
{
{
return serverLdapSocket.getLocalSocketAddress();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
/**
* Undo all the setup done by #startFakeServer().
*
* @see #startFakeServer() Matching method that starts the fake server
*/
public static void shutdownFakeServer()
{
}
/**
* Shut down the server. This should only be called at the end of the test
* suite and not by any unit tests.
*
* @param reason
* The reason for the shutdown.
*/
{
if (SERVER_STARTED)
{
SERVER_STARTED = false;
}
}
/**
* Initializes a memory-based backend that may be used to perform operations
* while testing the server. This will ensure that the memory backend is
* created in the server if it does not yet exist, and that it is empty. Note
* that the base DN for the test backend will always be "o=test", and it must
* not be changed. It is acceptable for test cases using this backend to
* hard-code their sample data to use this base DN, although they may still
* reference the <CODE>TEST_ROOT_DN_STRING</CODE> constant if they wish.
*
* @param createBaseEntry Indicate whether to automatically create the base
* entry and add it to the backend.
*
* @throws Exception If an unexpected problem occurs.
*/
{
}
/**
* Initializes a memory-based backend that may be used to perform operations
* while testing the server. This will ensure that the memory backend is
* created in the server if it does not yet exist, and that it is empty.
*
* @param backendID the ID of the backend to create
* @param namingContext the naming context to create in the backend
* @param createBaseEntry Indicate whether to automatically create the base
* entry and add it to the backend.
*
* @throws Exception If an unexpected problem occurs.
*/
public static void initializeMemoryBackend(
boolean createBaseEntry
) throws Exception
{
startServer();
// Retrieve backend. Warning: it is important to perform this each time,
// because a test may have disabled then enabled the backend (i.e a test
// performing an import task). As it is a memory backend, when the backend
// is re-enabled, a new backend object is in fact created and old reference
// to memory backend must be invalidated. So to prevent this problem, we
// retrieve the memory backend reference each time before cleaning it.
if (memoryBackend == null)
{
memoryBackend = new MemoryBackend();
}
if (createBaseEntry)
{
}
}
/**
* Clears a memory-based backend.
*/
{
// FIXME JNR I suspect we could call finalizeBackend() here (but also in other
// places in this class), because finalizeBackend() calls clearMemoryBackend().
if (memoryBackend != null)
{
}
}
/**
* Clears all the entries from the backend determined by the backend id passed into the method.
*
* @throws Exception If an unexpected problem occurs.
*/
{
}
/**
* Clears all the entries from the backend determined by the backend id passed into the method.
*
* @param backendId The backend id to clear
* @param baseDN If not null, the suffix of the backend to create
* @throws Exception If an unexpected problem occurs.
*/
{
{
}
}
{
if (b instanceof BackendImpl)
{
if (rootContainer != null)
{
{
// assertEquals(ec.getHighestEntryID().longValue(), 0L);
}
return true;
}
}
return false;
}
/**
* Create a temporary directory with the specified prefix.
*
* @param prefix
* The directory prefix.
* @return The temporary directory.
* @throws IOException
* If the temporary directory could not be created.
*/
throws IOException {
}
}
return tmpDir;
}
/**
* Copy a directory and its contents.
*
* @param src
* The name of the directory to copy.
* @param dst
* The name of the destination directory.
* @throws IOException
* If the directory could not be copied.
*/
if (src.isDirectory()) {
// Create the destination directory if it does not exist.
}
// Recursively copy sub-directories and files.
}
} else {
}
}
/**
* Delete a directory and its contents.
*
* @param dir
* The name of the directory to delete.
* @throws IOException
* If the directory could not be deleted.
*/
{
return;
}
if (dir.isDirectory()) {
// Recursively delete sub-directories and files.
}
}
}
{
}
/**
* Copy a file.
*
* @param src
* The name of the source file.
* @param dst
* The name of the destination file.
* @throws IOException
* If the file could not be copied.
*/
}
{
}
throws IOException
{
{
// Transfer bytes from in to out
byte[] buf = new byte[8192];
int len;
{
}
}
}
/**
* Get the LDAP port the test environment Directory Server instance is
* running on.
*
* @return The port number.
*/
public static int getServerLdapPort()
{
return serverLdapPort;
}
/**
* Get the Admin port the test environment Directory Server instance is
* running on.
*
* @return The port number.
*/
public static int getServerAdminPort()
{
return serverAdminPort;
}
/**
* Get the JMX port the test environment Directory Server instance is
* running on.
*
* @return The port number.
*/
public static int getServerJmxPort()
{
return serverJmxPort;
}
/**
* Get the LDAPS port the test environment Directory Server instance is
* running on.
*
* @return The port number.
*/
public static int getServerLdapsPort()
{
return serverLdapsPort;
}
/**
* Get the number of times the server has done a restart during the unit tests.
*
* @return the number of server restarts.
*/
public static int getNumServerRestarts()
{
return serverRestarts;
}
/**
* Method for getting a file from the test resources directory.
*
* @return The directory as a File
*/
{
}
{
}
/** Prevent instantiation. */
private TestCaseUtils() {
// No implementation.
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Various methods for converting LDIF Strings to Entries
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
/**
* Returns a modifiable List of entries parsed from the provided LDIF.
* It's best to call this after the server has been initialized so
* that schema checking happens.
* <p>
* Also take a look at the makeLdif method below since this makes
* expressing LDIF a little bit cleaner.
*
* @param ldif of the entries to parse.
* @return a List of EntryS parsed from the ldif string.
* @see #makeLdif
*/
ldifImportConfig.setValidateSchema(false);
{
{
}
return entries;
}
}
/**
* This is used as a convenience when and LDIF string only includes a single
* entry. It's best to call this after the server has been initialized so
* that schema checking happens.
* <p>
* Also take a look at the makeLdif method below since this makes
* expressing LDIF a little bit cleaner.
*
* @return the first Entry parsed from the ldif String
* @see #makeLdif
*/
}
/**
* This method provides the minor convenience of not having to specify the
* newline character at the end of every line of LDIF in test code.
* This is an admittedly small advantage, but it does make things a little
* easier and less error prone. For example, this
*
<pre>
private static final String JOHN_SMITH_LDIF = TestCaseUtils.makeLdif(
"dn: cn=John Smith,dc=example,dc=com",
"objectclass: inetorgperson",
"cn: John Smith",
"sn: Smith",
"givenname: John");
</pre>
is a <bold>little</bold> easier to work with than
<pre>
private static final String JOHN_SMITH_LDIF =
"dn: cn=John Smith,dc=example,dc=com\n" +
"objectclass: inetorgperson\n" +
"cn: John Smith\n" +
"sn: Smith\n" +
"givenname: John\n";
</pre>
*
* @return the concatenation of each line followed by a newline character
*/
}
// Append an extra line so we can append LDIF Strings.
}
/**
* This is a convenience method that constructs an Entry from the specified
* lines of LDIF. Here's a sample usage
*
<pre>
Entry john = TestCaseUtils.makeEntry(
"dn: cn=John Smith,dc=example,dc=com",
"objectclass: inetorgperson",
"cn: John Smith",
"sn: Smith",
"givenname: John");
</pre>
* @see #makeLdif
*/
}
/**
* This is a convenience method that constructs an List of EntryS from the
* specified lines of LDIF. Here's a sample usage
*
<pre>
List<Entry> smiths = TestCaseUtils.makeEntries(
"dn: cn=John Smith,dc=example,dc=com",
"objectclass: inetorgperson",
"cn: John Smith",
"sn: Smith",
"givenname: John",
"",
"dn: cn=Jane Smith,dc=example,dc=com",
"objectclass: inetorgperson",
"cn: Jane Smith",
"sn: Smith",
"givenname: Jane");
</pre>
* @see #makeLdif
*/
}
/**
* Adds the provided entry to the Directory Server using an internal
* operation.
*
* @param entry The entry to be added.
*
* @throws Exception If an unexpected problem occurs.
*/
{
}
/**
* Deletes the provided entry from the Directory Server using an
* internal operation.
*
* @param entry The entry to be deleted.
*
* @throws Exception If an unexpected problem occurs.
*/
{
}
/**
* Deletes the provided entry from the Directory Server using an
* internal operation.
*
* @param dn The dn of entry to be deleted
*
* @throws Exception If an unexpected problem occurs.
*/
{
}
{
// Check that the user can bind.
{
3,
} catch (Exception t) {
t.printStackTrace();
return false;
}
}
/**
* Configures a socket for use in unit tests. This should only be used if the
* socket is not expected to timeout.
*
* @param s
* The socket.
* @throws Exception
* If an unexpected exception occurred while configuring the socket.
*/
{
}
/**
* Adds the provided entry to the Directory Server using an internal
* operation.
*
* @param lines The lines that make up the entry to be added.
* @return the added entry
* @throws Exception If an unexpected problem occurs.
*/
{
assertNotNull(e);
return e;
}
/**
* Adds the provided entry to the Directory Server using an internal
* operation.
*
* @param lines The lines that make up the entry to be added.
*
* @return result code for this operation.
*
* @throws Exception If an unexpected problem occurs.
*/
{
return addOperation.getResultCode();
}
/**
* Adds the provided set of entries to the Directory Server using internal
* operations.
*
* @param entries The entries to be added.
*
* @throws Exception If an unexpected problem occurs.
*/
{
{
}
}
/**
* Adds the provided set of entries to the Directory Server using internal
* operations.
*
* @param lines The lines defining the entries to add. If there are
* multiple entries, then they should be separated by blank
* lines.
*
* @throws Exception If an unexpected problem occurs.
*/
{
{
}
}
/**
* Applies a set of modifications to the server as described in the provided
* set of lines (using LDIF change form). The changes will be applied over
* LDAP using the ldapmodify tool using the "cn=Directory Manager" account.
*
* @param lines The set of lines including the changes to make to the
* server.
*
* @return The result code from applying the set of modifications. if it is
* nonzero, then there was a failure of some kind.
*
* @throws Exception If an unexpected problem occurs.
*/
throws Exception
{
if (! SERVER_STARTED)
{
startServer();
}
{
"--noPropertiesFile",
"-h", "127.0.0.1",
"-D", "cn=Directory Manager",
"-w", "password",
"-a",
"-f", path
};
{
"--noPropertiesFile",
"-h", "127.0.0.1",
"-Z", "-X",
"-D", "cn=Directory Manager",
"-w", "password",
"-a",
"-f", path
};
if (useAdminPort) {
}
}
/**
* Creates a temporary text file with the specified contents. It will be
* marked for automatic deletion when the JVM exits.
*
* @return The absolute path to the file that was created.
*
* @throws Exception If an unexpected problem occurs.
*/
{
f.deleteOnExit();
try (FileWriter w = new FileWriter(f))
{
{
}
}
return f.getAbsolutePath();
}
/** Convenience method so we don't have to catch InterruptedException everywhere. */
try {
} catch (InterruptedException e) {
// Ignore it.
}
}
/**
* Return a Map constructed via alternating key and value pairs.
*/
{
}
return map;
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
/** The set of loggers for which the console logger has been disabled. */
/** The original System.err print stream. Use this if you absolutely
* must write something to System.err. */
/** The original System.out print stream. Use this if you absolutely
* must write something to System.out. */
/** System.err is redirected to here so that we can only print it out
* if a test fails. */
/** System.out is redirected to here so that we can only print it out
* if a test fails. */
public static synchronized void suppressOutput() {
{
while (loggerNames.hasMoreElements())
{
{
break;
}
{
if (h instanceof ConsoleHandler)
{
logger.removeHandler(h);
break;
}
}
}
}
}
/**
* @return everything written to System.out since the last time
* clearSystemOutContents was called.
*/
return redirectedSystemOut.toString();
}
/**
* @return everything written to System.err since the last time
* clearSystemErrContents was called.
*/
return redirectedSystemErr.toString();
}
/**
* Clear everything written to System.out since the last time
* clearSystemOutContents was called.
*/
public static synchronized void clearSystemOutContents() {
}
/**
* Clear everything written to System.err since the last time
* clearSystemErrContents was called.
*/
public static synchronized void clearSystemErrContents() {
}
/**
* Clear everything written to the Access, Error, or Debug loggers.
*/
public static synchronized void clearLoggersContents() {
}
/**
* Append the contents of the Access Log, Error Log, Debug Loggers,
* System.out, System.err to the specified buffer.
*/
{
}
{
{
}
}
{
{
{
}
}
}
public static synchronized void unsupressOutput() {
{
l.addHandler(h);
}
}
/** Read the contents of a file and return it as a String. */
}
/** Read the contents of a file and return it as a String. */
}
/**
* Returns the contents of file as a List of the lines as defined by
* java.io.BufferedReader#readLine() (i.e. the line terminator is not
* included). An ArrayList is explicitly returned, so that callers know that
* random access is not expensive.
*/
}
return lines;
}
/** Read the contents of a file and return it as a String. */
return readInputStreamBytes(fis, true);
}
/**
* @param close - if true, close when finished reading.
* @return input stream content.
*/
try {
byte[] buf = new byte[1024];
int bytesRead;
} // end of while ((read(buf) != -1)
}
finally {
if (close)
{
}
}
}
return bytes;
}
/** Store the contents of a String in a file. */
}
/** Store the contents of a String in a file. */
}
/** Store the contents of a String in a file. */
{
}
}
/**
* Invokes the dsconfig tool with the provided set of arguments. Note that
* the address, port, bind DN (cn=Directory Manager), and password will always
* be provided, so they should not be included in the argument list. The
* given arguments should include only the subcommand and its associated
* options, along with any other global options that may not be included by
* default.
* <BR><BR>
* An assertion will be used to ensure that the dsconfig invocation is
* successful. If running dsconfig returns a non-zero result, then an
* assertion error will be thrown.
*
* @param args The set of arguments that should be provided when invoking
* the dsconfig tool
*/
{
try {
} catch (Exception e) {
}
}
/**
* Gets the root configuration associated with the active server
* instance. This root configuration can then be used to access and
* modify the server's configuration using that administration
* framework's strongly typed API.
* <p>
* Note: were possible the {@link #dsconfig(String...)} method
* should be used in preference to this method in order to perform
* end-to-end testing.
*
* @return Returns the root configuration associated with the active
* server instance.
* @throws Exception
* If the management context could not be initialized
* against the active server instance.
*/
{
"127.0.0.1",
"cn=Directory Manager",
"password");
return context.getRootConfiguration();
}
/**
* Return a String representation of all of the current threads.
* @return a dump of all Threads on the server
*/
{
// Re-arrange all of the elements by thread ID so that there is some logical order.
{
}
{
if (stackElements != null)
{
{
if (stackElement.isNativeMethod())
{
}
else
{
}
}
}
}
}
{
setBackendEnabled(backendID, true);
}
{
setBackendEnabled(backendID, false);
}
{
}
{
{
{
for (ByteString v : a)
{
}
}
}
return pluginTypes;
}
/** Saves a thread dump in a file with the provided id used in file prefix. */
{
try (BufferedWriter writer = new BufferedWriter(new FileWriter("/tmp/thread_dump_" + id + "_" + date)))
{
}
catch (Exception e)
{
// do nothing
}
}
/** Generates a thread dump programmatically. */
}
}
}
/** FIXME Replace with {@link Assert#assertNotEquals(Object, Object)} once we upgrade to testng >= 6.1. */
{
}
/** FIXME Replace with {@link Assert#assertNotEquals(Object, Object, String)} once we upgrade to testng >= 6.1. */
{
boolean fail = false;
try
{
fail = true;
}
catch (AssertionError e)
{
}
if (fail)
{
}
}
}