Class TestContext
- java.lang.Object
-
- mondrian.test.TestContext
-
- Direct Known Subclasses:
DelegatingTestContext
public class TestContext extends Object
TestContext
is a singleton class which contains the information necessary to run mondrian tests (otherwise we'd have to pass this information into the constructor of TestCases).The singleton instance (retrieved via the
instance()
method) contains a connection to the FoodMart database, and runs expressions in the context of theSales
cube.Using the
DelegatingTestContext
subclass, you can create derived classes which use a different connection or a different cube.- Since:
- 29 March, 2002
- Author:
- jhyde
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
TestContext.ConnectionInvocationHandler
static class
TestContext.DatabaseMetaDataInvocationHandler
static class
TestContext.HighCardDynamicSchemaProcessor
Schema processor that flags dimensions as high-cardinality if they appear in the list of values in theMondrianProperties.TestHighCardinalityDimensionList
property.static class
TestContext.SafeString
Wrapper around a string that indicates that all line endings have been converted to platform-specific line endings.static class
TestContext.SnoopingSchemaProcessor
-
Constructor Summary
Constructors Modifier Constructor Description protected
TestContext()
Creates a TestContext.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description static String
allHiers()
static String
allHiersExcept(String... hiers)
Generates a string containing all dimensions except those given.void
assertAxisReturns(String expression, String expected)
Executes a query with a given expression on an axis, and asserts that it returns the expected string.void
assertAxisThrows(String expression, String pattern)
Executes a query with a given expression on an axis, and asserts that it throws an error which matches a particular pattern.static void
assertEqualsVerbose(String expected, String actual)
Checks that an actual string matches an expected string.static void
assertEqualsVerbose(String expected, String actual, boolean java, String message)
Checks that an actual string matches an expected string.static void
assertEqualsVerbose(TestContext.SafeString safeExpected, String actual, boolean java, String message)
Checks that an actual string matches an expected string.void
assertExprDependsOn(String expr, String hierList)
Asserts that an MDX expression depends upon a given list of dimensions.void
assertExprReturns(String expression, String expected)
Executes an expression and asserts that it returns a given result.void
assertExprThrows(String expression, String pattern)
Executes an expression, and asserts that it gives an error which contains a particular pattern.void
assertMatchesVerbose(Pattern expected, String actual)
Checks that an actual string matches an expected pattern.void
assertMemberExprDependsOn(String expr, String dimList)
Asserts that an MDX member-valued depends upon a given list of dimensions.void
assertParameterizedExprReturns(String expr, String expected, Object... paramValues)
Asserts that an expression, with a given set of parameter bindings, returns a given result.void
assertQueryReturns(String query, String desiredResult)
Executes a query and checks that the result is a given string.void
assertQueryReturns(String message, String query, String desiredResult)
Executes a query and checks that the result is a given string, displaying a message if result does not match desiredResult.void
assertQueryThrows(String queryString, String pattern)
Executes a query, and asserts that it throws an exception which contains the given pattern.void
assertSetExprDependsOn(String expr, String dimList)
Asserts that an MDX set-valued expression depends upon a given list of dimensions.void
assertSimpleQuery()
Executes a very simple query.void
assertSqlEquals(String expectedSql, String actualSql, int expectedRows)
Checks that expected SQL equals actual SQL.(package private) static Iterable<Cell>
cellIter(Result result)
Returns an iterator over cells in a result.(package private) static Iterable<Cell>
cellIter(CellSet cellSet)
Returns an iterator over cells in an olap4j cell set.static void
checkThrowable(Throwable throwable, String pattern)
void
close()
String
compileExpression(String expression, boolean scalar)
Compiles a scalar expression in the context of the default cube.static boolean
contains(String[] a, String s)
static TestSuite
copySuite(TestSuite suite, Util.Functor1<Boolean,Test> testPattern)
Makes a copy of a suite, filtering certain tests.TestContext
create(String parameterDefs, String cubeDefs, String virtualCubeDefs, String namedSetDefs, String udfDefs, String roleDefs)
Creates a TestContext which is based on a variant of the FoodMart schema, which parameter, cube, named set, and user-defined function definitions added.TestContext
createSubstitutingCube(String cubeName, String dimensionDefs)
Creates a TestContext, adding hierarchy definitions to a cube definition.TestContext
createSubstitutingCube(String cubeName, String dimensionDefs, String memberDefs)
Creates a TestContext, adding hierarchy and calculated member definitions to a cube definition.TestContext
createSubstitutingCube(String cubeName, String dimensionDefs, String measureDefs, String memberDefs, String namedSetDefs)
Creates a TestContext, adding hierarchy and calculated member definitions to a cube definition.TestContext
createSubstitutingCube(String cubeName, String dimensionDefs, String measureDefs, String memberDefs, String namedSetDefs, String defaultMeasure)
Overload that allows swapping the defaultMeasure.boolean
databaseIsValid()
Tests whether the database is valid.Axis
executeAxis(String expression)
Executes a query with a given expression on an axis, and returns the whole axis.Cell
executeExprRaw(String expression)
Executes the expression in the context of the cube indicated bycubeName
, and returns the result as a Cell.CellSet
executeOlap4jQuery(String queryString)
Executes a query using olap4j.CellSet
executeOlap4jXmlaQuery(String queryString)
Result
executeQuery(String queryString)
Executes a query.Member
executeSingletonAxis(String expression)
Executes a set expression which is expected to return 0 or 1 members.ResultSet
executeStatement(String queryString)
void
flushSchemaCache()
static TestContext.SafeString
fold(String string)
Replaces line-endings in a string with the platform-dependent equivalent.CacheControl
getCacheControl()
Returns aCacheControl
.Connection
getConnection()
Returns the connection to run queries.Util.PropertyList
getConnectionProperties()
String
getConnectString()
Returns the connect string by which the unit tests can talk to the FoodMart database.static String
getDefaultConnectString()
Constructs a connect string by which the unit tests can talk to the FoodMart database.String
getDefaultCubeName()
Returns the name of the default cube.Dialect
getDialect()
static Dialect
getFakeDialect(Dialect.DatabaseProduct product)
Creates a dialect without using a connection.OlapConnection
getOlap4jConnection()
static String
getRawFoodMartSchema()
Returns the definition of the "FoodMart" schema as stored inFoodMart.xml
.String
getRawSchema()
Returns the definition of the schema.String
getSchema(String parameterDefs, String cubeDefs, String virtualCubeDefs, String namedSetDefs, String udfDefs, String roleDefs)
Returns a the XML of the current schema with added parameters and cube definitions.List<Exception>
getSchemaWarnings()
Creates a FoodMart connection with "Ignore=true" and returns the list of warnings in the schema.static String
getStackTrace(Throwable e)
Converts aThrowable
to a stack trace.PrintWriter
getWriter()
Returns the output writer.static String
hierarchyName(String dimension, String hierarchy)
static TestContext
instance()
Retrieves the singleton (instantiating if necessary).static String
levelName(String dimension, String hierarchy, String level)
static String
repeatString(int count, String format)
Returns count copies of a string.static String
toString(List<Position> positions)
Converts a set of positions into a string.static String
toString(Result result)
Converts aResult
to text in traditional format.static String
toString(CellSet cellSet)
Converts aCellSet
to text in traditional format.static String
unfold(String string)
Reverses the effect offold(java.lang.String)
; converts platform-specific line endings in a string info linefeeds.String
upgradeActual(String actual)
Massages the actual result of executing a query to handle differences in unique names betweeen old and new behavior.String
upgradeQuery(String queryString)
Massages an MDX query to handle differences in unique names betweeen old and new behavior.TestContext
withConnection(Connection connection)
Returns aTestContext
similar to this one, but which uses a given connection.TestContext
withCube(String cubeName)
Returns a TestContext similar to this one, but using the given cube as default for tests such asassertExprReturns(String, String)
.TestContext
withFreshConnection()
Returns aTestContext
similar to this one, but which uses a fresh connection.TestContext
withProperties(Util.PropertyList properties)
Creates a TestContext which is like this one but uses the given connection properties.TestContext
withRole(String roleName)
Returns a TestContext similar to this one, but using the given role.TestContext
withScenario()
Returns a test context whosegetOlap4jConnection()
method always returns the same connection object, and which has an activeScenario
, thus enabling writeback.TestContext
withSchema(String schema)
Creates a TestContext which contains the given schema text.TestContext
withSchemaPool(boolean usePool)
TestContext
withSchemaProcessor(Class<? extends DynamicSchemaProcessor> dynProcClass)
Returns a connection to the FoodMart database with a dynamic schema processor and disables use of RolapSchema Pool.
-
-
-
Field Detail
-
nl
protected static final String nl
-
-
Method Detail
-
instance
public static TestContext instance()
Retrieves the singleton (instantiating if necessary).
-
getConnectString
public final String getConnectString()
Returns the connect string by which the unit tests can talk to the FoodMart database.In the base class, the result is the same as the static method
getDefaultConnectString()
. If a derived class overridesgetConnectionProperties()
, the result of this method will change also.
-
getDefaultConnectString
public static String getDefaultConnectString()
Constructs a connect string by which the unit tests can talk to the FoodMart database. The algorithm is as follows:- Starts with
MondrianProperties.TestConnectString
, if it is set. - If
MondrianProperties.FoodmartJdbcURL
is set, this overrides theJdbc
property. - If the
catalog
URL is unset or invalid, it assumes that we are at the root of the source tree, and referencesdemo/FoodMart.xml
.
- Starts with
-
flushSchemaCache
public void flushSchemaCache()
-
getConnection
public Connection getConnection()
Returns the connection to run queries.When invoked on the default TestContext instance, returns a connection to the FoodMart database.
-
withSchemaProcessor
public TestContext withSchemaProcessor(Class<? extends DynamicSchemaProcessor> dynProcClass)
Returns a connection to the FoodMart database with a dynamic schema processor and disables use of RolapSchema Pool.
-
withFreshConnection
public final TestContext withFreshConnection()
Returns aTestContext
similar to this one, but which uses a fresh connection.- Returns:
- Test context which uses the a fresh connection
- See Also:
withSchemaPool(boolean)
-
withSchemaPool
public TestContext withSchemaPool(boolean usePool)
-
getConnectionProperties
public Util.PropertyList getConnectionProperties()
-
getSchema
public String getSchema(String parameterDefs, String cubeDefs, String virtualCubeDefs, String namedSetDefs, String udfDefs, String roleDefs)
Returns a the XML of the current schema with added parameters and cube definitions.
-
getRawFoodMartSchema
public static String getRawFoodMartSchema()
Returns the definition of the "FoodMart" schema as stored inFoodMart.xml
.- Returns:
- XML definition of the FoodMart schema
-
getRawSchema
public String getRawSchema()
Returns the definition of the schema.- Returns:
- XML definition of the FoodMart schema
-
executeQuery
public Result executeQuery(String queryString)
Executes a query.- Parameters:
queryString
- Query string
-
executeStatement
public ResultSet executeStatement(String queryString) throws SQLException
- Throws:
SQLException
-
executeOlap4jQuery
public CellSet executeOlap4jQuery(String queryString) throws SQLException
Executes a query using olap4j.- Throws:
SQLException
-
executeOlap4jXmlaQuery
public CellSet executeOlap4jXmlaQuery(String queryString) throws SQLException
- Throws:
SQLException
-
cellIter
static Iterable<Cell> cellIter(CellSet cellSet)
Returns an iterator over cells in an olap4j cell set.
-
assertQueryThrows
public void assertQueryThrows(String queryString, String pattern)
Executes a query, and asserts that it throws an exception which contains the given pattern.- Parameters:
queryString
- Query stringpattern
- Pattern which exception must match
-
assertExprThrows
public void assertExprThrows(String expression, String pattern)
Executes an expression, and asserts that it gives an error which contains a particular pattern. The error might occur during parsing, or might be contained within the cell value.
-
getDefaultCubeName
public String getDefaultCubeName()
Returns the name of the default cube.Tests which evaluate scalar expressions, such as
assertExprReturns(String, String)
, generate queries against this cube.- Returns:
- the name of the default cube
-
executeExprRaw
public Cell executeExprRaw(String expression)
Executes the expression in the context of the cube indicated bycubeName
, and returns the result as a Cell.- Parameters:
expression
- The expression to evaluate- Returns:
- Cell which is the result of the expression
-
assertExprReturns
public void assertExprReturns(String expression, String expected)
Executes an expression and asserts that it returns a given result.
-
assertParameterizedExprReturns
public void assertParameterizedExprReturns(String expr, String expected, Object... paramValues)
Asserts that an expression, with a given set of parameter bindings, returns a given result.- Parameters:
expr
- Scalar MDX expressionexpected
- Expected resultparamValues
- Array of parameter names and values
-
assertAxisReturns
public void assertAxisReturns(String expression, String expected)
Executes a query with a given expression on an axis, and asserts that it returns the expected string.
-
upgradeActual
public String upgradeActual(String actual)
Massages the actual result of executing a query to handle differences in unique names betweeen old and new behavior.Even though the new naming is not enabled by default, reference logs should be in terms of the new naming.
- Parameters:
actual
- Actual result- Returns:
- Expected result massaged for backwards compatibility
- See Also:
MondrianProperties.SsasCompatibleNaming
-
upgradeQuery
public String upgradeQuery(String queryString)
Massages an MDX query to handle differences in unique names betweeen old and new behavior.The main difference addressed is with level naming. The problem arises when dimension, hierarchy and level have the same name:
- In old behavior, the [Gender].[Gender] represents the Gender level, and [Gender].[Gender].[Gender] is invalid.
- In new behavior, [Gender].[Gender] represents the Gender hierarchy, and [Gender].[Gender].[Gender].members represents the Gender level.
So,
upgradeQuery("[Gender]")
returns "[Gender].[Gender]" for old behavior, "[Gender].[Gender].[Gender]" for new behavior.- Parameters:
queryString
- Original query- Returns:
- Massaged query for backwards compatibility
- See Also:
MondrianProperties.SsasCompatibleNaming
-
compileExpression
public String compileExpression(String expression, boolean scalar)
Compiles a scalar expression in the context of the default cube.- Parameters:
expression
- The expression to evaluatescalar
- Whether the expression is scalar- Returns:
- String form of the program
-
executeSingletonAxis
public Member executeSingletonAxis(String expression)
Executes a set expression which is expected to return 0 or 1 members. It is an error if the expression returns tuples (as opposed to members), or if it returns two or more members.- Parameters:
expression
- Expression string- Returns:
- Null if axis returns the empty set, member if axis returns one member. Throws otherwise.
-
executeAxis
public Axis executeAxis(String expression)
Executes a query with a given expression on an axis, and returns the whole axis.
-
assertAxisThrows
public void assertAxisThrows(String expression, String pattern)
Executes a query with a given expression on an axis, and asserts that it throws an error which matches a particular pattern. The expression is evaulated against the default cube.
-
getWriter
public PrintWriter getWriter()
Returns the output writer.
-
assertQueryReturns
public void assertQueryReturns(String query, String desiredResult)
Executes a query and checks that the result is a given string.
-
assertQueryReturns
public void assertQueryReturns(String message, String query, String desiredResult)
Executes a query and checks that the result is a given string, displaying a message if result does not match desiredResult.
-
assertSimpleQuery
public void assertSimpleQuery()
Executes a very simple query.This forces the schema to be loaded and performs a basic sanity check. If this is a negative schema test, causes schema validation errors to be thrown.
-
assertEqualsVerbose
public static void assertEqualsVerbose(String expected, String actual)
Checks that an actual string matches an expected string.If they do not, throws a
junit.framework.ComparisonFailure
and prints the difference, including the actual string as an easily pasted Java string literal.
-
assertEqualsVerbose
public static void assertEqualsVerbose(String expected, String actual, boolean java, String message)
Checks that an actual string matches an expected string.If they do not, throws a
ComparisonFailure
and prints the difference, including the actual string as an easily pasted Java string literal.- Parameters:
expected
- Expected stringactual
- Actual stringjava
- Whether to generate actual string as a Java string literal if the values are not equalmessage
- Message to display, optional
-
assertEqualsVerbose
public static void assertEqualsVerbose(TestContext.SafeString safeExpected, String actual, boolean java, String message)
Checks that an actual string matches an expected string.If they do not, throws a
ComparisonFailure
and prints the difference, including the actual string as an easily pasted Java string literal.- Parameters:
safeExpected
- Expected string, where all line endings have been converted into platform-specific line endingsactual
- Actual stringjava
- Whether to generate actual string as a Java string literal if the values are not equalmessage
- Message to display, optional
-
assertMatchesVerbose
public void assertMatchesVerbose(Pattern expected, String actual)
Checks that an actual string matches an expected pattern. If they do not, throws aComparisonFailure
and prints the difference, including the actual string as an easily pasted Java string literal.
-
getStackTrace
public static String getStackTrace(Throwable e)
Converts aThrowable
to a stack trace.
-
toString
public static String toString(Result result)
Converts aResult
to text in traditional format.For more exotic formats, see
CellSetFormatter
.- Parameters:
result
- Query result- Returns:
- Result as text
-
toString
public static String toString(CellSet cellSet)
Converts aCellSet
to text in traditional format.For more exotic formats, see
CellSetFormatter
.- Parameters:
cellSet
- Query result- Returns:
- Result as text
-
withScenario
public final TestContext withScenario()
Returns a test context whosegetOlap4jConnection()
method always returns the same connection object, and which has an activeScenario
, thus enabling writeback.- Returns:
- Test context with active scenario
-
toString
public static String toString(List<Position> positions)
Converts a set of positions into a string. Useful if you want to check that an axis has the results you expected.
-
copySuite
public static TestSuite copySuite(TestSuite suite, Util.Functor1<Boolean,Test> testPattern)
Makes a copy of a suite, filtering certain tests.- Parameters:
suite
- Test suitetestPattern
- Regular expression of name of tests to include- Returns:
- copy of test suite
-
close
public void close()
-
getCacheControl
public CacheControl getCacheControl()
Returns aCacheControl
.
-
fold
public static TestContext.SafeString fold(String string)
Replaces line-endings in a string with the platform-dependent equivalent. If the input string already has platform-dependent line endings, no replacements are made.- Parameters:
string
- String whose line endings are to be made platform- dependent. Typically these are constant "expected value" string expressions where the linefeed is represented as linefeed "\n", but sometimes this method will receive strings created dynamically where the line endings are already appropriate for the platform.- Returns:
- String where all linefeeds have been converted to platform-specific (CR+LF on Windows, LF on Unix/Linux)
-
unfold
public static String unfold(String string)
Reverses the effect offold(java.lang.String)
; converts platform-specific line endings in a string info linefeeds.- Parameters:
string
- String where all linefeeds have been converted to platform-specific (CR+LF on Windows, LF on Unix/Linux)- Returns:
- String where line endings are represented as linefeed "\n"
-
getDialect
public Dialect getDialect()
-
getFakeDialect
public static Dialect getFakeDialect(Dialect.DatabaseProduct product)
Creates a dialect without using a connection.- Parameters:
product
- Database product- Returns:
- dialect of an required persuasion
-
assertSqlEquals
public void assertSqlEquals(String expectedSql, String actualSql, int expectedRows)
Checks that expected SQL equals actual SQL. Performs some normalization on the actual SQL to compensate for differences between dialects.
-
assertSetExprDependsOn
public void assertSetExprDependsOn(String expr, String dimList)
Asserts that an MDX set-valued expression depends upon a given list of dimensions.
-
assertMemberExprDependsOn
public void assertMemberExprDependsOn(String expr, String dimList)
Asserts that an MDX member-valued depends upon a given list of dimensions.
-
assertExprDependsOn
public void assertExprDependsOn(String expr, String hierList)
Asserts that an MDX expression depends upon a given list of dimensions.
-
create
public final TestContext create(String parameterDefs, String cubeDefs, String virtualCubeDefs, String namedSetDefs, String udfDefs, String roleDefs)
Creates a TestContext which is based on a variant of the FoodMart schema, which parameter, cube, named set, and user-defined function definitions added.- Parameters:
parameterDefs
- Parameter definitions. If not null, the string is is inserted into the schema XML in the appropriate place for parameter definitions.cubeDefs
- Cube definition(s). If not null, the string is is inserted into the schema XML in the appropriate place for cube definitions.virtualCubeDefs
- Definitions of virtual cubes. If not null, the string is inserted into the schema XML in the appropriate place for virtual cube definitions.namedSetDefs
- Definitions of named sets. If not null, the string is inserted into the schema XML in the appropriate place for named set definitions.udfDefs
- Definitions of user-defined functions. If not null, the string is inserted into the schema XML in the appropriate place for UDF definitions.roleDefs
- Definitions of roles- Returns:
- TestContext which reads from a slightly different hymnbook
-
withSchema
public final TestContext withSchema(String schema)
Creates a TestContext which contains the given schema text.- Parameters:
schema
- XML schema content- Returns:
- TestContext which contains the given schema
-
withProperties
public TestContext withProperties(Util.PropertyList properties)
Creates a TestContext which is like this one but uses the given connection properties.- Parameters:
properties
- Connection properties- Returns:
- TestContext which contains the given properties
-
createSubstitutingCube
public final TestContext createSubstitutingCube(String cubeName, String dimensionDefs)
Creates a TestContext, adding hierarchy definitions to a cube definition.- Parameters:
cubeName
- Name of a cube in the schema (cube must exist)dimensionDefs
- String defining dimensions, or null- Returns:
- TestContext with modified cube defn
-
createSubstitutingCube
public final TestContext createSubstitutingCube(String cubeName, String dimensionDefs, String memberDefs)
Creates a TestContext, adding hierarchy and calculated member definitions to a cube definition.- Parameters:
cubeName
- Name of a cube in the schema (cube must exist)dimensionDefs
- String defining dimensions, or nullmemberDefs
- String defining calculated members, or null- Returns:
- TestContext with modified cube defn
-
createSubstitutingCube
public final TestContext createSubstitutingCube(String cubeName, String dimensionDefs, String measureDefs, String memberDefs, String namedSetDefs)
Creates a TestContext, adding hierarchy and calculated member definitions to a cube definition.- Parameters:
cubeName
- Name of a cube in the schema (cube must exist)dimensionDefs
- String defining dimensions, or nullmeasureDefs
- String defining measures, or nullmemberDefs
- String defining calculated members, or nullnamedSetDefs
- String defining named set definitions, or null- Returns:
- TestContext with modified cube defn
-
createSubstitutingCube
public final TestContext createSubstitutingCube(String cubeName, String dimensionDefs, String measureDefs, String memberDefs, String namedSetDefs, String defaultMeasure)
Overload that allows swapping the defaultMeasure.
-
withRole
public final TestContext withRole(String roleName)
Returns a TestContext similar to this one, but using the given role.- Parameters:
roleName
- Role name- Returns:
- Test context with the given role
-
withCube
public final TestContext withCube(String cubeName)
Returns a TestContext similar to this one, but using the given cube as default for tests such asassertExprReturns(String, String)
.- Parameters:
cubeName
- Cube name- Returns:
- Test context with the given default cube
-
withConnection
public final TestContext withConnection(Connection connection)
Returns aTestContext
similar to this one, but which uses a given connection.- Parameters:
connection
- Connection- Returns:
- Test context which uses the given connection
-
allHiersExcept
public static String allHiersExcept(String... hiers)
Generates a string containing all dimensions except those given. Useful as an argument toassertExprDependsOn(String, String)
.- Returns:
- string containing all dimensions except those given
-
allHiers
public static String allHiers()
-
getSchemaWarnings
public List<Exception> getSchemaWarnings()
Creates a FoodMart connection with "Ignore=true" and returns the list of warnings in the schema.- Returns:
- Warnings encountered while loading schema
-
getOlap4jConnection
public OlapConnection getOlap4jConnection() throws SQLException
- Throws:
SQLException
-
databaseIsValid
public boolean databaseIsValid()
Tests whether the database is valid. Allows tests that depend on optional databases to figure out whether to proceed.- Returns:
- whether a database is present and correct
-
repeatString
public static String repeatString(int count, String format)
Returns count copies of a string. Format strings within string are substituted, perString.format(java.lang.String, java.lang.Object...)
.- Parameters:
count
- Number of copiesformat
- String template- Returns:
- Multiple copies of a string
-
-