@Test
  public void testAddRemoveTradePosition() {

    try {
      TradePosition instance =
          new TradePosition(
              this.tradestrategy.getContract(),
              TradingCalendar.getDateTimeNowMarketTimeZone(),
              Side.BOT);

      TradePosition tradePosition = aspectHome.persist(instance);

      assertNotNull("1", tradePosition.getIdTradePosition());
      _log.info(
          "testAddTradePosition IdTradeStrategy: "
              + this.tradestrategy.getIdTradeStrategy()
              + "IdTradePosition: "
              + tradePosition.getIdTradePosition());

      tradePositionHome.remove(tradePosition);
      _log.info("testDeleteTradePosition IdTradeStrategy: " + tradestrategy.getIdTradeStrategy());
      tradePosition = tradePositionHome.findById(tradePosition.getIdTradePosition());
      assertNull("2", tradePosition);
    } catch (Exception | AssertionError ex) {
      String msg = "Error running " + name.getMethodName() + " msg: " + ex.getMessage();
      _log.error(msg);
      fail(msg);
    }
  }
Exemplo n.º 2
1
  @Test
  public void testAddTradeOrder() {

    try {
      String side = this.tradestrategy.getSide();
      String action = Action.BUY;
      if (Side.SLD.equals(side)) {
        action = Action.SELL;
      }

      double risk = this.tradestrategy.getRiskAmount().doubleValue();

      double stop = 0.20;
      BigDecimal price = new BigDecimal(20);
      int quantity = (int) ((int) risk / stop);
      ZonedDateTime createDate = this.tradestrategy.getTradingday().getOpen().plusMinutes(5);

      TradeOrder tradeOrder =
          new TradeOrder(
              this.tradestrategy,
              action,
              OrderType.STPLMT,
              quantity,
              price,
              price.add(new BigDecimal(0.004)),
              TradingCalendar.getDateTimeNowMarketTimeZone());
      tradeOrder.setOrderKey((new BigDecimal((Math.random() * 1000000))).intValue());
      tradeOrder.setClientId(clientId);
      tradeOrder.setTransmit(true);
      tradeOrder.setStatus("SUBMITTED");
      tradeOrder.validate();
      tradeOrder = tradeOrderHome.persist(tradeOrder);
      assertNotNull("1", tradeOrder);
      _log.info("IdOrder: " + tradeOrder.getIdTradeOrder());

      TradeOrder tradeOrder1 =
          new TradeOrder(
              this.tradestrategy,
              Action.SELL,
              OrderType.STP,
              quantity,
              price.subtract(new BigDecimal(1)),
              null,
              createDate);

      tradeOrder1.setAuxPrice(price.subtract(new BigDecimal(1)));
      tradeOrder1.setOrderKey((new BigDecimal((Math.random() * 1000000))).intValue());
      tradeOrder1.setClientId(clientId);
      tradeOrder1.setTransmit(true);
      tradeOrder1.setStatus("SUBMITTED");
      tradeOrder1.validate();
      tradeOrder1 = tradeOrderHome.persist(tradeOrder1);
      assertNotNull("2", tradeOrder1);
    } catch (Exception | AssertionError ex) {
      String msg = "Error running " + name.getMethodName() + " msg: " + ex.getMessage();
      _log.error(msg);
      fail(msg);
    }
  }
  @Before
  public void createMockKeyValues() throws Exception {
    // Make a MockInstance here, by setting the instance name to be the same as this mock instance
    // we can "trick" the InputFormat into using a MockInstance
    mockInstance = new MockInstance(test.getMethodName());
    inputformat = new HiveAccumuloTableInputFormat();
    conf = new JobConf();
    conf.set(AccumuloSerDeParameters.TABLE_NAME, TEST_TABLE);
    conf.set(AccumuloSerDeParameters.USE_MOCK_INSTANCE, "true");
    conf.set(AccumuloSerDeParameters.INSTANCE_NAME, test.getMethodName());
    conf.set(AccumuloSerDeParameters.USER_NAME, USER);
    conf.set(AccumuloSerDeParameters.USER_PASS, PASS);
    conf.set(AccumuloSerDeParameters.ZOOKEEPERS, "localhost:2181"); // not used for mock, but
    // required by input format.

    columnNames = Arrays.asList("name", "sid", "dgrs", "mills");
    columnTypes =
        Arrays.<TypeInfo>asList(
            TypeInfoFactory.stringTypeInfo,
            TypeInfoFactory.intTypeInfo,
            TypeInfoFactory.doubleTypeInfo,
            TypeInfoFactory.longTypeInfo);
    conf.set(AccumuloSerDeParameters.COLUMN_MAPPINGS, "cf:name,cf:sid,cf:dgrs,cf:mills");
    conf.set(serdeConstants.LIST_COLUMNS, "name,sid,dgrs,mills");
    conf.set(serdeConstants.LIST_COLUMN_TYPES, "string,int,double,bigint");

    con = mockInstance.getConnector(USER, new PasswordToken(PASS.getBytes()));
    con.tableOperations().create(TEST_TABLE);
    con.securityOperations().changeUserAuthorizations(USER, new Authorizations("blah"));
    BatchWriterConfig writerConf = new BatchWriterConfig();
    BatchWriter writer = con.createBatchWriter(TEST_TABLE, writerConf);

    Mutation m1 = new Mutation(new Text("r1"));
    m1.put(COLUMN_FAMILY, NAME, new Value("brian".getBytes()));
    m1.put(COLUMN_FAMILY, SID, new Value(parseIntBytes("1")));
    m1.put(COLUMN_FAMILY, DEGREES, new Value(parseDoubleBytes("44.5")));
    m1.put(COLUMN_FAMILY, MILLIS, new Value(parseLongBytes("555")));

    Mutation m2 = new Mutation(new Text("r2"));
    m2.put(COLUMN_FAMILY, NAME, new Value("mark".getBytes()));
    m2.put(COLUMN_FAMILY, SID, new Value(parseIntBytes("2")));
    m2.put(COLUMN_FAMILY, DEGREES, new Value(parseDoubleBytes("55.5")));
    m2.put(COLUMN_FAMILY, MILLIS, new Value(parseLongBytes("666")));

    Mutation m3 = new Mutation(new Text("r3"));
    m3.put(COLUMN_FAMILY, NAME, new Value("dennis".getBytes()));
    m3.put(COLUMN_FAMILY, SID, new Value(parseIntBytes("3")));
    m3.put(COLUMN_FAMILY, DEGREES, new Value(parseDoubleBytes("65.5")));
    m3.put(COLUMN_FAMILY, MILLIS, new Value(parseLongBytes("777")));

    writer.addMutation(m1);
    writer.addMutation(m2);
    writer.addMutation(m3);

    writer.close();
  }
Exemplo n.º 4
0
  @Before
  public void setup() {
    System.out.println("\n\n #### SETUP: " + name.getMethodName() + " #### \n\n");
    passwordManager = new MemoryPasswordManager();
    factory = new HttpFactory(passwordManager);
    System.out.println("\n\n #### START: " + name.getMethodName() + " #### \n\n");

    String buildDir = System.getProperty("project.build.directory", "target");

    downloadDir = Paths.get(buildDir, "downloads", name.getMethodName()).toFile();
    downloadDir.mkdirs();
  }
Exemplo n.º 5
0
  /** @throws java.lang.Exception */
  @After
  public void tearDown() throws Exception {
    try {
      conn.rollback();
    } finally {
      try (final Statement deleteTable = conn.createStatement(); ) {
        deleteTable.executeUpdate("DROP TABLE " + tableString);
      } catch (SQLException e) {
        assertEquals(
            "'DROP TABLE' cannot be performed on 'TESTTABLE' because it does not exist.",
            e.getMessage());
      } finally {
        try {
          conn.close();
        } finally {
          try {
            // Shutdown embedded Apache Derby:
            // https://db.apache.org/derby/papers/DerbyTut/embedded_intro.html
            DriverManager.getConnection(
                "jdbc:derby:" + testName.getMethodName() + ";shutdown=true");
            fail(
                "Did not find expected exception when shutting down Derby instance for test: "
                    + testName.getMethodName());
          } catch (SQLException e) {
            System.out.println(e.getMessage());
            assertEquals("Database '" + testName.getMethodName() + "' shutdown.", e.getMessage());
          } finally {
            Files.walkFileTree(
                testDir,
                new SimpleFileVisitor<Path>() {
                  @Override
                  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                      throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                  }

                  @Override
                  public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                      throws IOException {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                  }
                });
          }
        }
      }
    }
  }
Exemplo n.º 6
0
  /** @throws java.lang.Exception */
  @Before
  public void setUp() throws Exception {
    // Create embedded Apache Derby:
    // https://db.apache.org/derby/papers/DerbyTut/embedded_intro.html
    System.out.println("Creating Derby database instance for test: " + testName.getMethodName());

    testDir = tempDir.newFolder(testName.getMethodName()).toPath();

    System.setProperty("derby.system.home", testDir.toAbsolutePath().toString());

    databaseConnectionString = "jdbc:derby:" + testName.getMethodName();
    conn = DriverManager.getConnection(databaseConnectionString + ";create=true");

    tableString = "testTable";
  }
  @Before
  public void before() throws IOException {
    System.setProperty("Throttler.maxEventsPreSecond", "1");
    serverAssetTree = new VanillaAssetTree().forTesting();

    methodName(name.getMethodName());
    final String hostPort =
        "ThrottledKeySubscriptionEventTest." + name.getMethodName() + ".host.port";
    TCPRegistry.createServerSocketChannelFor(hostPort);

    serverEndpoint = new ServerEndpoint(hostPort, serverAssetTree, WIRE_TYPE);
    assetTree = new VanillaAssetTree().forRemoteAccess(hostPort, WIRE_TYPE);

    map = assetTree.acquireMap(NAME, String.class, String.class);
  }
Exemplo n.º 8
0
 @Test
 public void select_2() throws IOException {
   Set<String> vars = extractVars(loadQuery(testName.getMethodName()));
   Assert.assertTrue(vars.contains("?description"));
   Assert.assertTrue(vars.contains("?thing"));
   Assert.assertTrue(vars.contains("?_term"));
 }
Exemplo n.º 9
0
 @Test
 public void select_1() throws IOException {
   Set<String> vars = extractVars(loadQuery(testName.getMethodName()));
   Assert.assertTrue(vars.contains("?course"));
   Assert.assertTrue(vars.contains("?location"));
   Assert.assertTrue(vars.contains("?_geoid"));
 }
  @Test
  public void repositoryCreatedFromScannedDataDirRules() throws Exception {
    final URL u =
        Thread.currentThread()
            .getContextClassLoader()
            .getResource("data/autoprox/simple-factory.groovy");
    final File f = new File(u.getPath());

    final File scriptFile = new File(autoproxDataDir, f.getName());
    FileUtils.copyFile(f, scriptFile);

    System.out.println("Parsing rules for: " + name.getMethodName());
    catalog.parseRules();

    final String testUrl = http.formatUrl("target", "test");

    logger.info("\n\nSETTING UP / VERIFYING REMOTE SERVER EXPECTATIONS");
    http.get(testUrl, 404);
    http.expect(testUrl, 200);
    //        targetResponder.approveTargets( "test" );
    http.get(testUrl, 200);
    logger.info("DONE: SETTING UP / VERIFYING REMOTE SERVER EXPECTATIONS\n\n");

    catalog.setEnabled(false);
    assertThat(proxyManager.getRemoteRepository("test"), nullValue());
    catalog.setEnabled(true);

    final RemoteRepository repo = proxyManager.getRemoteRepository("test");

    assertThat(repo, notNullValue());
    assertThat(repo.getName(), equalTo("test"));
    assertThat(repo.getUrl(), equalTo(testUrl));
  }
  @Test
  public void repositoryNOTCreatedFromScannedDataDirRulesWhenNameNotTest() throws Exception {
    final URL u =
        Thread.currentThread()
            .getContextClassLoader()
            .getResource("data/autoprox/simple-factory.groovy");
    final File f = new File(u.getPath());
    final File scriptFile = new File(autoproxDataDir, f.getName());
    FileUtils.copyFile(f, scriptFile);

    System.out.println("Parsing rules for: " + name.getMethodName());
    catalog.parseRules();

    final String testUrl = http.formatUrl("target", "test");
    http.get(testUrl, 404);
    http.expect(testUrl, 200);
    //        targetResponder.approveTargets( "test" );
    http.get(testUrl, 200);

    catalog.setEnabled(false);
    assertThat(proxyManager.getRemoteRepository("foo"), nullValue());
    catalog.setEnabled(true);

    final RemoteRepository repo = proxyManager.getRemoteRepository("foo");

    assertThat(repo, nullValue());
  }
  @Test
  public void testContainerAssignmentOfMultipleFiles() {
    System.out.println(Constants.TESTCASE_LIMITER);
    System.out.println(this.getClass().getSimpleName() + ": " + name.getMethodName());
    int id1 = 1001;
    int id2 = 1002;
    int id3 = 2000;
    int shareRelationID = 4444;
    // Create FileInfo
    FileInfoEncrypt textFileInfo1 =
        new FileInfoEncrypt(id1, textFile.getAbsolutePath(), shareRelationID);
    FileInfoEncrypt textFileInfo2 =
        new FileInfoEncrypt(id2, textFile.getAbsolutePath(), shareRelationID);
    FileInfoEncrypt textFileInfoBigger =
        new FileInfoEncrypt(id3, textFileBigger.getAbsolutePath(), shareRelationID);

    // create FileInfoList
    List<FileInfoEncrypt> fileInfoList = new ArrayList<FileInfoEncrypt>();
    fileInfoList.add(textFileInfo1);
    fileInfoList.add(textFileInfo2);
    fileInfoList.add(textFileInfoBigger);

    // set Max Container Size
    containerManager.setMaxContainerSize(textFile.length() * 2 + 1);

    // get the gerated File Infos
    containerManager.assignContainerID(fileInfoList);

    assertFalse(fileInfoList.isEmpty()); // not Empty

    // check if both textfiles are in the same container
    assertTrue(
        fileInfoList.get(fileInfoList.indexOf(textFileInfo1)).getContainerInfo().getContainerID()
            == fileInfoList
                .get(fileInfoList.indexOf(textFileInfo2))
                .getContainerInfo()
                .getContainerID());
    // Check Size of these container
    assertTrue(
        fileInfoList
                .get(fileInfoList.indexOf(textFileInfo1))
                .getContainerInfo()
                .getEstimatedContainerSize()
            == (textFile.length() * 2));

    // check if the Bigger File is in another container
    assertFalse(
        fileInfoList.get(fileInfoList.indexOf(textFileInfo1)).getContainerInfo().getContainerID()
            == fileInfoList
                .get(fileInfoList.indexOf(textFileInfoBigger))
                .getContainerInfo()
                .getContainerID());
    // Check Size of this container
    assertTrue(
        fileInfoList
                .get(fileInfoList.indexOf(textFileInfoBigger))
                .getContainerInfo()
                .getEstimatedContainerSize()
            == textFileBigger.length());
  }
  @Test
  public void testExistingContainerID() {
    System.out.println(Constants.TESTCASE_LIMITER);
    System.out.println(this.getClass().getSimpleName() + ": " + name.getMethodName());
    int id = 2222;
    int shareRelationID = 4444;
    int contId = 9999;
    // Create FileInfo
    FileInfoEncrypt fie = new FileInfoEncrypt(id, textFile.getAbsolutePath(), shareRelationID);
    fie.getContainerInfo().setContainerID(contId);

    List<FileInfoEncrypt> fileInfoList = new ArrayList<FileInfoEncrypt>();
    fileInfoList.add(fie);
    // get the gerated File Infos
    containerManager.assignContainerID(fileInfoList);
    assertFalse(fileInfoList.isEmpty()); // not Empty
    // check Container ID
    assertTrue(fileInfoList.get(0).getContainerInfo().getContainerID() == contId);
    // Check Path
    assertEquals(
        fie.getContainerInfo().getShareRelationID(),
        fileInfoList.get(0).getContainerInfo().getShareRelationID());
    // Check Size
    // assertTrue(fileInfoList.get(0).getContainerInfo().getEstimatedContainerSize() ==
    // textFile.length());
  }
 @Test
 public void E_FillFormEducationAndEmploymentSectionComplete() throws InterruptedException {
   Step3_EducationaAndEmployment_PageObjects FormEducationAndEmploymentSection =
       PageFactory.initElements(driver, Step3_EducationaAndEmployment_PageObjects.class);
   TcaseName.add(name.getMethodName());
   Results.add(FormEducationAndEmploymentSection.FillFormStandard());
 }
 @Test
 public void F_FillFormExtraCurrAndForeignExpSectionComplete() throws InterruptedException {
   Step4_ExtraCurrAndForeignExp_PageObjects FormExtraCurrAndForeignExpSection =
       PageFactory.initElements(driver, Step4_ExtraCurrAndForeignExp_PageObjects.class);
   TcaseName.add(name.getMethodName());
   Results.add(FormExtraCurrAndForeignExpSection.FillFormStandard());
 }
 /**
  * Tests that the details of cargo with tracking Id DEF789 can be viewed through the admin
  * interface.
  */
 @Test
 @RunAsClient
 public void testViewDetailsId4() {
   log.log(
       Level.INFO,
       "Starting automated test to view details for Id \""
           + trackingId4
           + "\" through admin interface.");
   try {
     System.out.println(landingPageResponse.getUrl());
     // Stores the adminDashboard as a HtmlPage object.
     HtmlPage adminDashboard = landingPageResponse.getElementById("adminLandingLink").click();
     Assert.assertThat(
         "Page title was not as expected for the admin dashboard. Expected \"Cargo Dashboard\" but actual was \""
             + adminDashboard.getTitleText()
             + "\".",
         adminDashboard.getTitleText(),
         is("Cargo Dashboard"));
     // Stores the details page as a HtmlPage object.
     HtmlPage detailsPage = adminDashboard.getAnchorByText(trackingId4).click();
     Assert.assertTrue(
         "Expected \"Not routed\" message was not found.",
         detailsPage.asText().contains("Not routed"));
   } catch (IOException ex) {
     Assert.fail(
         "An IOException was thrown during the test for class \""
             + ViewDetailTest.class.getSimpleName()
             + "\" at method \""
             + testName.getMethodName()
             + "\" with message: "
             + ex.getMessage());
   }
 }
 @Before
 public void before() {
   storeDir =
       TargetDirectory.forTest(getClass())
           .directory(testName.getMethodName(), true)
           .getAbsolutePath();
 }
Exemplo n.º 18
0
  @Test
  @Category(UnitTest.class)
  public void writeSplitsPath() throws IOException {
    Splits splits = new PartitionerSplit();
    splits.generateSplits(new TestGenerator());

    File splitfile = folder.newFolder(testName.getMethodName());

    splits.writeSplits(new Path(splitfile.toURI()));

    FileInputStream in = new FileInputStream(new File(splitfile, "partitions"));
    Scanner reader = new Scanner(in);

    Assert.assertEquals("Wrong number written", generated.length, reader.nextInt());

    PartitionerSplit.PartitionerSplitInfo[] si =
        (PartitionerSplit.PartitionerSplitInfo[]) splits.getSplits();

    for (int i = 0; i < generated.length; i++) {
      Assert.assertEquals("Splits entry not correct", generated[i].longValue(), reader.nextLong());
      Assert.assertEquals("Partition entry not correct", i, reader.nextLong());
    }

    reader.close();
  }
Exemplo n.º 19
0
 @Before
 public void setUp() throws Exception {
   LOGGER.info("Testing : {}", name.getMethodName());
   cacheService = getCacheService();
   cacheService.clearAll();
   cacheService.start();
 }
Exemplo n.º 20
0
  @Test
  @Category(UnitTest.class)
  public void readSplitsPath() throws IOException {
    File splitFolder = folder.newFolder(testName.getMethodName());
    File splitfile = new File(splitFolder, "partitions");

    FileOutputStream stream = new FileOutputStream(splitfile);
    PrintWriter writer = new PrintWriter(stream);

    writer.println(generated.length);
    for (int i = 0; i < generated.length; i++) {
      writer.print(generated[i]);
      writer.print(" ");
      writer.println(i);
    }

    writer.close();
    stream.close();

    Splits splits = new PartitionerSplit();
    splits.readSplits(new Path(splitFolder.toURI()));

    PartitionerSplit.PartitionerSplitInfo[] si =
        (PartitionerSplit.PartitionerSplitInfo[]) splits.getSplits();

    Assert.assertEquals("Splits length not correct", generated.length, si.length);
    for (int i = 0; i < generated.length; i++) {
      Assert.assertEquals("Splits entry not correct", generated[i].longValue(), si[i].getTileId());
    }
  }
 @Test
 public void D_FillFormPartnerAndRelationshipSectionComplete() throws InterruptedException {
   Step2_PartnerAndRelationship_PageObjects FormPartnerAndRelationshipSection =
       PageFactory.initElements(driver, Step2_PartnerAndRelationship_PageObjects.class);
   TcaseName.add(name.getMethodName());
   Results.add(FormPartnerAndRelationshipSection.FillFormStandard());
 }
 @Test
 public void C_FillFormFormPersonalSectionComplete() throws InterruptedException {
   Step1_Personal_PageObjects FormPersonalSection =
       PageFactory.initElements(driver, Step1_Personal_PageObjects.class);
   TcaseName.add(name.getMethodName());
   FormPersonalSection.FillFormStandard();
 }
 @Test
 public void H_SubmitFormSection() throws InterruptedException, IOException {
   Step6_ReviewAndSubmit_PageObjects ReviewAndSubmitSection =
       PageFactory.initElements(driver, Step6_ReviewAndSubmit_PageObjects.class);
   TcaseName.add(name.getMethodName());
   Results.add(ReviewAndSubmitSection.ReviewFormStandard(driver, CurrentPath));
 }
 @Test
 public void G_FillFormExtendedResponseSectionComplete() throws InterruptedException {
   Step5_ExtendedResponse_PageObjects FormExtendedResponseSection =
       PageFactory.initElements(driver, Step5_ExtendedResponse_PageObjects.class);
   TcaseName.add(name.getMethodName());
   Results.add(FormExtendedResponseSection.FillFormStandard(driver));
 }
 @Test
 public void testRead139EncodedSize() {
   System.err.printf(
       "Running %s.%s - hex: %s%n", this.getClass().getName(), testname.getMethodName(), rawhex);
   ByteBuffer bbuf = ByteBuffer.wrap(buf);
   long actual = parser.read139EncodedSize(bbuf);
   Assert.assertThat("1/3/9 size from buffer [" + rawhex + "]", actual, is(expected));
 }
Exemplo n.º 26
0
 /**
  * Verify if the default reverse replication agents on author and publish are in place and
  * enabled, before starting the tests
  */
 @Before
 public void verifyDefaultAgents() throws ClientException {
   System.out.println("--- Running " + name.getMethodName());
   if (cloudServiceConfigs == null) {
     cloudServiceConfigs = new ArrayList<String[]>();
     cloudServiceConfigs.add(FACEBOOK_PROPERTY);
     cloudServiceConfigs.add(TWITTER_PROPERTY);
   }
 }
Exemplo n.º 27
0
 @Before
 public void setup() throws IOException {
   TEST_UTIL = HBaseTestingUtility.createLocalHTU();
   CONF = TEST_UTIL.getConfiguration();
   // Disable block cache.
   CONF.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0f);
   dir = TEST_UTIL.getDataTestDir("TestHRegion").toString();
   tableName = TableName.valueOf(name.getMethodName());
 }
 @Before
 public void recordTestName() {
   waitAQuarterSecond();
   logger.info("Recording TestName, @Before method");
   waitAQuarterSecond();
   ThreadContext.push(testName.getMethodName());
   logger.info("TestName:  " + testName);
   waitAQuarterSecond();
   logger.info("Done Recording TestName\n\n");
 }
Exemplo n.º 29
0
  @Before
  public void setUpTest() throws Exception {
    // call super setup
    super.setUp(name.getMethodName());

    // also start helloworld
    DebugBridge.get().runShellCommand("pm clear com.groupon.roboremote.example.helloworld");
    DebugBridge.get()
        .runShellCommand("am start -n com.groupon.roboremote.example.helloworld/.HelloWorld");
  }
 @After
 public void afterTest() {
   IoUtils.safeClose(clientChannel);
   IoUtils.safeClose(serverChannel);
   IoUtils.safeClose(connection);
   serviceRegistration.close();
   System.gc();
   System.runFinalization();
   Logger.getLogger("TEST").infof("Finished test %s", name.getMethodName());
 }