Search in sources :

Example 1 with Tag

use of org.junit.jupiter.api.Tag in project ojAlgo-finance by optimatika.

the class StrategyMixer method testStratCombPortfolioMixerRandom.

@Test
@Tag("unstable")
public void testStratCombPortfolioMixerRandom() {
    final FinancePortfolio tmpTarget = new SimplePortfolio(QUARTER, QUARTER, QUARTER, QUARTER).normalise();
    final Uniform tmpGen = new Uniform();
    final FinancePortfolio tmpStrat1 = new SimplePortfolio(tmpGen.doubleValue(), tmpGen.doubleValue(), tmpGen.doubleValue(), tmpGen.doubleValue()).normalise();
    final FinancePortfolio tmpStrat2 = new SimplePortfolio(tmpGen.doubleValue(), tmpGen.doubleValue(), tmpGen.doubleValue(), tmpGen.doubleValue()).normalise();
    final FinancePortfolio tmpStrat3 = new SimplePortfolio(tmpGen.doubleValue(), tmpGen.doubleValue(), tmpGen.doubleValue(), tmpGen.doubleValue()).normalise();
    final PortfolioMixer tmpMixer = new PortfolioMixer(tmpTarget, tmpStrat1, tmpStrat2, tmpStrat3);
    final int tmpExpectedNumberOfStrategies = 2;
    final List<BigDecimal> tmpStrategyWeights = tmpMixer.mix(tmpExpectedNumberOfStrategies);
    int tmpUseCount = 0;
    double tmpTotalWeight = 0D;
    for (final BigDecimal tmpWeight : tmpStrategyWeights) {
        if (tmpWeight.signum() != 0) {
            tmpUseCount++;
            tmpTotalWeight += tmpWeight.doubleValue();
        }
    }
    TestUtils.assertEquals(tmpExpectedNumberOfStrategies, tmpUseCount);
    TestUtils.assertEquals(PrimitiveMath.ONE, tmpTotalWeight, 1E-14 / PrimitiveMath.THREE / PrimitiveMath.HUNDRED);
}
Also used : Uniform(org.ojalgo.random.Uniform) BigDecimal(java.math.BigDecimal) Test(org.junit.jupiter.api.Test) Tag(org.junit.jupiter.api.Tag)

Example 2 with Tag

use of org.junit.jupiter.api.Tag in project junit5 by junit-team.

the class DynamicTestsDemo method generateRandomNumberOfTests.

@TestFactory
Stream<DynamicTest> generateRandomNumberOfTests() {
    // Generates random positive integers between 0 and 100 until
    // a number evenly divisible by 7 is encountered.
    Iterator<Integer> inputGenerator = new Iterator<Integer>() {

        Random random = new Random();

        // end::user_guide[]
        {
            // Use fixed seed to always produce the same number of tests for execution on the CI server
            random = new Random(23);
        }

        // tag::user_guide[]
        int current;

        @Override
        public boolean hasNext() {
            current = random.nextInt(100);
            return current % 7 != 0;
        }

        @Override
        public Integer next() {
            return current;
        }
    };
    // Generates display names like: input:5, input:37, input:85, etc.
    Function<Integer, String> displayNameGenerator = (input) -> "input:" + input;
    // Executes tests based on the current input value.
    ThrowingConsumer<Integer> testExecutor = (input) -> assertTrue(input % 7 != 0);
    // Returns a stream of dynamic tests.
    return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
}
Also used : IntStream(java.util.stream.IntStream) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) TestFactory(org.junit.jupiter.api.TestFactory) Iterator(java.util.Iterator) Collection(java.util.Collection) Random(java.util.Random) DynamicNode(org.junit.jupiter.api.DynamicNode) Function(java.util.function.Function) List(java.util.List) Stream(java.util.stream.Stream) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) DynamicTest.dynamicTest(org.junit.jupiter.api.DynamicTest.dynamicTest) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) DynamicContainer.dynamicContainer(org.junit.jupiter.api.DynamicContainer.dynamicContainer) DynamicTest(org.junit.jupiter.api.DynamicTest) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Tag(org.junit.jupiter.api.Tag) ThrowingConsumer(org.junit.jupiter.api.function.ThrowingConsumer) Random(java.util.Random) Iterator(java.util.Iterator) TestFactory(org.junit.jupiter.api.TestFactory)

Example 3 with Tag

use of org.junit.jupiter.api.Tag in project mssql-jdbc by Microsoft.

the class ConnectionDriverTest method testThreadInterruptedStatus.

/**
 * Test thread's interrupt status is not cleared.
 *
 * @throws InterruptedException
 */
@Test
@Tag("slow")
public void testThreadInterruptedStatus() throws InterruptedException {
    Runnable runnable = new Runnable() {

        public void run() {
            SQLServerDataSource ds = new SQLServerDataSource();
            ds.setURL(connectionString);
            ds.setServerName("invalidServerName" + UUID.randomUUID());
            ds.setLoginTimeout(5);
            try {
                ds.getConnection();
            } catch (SQLException e) {
                isInterrupted = Thread.currentThread().isInterrupted();
            }
        }
    };
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future<?> future = executor.submit(runnable);
    Thread.sleep(1000);
    // interrupt the thread in the Runnable
    future.cancel(true);
    Thread.sleep(8000);
    executor.shutdownNow();
    assertTrue(isInterrupted, "Thread's interrupt status is not set.");
}
Also used : SQLException(java.sql.SQLException) SQLServerDataSource(com.microsoft.sqlserver.jdbc.SQLServerDataSource) ExecutorService(java.util.concurrent.ExecutorService) AbstractTest(com.microsoft.sqlserver.testframework.AbstractTest) Test(org.junit.jupiter.api.Test) Tag(org.junit.jupiter.api.Tag)

Example 4 with Tag

use of org.junit.jupiter.api.Tag in project mssql-jdbc by Microsoft.

the class PreparedStatementTest method testStatementPooling.

/**
 * Test handling of statement pooling for prepared statements.
 *
 * @throws SQLException
 */
@Test
@Tag("slow")
public void testStatementPooling() throws SQLException {
    // Test % handle re-use
    try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) {
        String query = String.format("/*statementpoolingtest_re-use_%s*/SELECT TOP(1) * FROM sys.tables;", UUID.randomUUID().toString());
        con.setStatementPoolingCacheSize(10);
        boolean[] prepOnFirstCalls = { false, true };
        for (boolean prepOnFirstCall : prepOnFirstCalls) {
            con.setEnablePrepareOnFirstPreparedStatementCall(prepOnFirstCall);
            int[] queryCounts = { 10, 20, 30, 40 };
            for (int queryCount : queryCounts) {
                String[] queries = new String[queryCount];
                for (int i = 0; i < queries.length; ++i) {
                    queries[i] = String.format("%s--%s--%s--%s", query, i, queryCount, prepOnFirstCall);
                }
                int testsWithHandleReuse = 0;
                final int testCount = 500;
                for (int i = 0; i < testCount; ++i) {
                    Random random = new Random();
                    int queryNumber = random.nextInt(queries.length);
                    try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(queries[queryNumber])) {
                        pstmt.execute();
                        // Grab handle-reuse before it would be populated if initially created.
                        if (0 < pstmt.getPreparedStatementHandle())
                            testsWithHandleReuse++;
                        // Make sure handle is updated.
                        pstmt.getMoreResults();
                    }
                }
                System.out.println(String.format("Prep on first call: %s Query count:%s: %s of %s (%s)", prepOnFirstCall, queryCount, testsWithHandleReuse, testCount, (double) testsWithHandleReuse / (double) testCount));
            }
        }
    }
    try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) {
        // Test behvaior with statement pooling.
        con.setStatementPoolingCacheSize(10);
        this.executeSQL(con, "IF NOT EXISTS (SELECT * FROM sys.messages WHERE message_id = 99586) EXEC sp_addmessage 99586, 16, 'Prepared handle GAH!';");
        // Test with missing handle failures (fake).
        this.executeSQL(con, "CREATE TABLE #update1 (col INT);INSERT #update1 VALUES (1);");
        this.executeSQL(con, "CREATE PROC #updateProc1 AS UPDATE #update1 SET col += 1; IF EXISTS (SELECT * FROM #update1 WHERE col % 5 = 0) RAISERROR(99586,16,1);");
        try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement("#updateProc1")) {
            for (int i = 0; i < 100; ++i) {
                try {
                    assertSame(1, pstmt.executeUpdate());
                } catch (SQLException e) {
                    // Since the original "Could not find prepared statement with handle" error does not terminate the execution after it.
                    if (!e.getMessage().contains("Prepared handle GAH")) {
                        throw e;
                    }
                }
            }
        }
        // although executeUpdate() throws exception, update operation should be executed successfully.
        try (ResultSet rs = con.createStatement().executeQuery("select * from #update1")) {
            rs.next();
            assertSame(101, rs.getInt(1));
        }
        // Test batching with missing handle failures (fake).
        this.executeSQL(con, "IF NOT EXISTS (SELECT * FROM sys.messages WHERE message_id = 99586) EXEC sp_addmessage 99586, 16, 'Prepared handle GAH!';");
        this.executeSQL(con, "CREATE TABLE #update2 (col INT);INSERT #update2 VALUES (1);");
        this.executeSQL(con, "CREATE PROC #updateProc2 AS UPDATE #update2 SET col += 1; IF EXISTS (SELECT * FROM #update2 WHERE col % 5 = 0) RAISERROR(99586,16,1);");
        try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement("#updateProc2")) {
            for (int i = 0; i < 100; ++i) {
                pstmt.addBatch();
            }
            int[] updateCounts = null;
            try {
                updateCounts = pstmt.executeBatch();
            } catch (BatchUpdateException e) {
                // Since the original "Could not find prepared statement with handle" error does not terminate the execution after it.
                if (!e.getMessage().contains("Prepared handle GAH")) {
                    throw e;
                }
            }
            // since executeBatch() throws exception, it does not return anthing. So updateCounts is still null.
            assertSame(null, updateCounts);
            // although executeBatch() throws exception, update operation should be executed successfully.
            try (ResultSet rs = con.createStatement().executeQuery("select * from #update2")) {
                rs.next();
                assertSame(101, rs.getInt(1));
            }
        }
    }
    try (SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(connectionString)) {
        // Test behvaior with statement pooling.
        con.setDisableStatementPooling(false);
        con.setStatementPoolingCacheSize(10);
        String lookupUniqueifier = UUID.randomUUID().toString();
        String query = String.format("/*statementpoolingtest_%s*/SELECT * FROM sys.tables;", lookupUniqueifier);
        // Execute statement first, should create cache entry WITHOUT handle (since sp_executesql was used).
        try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(query)) {
            // sp_executesql
            pstmt.execute();
            // Make sure handle is updated.
            pstmt.getMoreResults();
            assertSame(0, pstmt.getPreparedStatementHandle());
        }
        // Execute statement again, should now create handle.
        int handle = 0;
        try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(query)) {
            // sp_prepexec
            pstmt.execute();
            // Make sure handle is updated.
            pstmt.getMoreResults();
            handle = pstmt.getPreparedStatementHandle();
            assertNotSame(0, handle);
        }
        // Execute statement again and verify same handle was used.
        try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(query)) {
            // sp_execute
            pstmt.execute();
            // Make sure handle is updated.
            pstmt.getMoreResults();
            assertNotSame(0, pstmt.getPreparedStatementHandle());
            assertSame(handle, pstmt.getPreparedStatementHandle());
        }
        // Execute new statement with different SQL text and verify it does NOT get same handle (should now fall back to using sp_executesql).
        SQLServerPreparedStatement outer = null;
        try (SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) con.prepareStatement(query + ";")) {
            outer = pstmt;
            // sp_executesql
            pstmt.execute();
            // Make sure handle is updated.
            pstmt.getMoreResults();
            assertSame(0, pstmt.getPreparedStatementHandle());
            assertNotSame(handle, pstmt.getPreparedStatementHandle());
        }
        try {
            System.out.println(outer.getPreparedStatementHandle());
            fail("Error for invalid use of getPreparedStatementHandle() after statement close expected.");
        } catch (Exception e) {
        // Good!
        }
    }
}
Also used : SQLException(java.sql.SQLException) SQLServerPreparedStatement(com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement) BatchUpdateException(java.sql.BatchUpdateException) SQLException(java.sql.SQLException) SQLServerConnection(com.microsoft.sqlserver.jdbc.SQLServerConnection) Random(java.util.Random) ResultSet(java.sql.ResultSet) BatchUpdateException(java.sql.BatchUpdateException) Test(org.junit.jupiter.api.Test) AbstractTest(com.microsoft.sqlserver.testframework.AbstractTest) Tag(org.junit.jupiter.api.Tag)

Example 5 with Tag

use of org.junit.jupiter.api.Tag in project ojAlgo by optimatika.

the class DecompositionProblems method testP20160419.

/**
 * A user reported problems related to calculating the pseudoinverse for large (2000x2000) matrices.
 */
@Test
@Tag("slow")
public void testP20160419() {
    final PrimitiveDenseStore tmpOrg = PrimitiveDenseStore.FACTORY.makeFilled(2000, 2000, new Normal());
    final SingularValue<Double> tmpRaw = new RawSingularValue();
    try {
        final MatrixStore<Double> tmpInv = tmpRaw.invert(tmpOrg);
        TestUtils.assertEquals(tmpOrg, tmpOrg.multiply(tmpInv).multiply(tmpOrg), NumberContext.getGeneral(6, 6));
    } catch (final RecoverableCondition exception) {
        exception.printStackTrace();
    }
}
Also used : RecoverableCondition(org.ojalgo.RecoverableCondition) Normal(org.ojalgo.random.Normal) PrimitiveDenseStore(org.ojalgo.matrix.store.PrimitiveDenseStore) Test(org.junit.jupiter.api.Test) Tag(org.junit.jupiter.api.Tag)

Aggregations

Tag (org.junit.jupiter.api.Tag)43 Test (org.junit.jupiter.api.Test)35 lombok.val (lombok.val)9 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)6 Order (org.junit.jupiter.api.Order)6 TestMethodOrder (org.junit.jupiter.api.TestMethodOrder)6 ArrayList (java.util.ArrayList)5 RepeatedTest (org.junit.jupiter.api.RepeatedTest)5 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)5 FeatureFlag (org.janusgraph.testutil.FeatureFlag)4 AbstractTest (com.microsoft.sqlserver.testframework.AbstractTest)3 Path (java.nio.file.Path)3 SQLException (java.sql.SQLException)3 Random (java.util.Random)3 ExecutorService (java.util.concurrent.ExecutorService)3 JanusGraphVertex (org.janusgraph.core.JanusGraphVertex)3 PropertyKey (org.janusgraph.core.PropertyKey)3 SQLServerConnection (com.microsoft.sqlserver.jdbc.SQLServerConnection)2 SQLServerDataSource (com.microsoft.sqlserver.jdbc.SQLServerDataSource)2 ServerAddress (com.mongodb.ServerAddress)2