@Test
 public void testGetType() {
   TestContext ctx = new TestContext.Builder().set("Test").set("a", 1).set("b", 2).build();
   assertEquals(String.class, ctx.getType(String.class.getName()));
   assertEquals(Integer.class, ctx.getType("a"));
   assertEquals(Integer.class, ctx.getType("b"));
 }
Ejemplo n.º 2
0
  /**
   * Makes sure the MDX runs correctly and not in native mode.
   *
   * @param rowCount Number of rows returned
   * @param mdx Query
   * @param expectedResult Expected result string
   */
  protected void checkNotNative(int rowCount, String mdx, String expectedResult) {
    getConnection().getCacheControl(null).flushSchemaCache();
    Connection con = getTestContext().withSchemaPool(false).getConnection();
    RolapNativeRegistry reg = getRegistry(con);
    reg.setListener(
        new Listener() {
          public void foundEvaluator(NativeEvent e) {
            fail("should not be executed native");
          }

          public void foundInCache(TupleEvent e) {}

          public void executingSql(TupleEvent e) {}
        });

    TestCase c = new TestCase(con, 0, rowCount, mdx);
    Result result = c.run();

    if (expectedResult != null) {
      String nonNativeResult = TestContext.toString(result);
      if (!nonNativeResult.equals(expectedResult)) {
        TestContext.assertEqualsVerbose(
            expectedResult,
            nonNativeResult,
            false,
            "Non Native implementation returned different result than " + "expected; MDX=" + mdx);
      }
    }
  }
 @Test
 public void testSetWithKey() {
   TestContext ctx = new TestContext.Builder().set("myKey", "Test").build();
   assertNull(ctx.get(String.class));
   assertEquals("Test", ctx.get("myKey", String.class));
   assertEquals(ctx.get("myKey", String.class), "Test");
   assertEquals(ctx.get(String.class.getName(), String.class), null);
 }
 public void run() {
   try {
     doWork();
   } catch (Throwable t) {
     ctx.threadFailed(t);
   }
   ctx.threadDone();
 }
 @Test
 public void testSetWithKeyAndType() {
   TestContext ctx = new TestContext.Builder().set("MyNum", 2).build();
   assertNull(ctx.get(String.class));
   assertEquals(Integer.valueOf(2), ctx.getInt("MyNum"));
   assertEquals(ctx.get("MyNum", Number.class), 2);
   assertNotNull(ctx.get("MyNum", Integer.class));
 }
 public void startAppServer(@Observes(precedence = -1) BeforeClass event)
     throws MalformedURLException, InterruptedException, IOException {
   if (testContext.isAdapterTest()) {
     ContainerController controller = containerConrollerInstance.get();
     if (!controller.isStarted(testContext.getAppServerInfo().getQualifier())) {
       controller.start(testContext.getAppServerInfo().getQualifier());
     }
   }
 }
Ejemplo n.º 7
0
 @Override
 protected Object createTest() throws Exception {
   Object test = super.createTest();
   if (PARENT_CLASS.isAssignableFrom(getTestClass().getJavaClass())) {
     JongoTestCase jongoTestCase = (JongoTestCase) test;
     jongoTestCase.prepareMarshallingStrategy(
         testContext.getMarshaller(), testContext.getUnmarshaller());
   }
   return test;
 }
 @Test
 public void testGetKeys() {
   TestContext ctx = new TestContext.Builder().set("Test").set("a", 1).set("b", 2).build();
   Set<String> keys = ctx.getKeys(String.class);
   assertNotNull(keys);
   assertFalse(keys.isEmpty());
   assertEquals(String.class.getName(), keys.iterator().next());
   keys = ctx.getKeys(Integer.class);
   assertNotNull(keys);
   assertTrue(keys.size() == 2);
   assertTrue("a".equals(keys.iterator().next()) || "b".equals(keys.iterator().next()));
 }
 public void installAdapterLibs(@Observes BeforeDeploy event) {
   log.debug("BEFORE DEPLOY - INSTALL ADAPTER LIBS");
   if (testContext.isAdapterTest()) {
     // install adapter libs on JBoss-based container via CLI
     if (testContext.getAppServerInfo().isJBossBased()) {
       try {
         installAdapterLibsUsingJBossCLIClient(testContext.getAppServerInfo());
       } catch (InterruptedException | IOException ex) {
         throw new RuntimeException("Failed to install adapter libs.", ex);
       }
     }
   }
 }
Ejemplo n.º 10
0
  /**
   * Tests <a href="http://jira.pentaho.com/browse/MONDRIAN-750">bug MONDRIAN-750, "... multiple
   * hierarchies beneath a single dimension throws exception"</a>.
   */
  public void testDefaultNamedHierarchy() {
    TestContext testContext =
        TestContext.instance()
            .createSubstitutingCube(
                "Sales",
                "<Dimension name=\"NuStore\" foreignKey=\"store_id\">\n"
                    + "<Hierarchy name=\"NuStore\" hasAll=\"true\" primaryKey=\"store_id\">\n"
                    + "  <Table name=\"store\"/>\n"
                    + "  <Level name=\"NuStore Country\" column=\"store_country\" uniqueMembers=\"true\"/>\n"
                    + "  <Level name=\"NuStore State\" column=\"store_state\" uniqueMembers=\"true\"/>\n"
                    + "  <Level name=\"NuStore City\" column=\"store_city\" uniqueMembers=\"false\"/>\n"
                    + "  <Level name=\"NuStore Name\" column=\"store_name\" uniqueMembers=\"true\"/>\n"
                    + "</Hierarchy>\n"
                    + "<Hierarchy caption=\"NuStore2\" name=\"NuStore2\" allMemberName=\"All NuStore2s\" hasAll=\"true\" primaryKey=\"NuStore_id\">\n"
                    + "  <Table name=\"store\"/>\n"
                    + "  <Level name=\"NuStore City\" column=\"store_city\" uniqueMembers=\"false\"/>\n"
                    + "  <Level name=\"NuStore Name\" column=\"store_name\"  uniqueMembers=\"true\"/>\n"
                    + "</Hierarchy>\n"
                    + "</Dimension>");

    final String nuStore = TestContext.hierarchyName("NuStore", "NuStore");

    testContext.assertQueryReturns(
        "with set [*NATIVE_CJ_SET] as '[*BASE_MEMBERS_NuStore]' "
            + "set [*SORTED_ROW_AXIS] as 'Order([*CJ_ROW_AXIS], "
            + nuStore
            + ".CurrentMember.OrderKey, BASC)' "
            + "set [*BASE_MEMBERS_NuStore] as '"
            + nuStore
            + ".[NuStore Country].Members' "
            + "set [*BASE_MEMBERS_Measures] as '{[Measures].[*ZERO]}' "
            + "set [*CJ_ROW_AXIS] as 'Generate([*NATIVE_CJ_SET], {"
            + nuStore
            + ".CurrentMember})' "
            + "set [*CJ_COL_AXIS] as '[*NATIVE_CJ_SET]' "
            + "member [Measures].[*ZERO] as '0.0', SOLVE_ORDER = 0.0 "
            + "select [*BASE_MEMBERS_Measures] ON COLUMNS, "
            + "[*SORTED_ROW_AXIS] ON ROWS "
            + "from [Sales]",
        "Axis #0:\n"
            + "{}\n"
            + "Axis #1:\n"
            + "{[Measures].[*ZERO]}\n"
            + "Axis #2:\n"
            + "{[NuStore].[Canada]}\n"
            + "{[NuStore].[Mexico]}\n"
            + "{[NuStore].[USA]}\n"
            + "Row #0: 0\n"
            + "Row #1: 0\n"
            + "Row #2: 0\n");
  }
 @Test
 public void testRoundRobinClear() throws PersistenceLayerException {
   if (isClearLegal()) {
     if (requiresPreconstruction()) {
       getConstant("Languedoc-Roussillon");
     }
     verifyCleanStart();
     TestContext tc = new TestContext();
     commit(testCampaign, tc, "Languedoc-Roussillon");
     commit(testCampaign, tc, Constants.LST_DOT_CLEAR);
     tc = new TestContext();
     tc.putText(testCampaign.getURI(), null);
     completeRoundRobin(tc);
   }
 }
 @Test
 public void testRoundRobinAppend() throws PersistenceLayerException {
   if (requiresPreconstruction()) {
     getConstant("Languedoc-Roussillon");
     getConstant("Finger Lakes");
   }
   verifyCleanStart();
   TestContext tc = new TestContext();
   commit(testCampaign, tc, "Languedoc-Roussillon");
   commit(testCampaign, tc, "Finger Lakes");
   tc = new TestContext();
   tc.putText(
       testCampaign.getURI(),
       new String[] {"Languedoc-Roussillon" + getJoinCharacter() + "Finger Lakes"});
   completeRoundRobin(tc);
 }
Ejemplo n.º 13
0
 protected void setUp() throws Exception {
   super.setUp(); // parent setUp enabled agg
   propSaver.set(propSaver.properties.EnableNativeCrossJoin, true);
   propSaver.set(propSaver.properties.EnableNativeNonEmpty, true);
   propSaver.set(propSaver.properties.GenerateFormattedSql, true);
   TestContext.instance().flushSchemaCache();
 }
Ejemplo n.º 14
0
  protected void scheduleTasksAndStart(TestContext ctx, long cyclesCount) {
    InsertBookTask insertBookTask = new InsertBookTask(ctx);
    UpdateBookRatingTask updateBookRatingTask = new UpdateBookRatingTask(ctx);
    UpdateBookTotalSoldTask updateBookTotalSoldTask = new UpdateBookTotalSoldTask(ctx);
    QueryBooksByAuthorTask queryBooksByAuthorTask = new QueryBooksByAuthorTask(ctx);
    QueryBooksByAverageRatingTask queryBooksByAverageRatingTask =
        new QueryBooksByAverageRatingTask(ctx);
    QueryBooksByBestRatingTask queryBooksByBestRatingTask = new QueryBooksByBestRatingTask(ctx);
    QueryBooksByNewestPublishedTask queryBooksByNewestPublishedTask =
        new QueryBooksByNewestPublishedTask(ctx);
    QueryBooksBySummaryTask queryBooksBySummaryTask = new QueryBooksBySummaryTask(ctx);
    QueryBooksByTitleTask queryBooksByTitleTask = new QueryBooksByTitleTask(ctx);
    QueryBooksByTotalSoldTask queryBooksByTotalSoldTask = new QueryBooksByTotalSoldTask(ctx);

    for (int i = 0; i < cyclesCount; i++) {
      ctx.executor.execute(insertBookTask);
      ctx.executor.execute(updateBookRatingTask);
      ctx.executor.execute(updateBookTotalSoldTask);
      ctx.executor.execute(queryBooksByAuthorTask);
      ctx.executor.execute(queryBooksByAverageRatingTask);
      ctx.executor.execute(queryBooksByBestRatingTask);
      ctx.executor.execute(queryBooksByNewestPublishedTask);
      ctx.executor.execute(queryBooksBySummaryTask);
      ctx.executor.execute(queryBooksByTitleTask);
      ctx.executor.execute(queryBooksByTotalSoldTask);
    }

    ctx.startAndWait();
  }
 public void updateTestContextWithAppServerInfo(@Observes(precedence = 1) BeforeClass event) {
   testContext = testContextProducer.get();
   String appServerQualifier = getAppServerQualifier(testContext.getTestClass());
   for (ContainerInfo container : testContext.getSuiteContext().getContainers()) {
     if (container.getQualifier().equals(appServerQualifier)) {
       testContext.setAppServerInfo(updateWithAppServerInfo(container));
     }
   }
   // validate app server
   if (appServerQualifier != null && testContext.getAppServerInfo() == null) {
     throw new RuntimeException(
         String.format(
             "No app server container matching '%s' was activated. Check if defined and enabled in arquillian.xml.",
             appServerQualifier));
   }
   log.info("\n\n" + testContext);
 }
Ejemplo n.º 16
0
 protected void doRun(TestCase testCase) throws Exception {
   if (testCase.isIgnored()) {
     logWarning(Text.valueOf("Ignore ").plus(testCase.getName()));
     return;
   }
   logMessage("test", Text.valueOf(testCase.getName()));
   super.doRun(testCase);
 }
 @Test
 public void testRoundRobinMerge() throws PersistenceLayerException {
   if (isMerge()) {
     construct(primaryContext, "TestWP1");
     construct(primaryContext, "TestWP2");
     construct(secondaryContext, "TestWP1");
     construct(secondaryContext, "TestWP2");
     verifyCleanStart();
     TestContext tc = new TestContext();
     commit(testCampaign, tc, getPrefix() + "TestWP1");
     commit(testCampaign, tc, getPrefix() + "TestWP2");
     tc = new TestContext();
     tc.putText(
         testCampaign.getURI(),
         new String[] {getPrefix() + "TestWP1" + getJoinCharacter() + "TestWP2"});
     completeRoundRobin(tc);
   }
 }
Ejemplo n.º 18
0
 private RolapCube lookupCube(String cubeName) {
   Connection connection = TestContext.instance().getConnection();
   for (Cube cube : connection.getSchema().getCubes()) {
     if (cube.getName().equals(cubeName)) {
       return (RolapCube) cube;
     }
   }
   return null;
 }
Ejemplo n.º 19
0
  public <T> T invokeAsAdministrator(final Callable<T> callable) throws Exception {
    final TestContext ctx = TestContainer.getInstance().getTestContext();
    final String username = ctx.getUsername();
    final String password = ctx.getPassword();
    final boolean secure = ctx.isSecureTest();
    ctx.useAdminForRequests();
    ctx.setSecureTest(true);

    try {
      return callable.call();
    } finally {
      ctx.setUsername(username);
      ctx.setPassword(password);
      ctx.setSecureTest(secure);
    }
  }
Ejemplo n.º 20
0
 @Test
 public void runTestWithAsyncFailure() throws Exception {
   BlockingQueue<TestContext> queue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 context.async();
                 queue.add(context);
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   assertFalse(reporter.completed());
   TestContext test = queue.poll(2, TimeUnit.SECONDS);
   try {
     test.fail("the_message");
   } catch (AssertionError ignore) {
   }
   reporter.await();
   assertTrue(reporter.completed());
 }
Ejemplo n.º 21
0
 protected boolean doAssert(boolean value, CharSequence message) {
   if (!value) {
     super.doAssert(value, message); // Logs error.
     if (JUNIT_ERROR_CONSTRUCTOR != null) {
       RuntimeException junitError =
           (RuntimeException) JUNIT_ERROR_CONSTRUCTOR.newInstance(message.toString());
       throw junitError;
     } else {
       throw new AssertionException(message.toString());
     }
   }
   return true;
 }
  /**
   * Attempt to create a copy of the supplied {@code TestContext} using its <em>copy
   * constructor</em>.
   */
  private static TestContext copyTestContext(TestContext testContext) {
    Constructor<? extends TestContext> constructor =
        ClassUtils.getConstructorIfAvailable(testContext.getClass(), testContext.getClass());

    if (constructor != null) {
      try {
        ReflectionUtils.makeAccessible(constructor);
        return constructor.newInstance(testContext);
      } catch (Exception ex) {
        if (logger.isInfoEnabled()) {
          logger.info(
              String.format(
                  "Failed to invoke copy constructor for [%s]; "
                      + "concurrent test execution is therefore likely not supported.",
                  testContext),
              ex);
        }
      }
    }

    // fallback to original instance
    return testContext;
  }
  private ContainerInfo updateWithAppServerInfo(
      ContainerInfo appServerInfo, int clusterPortOffset) {
    try {

      String appServerContextRootStr =
          isRelative(testContext.getTestClass())
              ? getAuthServerContextRoot(clusterPortOffset)
              : getAppServerContextRoot(clusterPortOffset);

      appServerInfo.setContextRoot(new URL(appServerContextRootStr));

    } catch (MalformedURLException ex) {
      throw new IllegalArgumentException(ex);
    }
    return appServerInfo;
  }
  @Before
  public void init() throws Exception {

    Properties configuration = new Properties();
    configuration.load(new FileReader(PROPERTIES_FILE));

    TestContext tc = new TestContext();

    tc.setTo(configuration.getProperty("channelserver_to_test"));
    tc.setTopicChannelServer(configuration.getProperty("topic_channel_server"));

    tc.setClientUser(configuration.getProperty("testclient_user"));
    tc.setClientPass(configuration.getProperty("testclient_pass"));

    tc.setClientResource(configuration.getProperty("testclient_resource"));
    tc.setServerHostname(configuration.getProperty("testclient_xmpphost"));
    tc.setServiceName(configuration.getProperty("testclient_xmppservice"));
    tc.setServerPort(Integer.parseInt(configuration.getProperty("testclient_xmppport")));

    setContext(tc);
    initConnection();
  }
 @Test
 public void testToString() {
   TestContext ctx = new TestContext.Builder().set("Test").set(1).set((long) 2).build();
   assertNotNull(ctx.toString());
   assertTrue(ctx.toString().contains("1"));
   assertTrue(ctx.toString().contains("2"));
   assertTrue(ctx.toString().contains("Test"));
   assertTrue(ctx.toString().contains("String"));
   assertTrue(ctx.toString().contains("Integer"));
   assertTrue(ctx.toString().contains("Long"));
   assertTrue(ctx.toString().contains("TestContext"));
 }
  @Override
  protected void proceedOnce(TestContext context) {
    JComponent component = getComponentFromName(context);
    try {
      BufferedImage componentBufferedImage = exportImageFromComponent(component);
      BufferedImage expectedBufferedImage;
      String parentPath = context.getProperty(AgfTask.TEST_DIRECTORY);
      File expectedFile = new File(parentPath, expected);
      if (!expectedFile.exists()) {
        expectedBufferedImage = exportImageFromComponent(component);
        ImageIO.write(expectedBufferedImage, "bmp", expectedFile);
      } else {
        expectedBufferedImage = ImageIO.read(expectedFile);
      }

      proceedComparison(expectedBufferedImage, componentBufferedImage);
    } catch (IOException e) {
      fail("Impossible d'ouvrir le fichier spécifié.");
    }
  }
Ejemplo n.º 27
0
 public void testMembersOfHierarchiesInSameDimensionInSlicer() {
   assertQueryReturns(
       "select {[Measures].[Unit Sales]} on columns,\n"
           + " {[Store].children} on rows\n"
           + "from [Sales]\n"
           + "where ([Gender].[M], "
           + TestContext.hierarchyName("Time", "Weekly")
           + ".[1997], [Time].[1997].[Q1])",
       "Axis #0:\n"
           + "{[Gender].[M], [Time].[Weekly].[1997], [Time].[1997].[Q1]}\n"
           + "Axis #1:\n"
           + "{[Measures].[Unit Sales]}\n"
           + "Axis #2:\n"
           + "{[Store].[Canada]}\n"
           + "{[Store].[Mexico]}\n"
           + "{[Store].[USA]}\n"
           + "Row #0: \n"
           + "Row #1: \n"
           + "Row #2: 33,381\n");
 }
Ejemplo n.º 28
0
  private File createDistSuggestedSitesFile(int n) {
    FileOutputStream fos = null;

    try {
      File distFile = File.createTempFile("distrosites", ".json", context.getCacheDir());

      fos = new FileOutputStream(distFile);
      fos.write(generateSites(n, DIST_PREFIX).getBytes());

      return distFile;
    } catch (IOException e) {
      fail("Failed to create temp suggested sites file");
    } finally {
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
          // Ignore.
        }
      }
    }

    return null;
  }
Ejemplo n.º 29
0
 protected void remove(VersionedOntology vo) {
   if (ctx.graph.getHandle(vo.ontology()) != null) ctx.m.removeOntology(vo.ontology());
   new GarbageCollector(ctx.repo()).runGarbageCollection();
 }
public class MavenProxyResourceTest {

  // test with the following NodeJS and NPM versions
  private static final String[] NODEJS_VERSIONS = {"0.12.0", "4.4.0"};
  private static final String[] NODEJS_TARGETS = {
    "-windows-x86.exe",
    "-windows-x64.exe",
    "-linux-x86.tar.gz",
    "-linux-x64.tar.gz",
    "-darwin-x64.tar.gz"
  };
  private static final String[] NPM_VERSIONS = {"1.4.9"};
  private static final String[] NPM_TARGETS = {".tgz"};

  @Rule
  public ResourceTestRule context =
      new ResourceTestRule.Builder()
          .addResource(
              new MavenProxyResource(TestContext.getConfiguration(), TestContext.getHttpClient()))
          .build();

  @Test
  public void testGetIndex() {
    String path = "/";
    Response response = context.client().target(path).request().get();
    assertResponse(path, response, MediaType.TEXT_HTML);
  }

  @Test
  public void testGetPomNodeJS() {
    for (String version : NODEJS_VERSIONS) {
      String path =
          "/org/nodejs/dist/nodejs-binaries/" + version + "/nodejs-binaries-" + version + ".pom";
      Response response = context.client().target(path).request().get();
      assertResponse(path, response, MediaType.APPLICATION_XML);
      assertTrue("Content length " + path, response.getLength() > 0);
      assertSHA1(path, response);
    }
  }

  @Test
  public void testGetPomNPM() {
    for (String version : NPM_VERSIONS) {
      String path =
          "/org/nodejs/dist/npm-binaries/" + version + "/npm-binaries-" + version + ".pom";
      Response response = context.client().target(path).request().get();
      assertResponse(path, response, MediaType.APPLICATION_XML);
      assertTrue("Content length " + path, response.getLength() > 0);
      assertSHA1(path, response);
    }
  }

  @Test
  public void testGetBinaryNodeJS() {
    for (String version : NODEJS_VERSIONS) {
      for (String target : NODEJS_TARGETS) {
        String path =
            "/org/nodejs/dist/nodejs-binaries/" + version + "/nodejs-binaries-" + version + target;
        Response response = context.client().target(path).request().get();
        assertResponse(path, response, MediaType.APPLICATION_OCTET_STREAM);
        assertSHA1(path, response);
      }
    }
  }

  @Test
  public void testGetBinaryNPM() {
    for (String version : NPM_VERSIONS) {
      for (String target : NPM_TARGETS) {
        String path =
            "/org/nodejs/dist/npm-binaries/" + version + "/npm-binaries-" + version + target;
        Response response = context.client().target(path).request().get();
        assertResponse(path, response, MediaType.APPLICATION_OCTET_STREAM);
        assertSHA1(path, response);
      }
    }
  }

  private void assertResponse(String path, Response response, String mediaType) {
    System.out.println("Integration test: " + path);
    assertEquals("HTTP status " + path, HttpStatus.SC_OK, response.getStatus());
    assertEquals("Media type " + path, mediaType, response.getMediaType().toString());
    assertTrue(response.hasEntity());
  }

  private void assertSHA1(String path, Response dataResponse) {
    String sha1Path = path + ".sha1";
    Response sha1Response = context.client().target(sha1Path).request().get();
    assertResponse(sha1Path, sha1Response, MediaType.TEXT_PLAIN);

    try (InputStream is = dataResponse.readEntity(InputStream.class)) {
      byte[] data = IOUtils.toByteArray(is);
      String sha1 = sha1Response.readEntity(String.class);
      assertEquals("SHA-1 " + path, sha1, DigestUtils.sha1Hex(data));
    } catch (IOException ex) {
      throw new RuntimeException("Error checking SHA-1 of " + path, ex);
    }
  }
}