@Before
  public void setup()
      throws NoPeerConnectionException, InvalidProcessStateException, ProcessExecutionException {
    // setup network
    network = NetworkTestUtil.createH2HNetwork(NETWORK_SIZE);
    // create some random user credentials
    userCredentials = H2HJUnitTest.generateRandomCredentials();
    // register and login a user (peer 0)
    uploaderRoot = FileTestUtil.getTempDirectory();
    uploader = network.get(0);
    uploader.getUserManager().createRegisterProcess(userCredentials).execute();
    uploader
        .getUserManager()
        .createLoginProcess(userCredentials, new TestFileAgent(uploaderRoot))
        .execute();

    // other client to verify this
    File downloaderRoot = FileTestUtil.getTempDirectory();
    downloader = network.get(1);
    downloader
        .getUserManager()
        .createLoginProcess(userCredentials, new TestFileAgent(downloaderRoot))
        .execute();

    nodeManager = Mockito.mock(INodeManager.class);
    Mockito.stub(nodeManager.getNode()).toReturn(uploader);
    UserConfig userConfig = Mockito.mock(UserConfig.class);
    Mockito.stub(userConfig.getRootPath()).toReturn(uploaderRoot.toPath());
    fileManager = new FileManager(nodeManager, userConfig);
  }
Пример #2
0
 @Test
 public void testWarnings() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   DQP dqp = Mockito.mock(DQP.class);
   ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>();
   Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage) Mockito.anyObject()))
       .toReturn(results);
   ResultsMessage rm = new ResultsMessage();
   rm.setResults(new List<?>[] {Arrays.asList(1)});
   rm.setWarnings(Arrays.asList(new Throwable()));
   rm.setColumnNames(new String[] {"expr1"});
   rm.setDataTypes(new String[] {"string"});
   results.getResultsReceiver().receiveResults(rm);
   Mockito.stub(conn.getDQP()).toReturn(dqp);
   StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) {
         @Override
         protected java.util.TimeZone getServerTimeZone() throws java.sql.SQLException {
           return null;
         }
       };
   statement.execute("select 'a'");
   assertNotNull(statement.getResultSet());
   SQLWarning warning = statement.getWarnings();
   assertNotNull(warning);
   assertNull(warning.getNextWarning());
 }
 private IWsdlWtpDescriptorContainer mockWsdlContainer(final File rootWsdl) {
   final IWsdlDefinition rootWsdlDef = Mockito.mock(IWsdlDefinition.class);
   Mockito.stub(rootWsdlDef.getFile()).toReturn(rootWsdl);
   final IWsdlWtpDescriptorContainer container = Mockito.mock(IWsdlWtpDescriptorContainer.class);
   Mockito.stub(container.getRootWsdlDefinition()).toReturn(rootWsdlDef);
   return container;
 }
  @Before
  public void beforeEachTest() {
    logger.debug("Before Test");

    dataSource = Mockito.mock(DataSource.class);
    Connection connection = Mockito.mock(Connection.class);
    DatabaseMetaData databaseMetaData = Mockito.mock(DatabaseMetaData.class);
    try {
      Mockito.stub(dataSource.getConnection()).toReturn(connection);
      Mockito.stub(connection.getMetaData()).toReturn(databaseMetaData);
    } catch (Exception e) {
      logger.error("Error Occurred Stubbing Datasource or connection", e);
    }
    transactionManager = new DataSourceTransactionManager();
    transactionManager.setTransactionSynchronization(
        DataSourceTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
    transactionManager = Mockito.spy(transactionManager);
    transactionManager.setDataSource(dataSource);

    MapJobInstanceDao jobInstanceDao = new MapJobInstanceDao();
    MapJobExecutionDao jobExecutionDao = new MapJobExecutionDao();
    MapStepExecutionDao stepExecutionDao = new MapStepExecutionDao();
    MapExecutionContextDao ecDao = new MapExecutionContextDao();

    jobLauncherTestUtils = new JobLauncherTestUtils();
    jobRepository =
        new SimpleJobRepository(jobInstanceDao, jobExecutionDao, stepExecutionDao, ecDao);

    jobLauncherTestUtils.setJobRepository(jobRepository);
    // jobConfig = new ProductJobConfig();
    // jobConfig.setJobRepository(jobRepository);
    executionContext = new ExecutionContext();
  }
Пример #5
0
 private Dispatch<Object> mockDispatch() {
   Dispatch<Object> mockDispatch = Mockito.mock(Dispatch.class);
   Map<String, Object> map = new HashMap<String, Object>();
   map.put(WSConnection.STATUS_CODE, 200);
   Map<String, Object> requestMap = new HashMap<String, Object>();
   Mockito.stub(mockDispatch.getRequestContext()).toReturn(requestMap);
   requestMap.put(MessageContext.HTTP_REQUEST_HEADERS, new LinkedHashMap<String, List<String>>());
   Mockito.stub(mockDispatch.getResponseContext()).toReturn(map);
   return mockDispatch;
 }
Пример #6
0
  @Test
  public void testClearPolicies() {
    DQPWorkContext message = new DQPWorkContext();
    message.setSession(Mockito.mock(SessionMetadata.class));
    Mockito.stub(message.getSession().getVdb()).toReturn(new VDBMetaData());
    Map<String, DataPolicy> map = message.getAllowedDataPolicies();
    map.put("role", Mockito.mock(DataPolicy.class)); // $NON-NLS-1$
    assertFalse(map.isEmpty());

    message.setSession(Mockito.mock(SessionMetadata.class));
    Mockito.stub(message.getSession().getVdb()).toReturn(new VDBMetaData());
    map = message.getAllowedDataPolicies();
    assertTrue(map.isEmpty());
  }
Пример #7
0
  @Test
  public void testStreaming() throws Exception {
    WSExecutionFactory ef = new WSExecutionFactory();
    MetadataFactory mf =
        new MetadataFactory(
            "vdb",
            1,
            "x",
            SystemMetadata.getInstance().getRuntimeTypeMap(),
            new Properties(),
            null);
    ef.getMetadata(mf, null);
    Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP);
    assertEquals(7, p.getParameters().size());

    TransformationMetadata tm =
        RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb");
    RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm);
    WSConnection mockConnection = Mockito.mock(WSConnection.class);
    Dispatch<Object> mockDispatch = mockDispatch();
    DataSource mock = Mockito.mock(DataSource.class);
    ByteArrayInputStream baos = new ByteArrayInputStream(new byte[100]);
    Mockito.stub(mock.getInputStream()).toReturn(baos);
    Mockito.stub(mockDispatch.invoke(Mockito.any(DataSource.class))).toReturn(mock);
    Mockito.stub(
            mockConnection.createDispatch(
                Mockito.any(String.class),
                Mockito.any(String.class),
                Mockito.any(Class.class),
                Mockito.any(Service.Mode.class)))
        .toReturn(mockDispatch);
    CommandBuilder cb = new CommandBuilder(tm);

    Call call = (Call) cb.getCommand("call invokeHttp('GET', null, null, true)");
    BinaryWSProcedureExecution pe =
        new BinaryWSProcedureExecution(
            call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
    pe.execute();
    List<?> result = pe.getOutputParameterValues();

    Blob b = (Blob) result.get(0);
    assertEquals(100, ObjectConverterUtil.convertToByteArray(b.getBinaryStream()).length);
    try {
      ObjectConverterUtil.convertToByteArray(b.getBinaryStream());
      fail();
    } catch (SQLException e) {
      // should only be able to read once
    }
  }
  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    Mockito.stub(mPhotoListManager.getPhotoListFetched()).toReturn(true);

    activityController = Robolectric.buildActivity(PhotosListViewActivity.class);
    subject = activityController.get();
    Mockito.doAnswer(
            new Answer() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                subject.requestPermissionCallback.Granted(1);
                return null;
              }
            })
        .when(mRequestPermissionUtils)
        .requestPermission(
            subject,
            Manifest.permission.ACCESS_FINE_LOCATION,
            subject.requestPermissionCallback,
            Constants.MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    flickrPhotoList =
        new ArrayList<FlickrPhoto>(
            Arrays.asList(new FlickrPhoto("some-photo", "some-small-url", "some-big-url")));
    subject.setFlickrPhotoList(flickrPhotoList);
    activityController.create().start();
  }
  @Before
  public void setUp() throws CoreException {
    MockitoAnnotations.initMocks(this);
    Mockito.stub(env.errorHandler()).toReturn(errHandler);

    testProject = new TestProject();
  }
  @Test
  @Ignore
  public void testGetDogsByOwner() {
    Customer customer1 = new Customer("Martin", "Sakac", "Purkynova 4", "111");
    Customer customer2 = new Customer("Martin", "Haha", "Purkynova 55", "9999");
    Dog dog1 = new Dog("Martin", "doga", new LocalDate(1998, 05, 22), customer1);
    Dog dog2 = new Dog("Martin", "doga", new LocalDate(1998, 05, 22), customer2);
    Dog dog3 = new Dog("Pepan", "doga", new LocalDate(1998, 05, 22), customer2);

    List<Dog> listAll = Arrays.asList(dog1, dog2, dog3);
    List<Dog> listExpected = Arrays.asList(dog2, dog3);

    Mockito.stub(dogDaoImplMock.getDogsByOwner(CustomerConverter.CustomerToCustomerDto(customer2)))
        .toReturn(listExpected);

    List<DogDto> listActual =
        dogService.getDogsByOwner(CustomerConverter.CustomerToCustomerDto(customer2));

    Mockito.verify(dogDaoImplMock)
        .getDogsByOwner(CustomerConverter.CustomerToCustomerDto(customer2));

    for (int i = 0; i < 2; i++) {
      assertDog(listExpected.get(i), listActual.get(i));
    }
  }
  @Test
  public void testCreate() throws Exception {
    String input = "exec native('create;id=pk;type=table;attributes=one,two,three', 'one', 2, 3.0)";

    TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
    Command command = util.parseCommand(input);
    ExecutionContext ec = Mockito.mock(ExecutionContext.class);
    RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
    SalesforceConnection connection = Mockito.mock(SalesforceConnection.class);

    ArgumentCaptor<DataPayload> payloadArgument = ArgumentCaptor.forClass(DataPayload.class);
    Mockito.stub(connection.create(payloadArgument.capture())).toReturn(23);

    DirectQueryExecution execution =
        (DirectQueryExecution) TRANSLATOR.createExecution(command, ec, rm, connection);
    execution.execute();

    Mockito.verify(connection).create(payloadArgument.capture());

    assertEquals("pk", payloadArgument.getValue().getID());
    assertEquals("table", payloadArgument.getValue().getType());
    assertEquals(3, payloadArgument.getValue().getMessageElements().size());

    assertArrayEquals(new Object[] {23}, (Object[]) execution.next().get(0));
  }
Пример #12
0
  @Test
  public void testUpdateArray() throws Exception {
    String sql =
        "update LdapModel.People set userid = 1, vals = ('a','b') where dn = 'x'"; //$NON-NLS-1$

    QueryMetadataInterface metadata = exampleLdap();

    Update query = (Update) getCommand(sql, metadata);

    LDAPExecutionFactory config = new LDAPExecutionFactory();

    LdapContext context = Mockito.mock(LdapContext.class);

    Mockito.stub(context.lookup("")).toReturn(context);

    LDAPUpdateExecution lue = new LDAPUpdateExecution(query, context);

    lue.execute();
    ArgumentCaptor<ModificationItem[]> captor = ArgumentCaptor.forClass(ModificationItem[].class);
    Mockito.verify(context)
        .modifyAttributes(ArgumentCaptor.forClass(String.class).capture(), captor.capture());
    ModificationItem[] modifications = captor.getValue();
    assertEquals(2, modifications.length);
    assertEquals("uid: 1", modifications[0].getAttribute().toString());
    assertEquals("vals: a, b", modifications[1].getAttribute().toString());
  }
Пример #13
0
  @Test
  public void testHeaders() throws Exception {
    WSExecutionFactory ef = new WSExecutionFactory();
    MetadataFactory mf =
        new MetadataFactory(
            "vdb",
            1,
            "x",
            SystemMetadata.getInstance().getRuntimeTypeMap(),
            new Properties(),
            null);
    ef.getMetadata(mf, null);
    Procedure p = mf.getSchema().getProcedure(WSExecutionFactory.INVOKE_HTTP);

    TransformationMetadata tm =
        RealMetadataFactory.createTransformationMetadata(mf.asMetadataStore(), "vdb");
    RuntimeMetadataImpl rm = new RuntimeMetadataImpl(tm);
    WSConnection mockConnection = Mockito.mock(WSConnection.class);
    Dispatch<Object> mockDispatch = mockDispatch();
    DataSource mock = Mockito.mock(DataSource.class);
    ByteArrayInputStream baos = new ByteArrayInputStream(new byte[100]);
    Mockito.stub(mock.getInputStream()).toReturn(baos);
    Mockito.stub(mockDispatch.invoke(Mockito.any(DataSource.class))).toReturn(mock);
    Mockito.stub(
            mockConnection.createDispatch(
                Mockito.any(String.class),
                Mockito.any(String.class),
                Mockito.any(Class.class),
                Mockito.any(Service.Mode.class)))
        .toReturn(mockDispatch);
    CommandBuilder cb = new CommandBuilder(tm);

    Call call =
        (Call)
            cb.getCommand(
                "call invokeHttp('GET', null, null, false, '{\"ContentType\":\"application/json\"}')");
    BinaryWSProcedureExecution pe =
        new BinaryWSProcedureExecution(
            call, rm, Mockito.mock(ExecutionContext.class), ef, mockConnection);
    pe.execute();

    Map<String, List<String>> headers =
        (Map<String, List<String>>)
            mockDispatch.getRequestContext().get(MessageContext.HTTP_REQUEST_HEADERS);
    assertEquals(Arrays.asList("application/json"), headers.get("ContentType"));
  }
Пример #14
0
  @Test
  public void testTime() throws Exception {
    FileConnection connection = Mockito.mock(FileConnection.class);
    Mockito.stub(connection.getFile("names.xls"))
        .toReturn(UnitTestUtil.getTestDataFile("names.xlsx"));

    ArrayList results = helpExecute(commonDDL, connection, "select \"time\" from Sheet1");
    assertEquals("[[10:12:14]]", results.toString());
  }
Пример #15
0
  @Test
  public void testExecutionLimit2() throws Exception {
    FileConnection connection = Mockito.mock(FileConnection.class);
    Mockito.stub(connection.getFile("names.xls"))
        .toReturn(UnitTestUtil.getTestDataFile("names.xls"));

    ArrayList results = helpExecute(commonDDL, connection, "select FirstName from Sheet1 LIMIT 1");
    assertEquals("[[John]]", results.toString());
  }
Пример #16
0
 @SuppressWarnings("unchecked")
 @Test
 public void testTransactionStatementsAsynch() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   Mockito.stub(conn.submitSetAutoCommitTrue(Mockito.anyBoolean()))
       .toReturn((ResultsFuture) ResultsFuture.NULL_FUTURE);
   Properties p = new Properties();
   Mockito.stub(conn.getExecutionProperties()).toReturn(p);
   StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   statement.submitExecute("start transaction", null); // $NON-NLS-1$
   Mockito.verify(conn).setAutoCommit(false);
   statement.submitExecute("commit", null); // $NON-NLS-1$
   Mockito.verify(conn).submitSetAutoCommitTrue(true);
   statement.submitExecute("start transaction", null); // $NON-NLS-1$
   statement.submitExecute("rollback", null); // $NON-NLS-1$
   Mockito.verify(conn).submitSetAutoCommitTrue(false);
 }
Пример #17
0
 @Test
 public void testSetPayloadStatement() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   Properties p = new Properties();
   Mockito.stub(conn.getExecutionProperties()).toReturn(p);
   StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   assertFalse(statement.execute("set payload foo bar")); // $NON-NLS-1$
 }
Пример #18
0
  @Test
  public void testExecutionNE() throws Exception {
    FileConnection connection = Mockito.mock(FileConnection.class);
    Mockito.stub(connection.getFile("names.xls"))
        .toReturn(UnitTestUtil.getTestDataFile("names.xls"));

    ArrayList results =
        helpExecute(commonDDL, connection, "select FirstName from Sheet1 WHERE ROW_ID != 16");
    assertEquals("[[John], [Jane], [Sarah], [Rocky], [Total]]", results.toString());
  }
Пример #19
0
 @Test
 public void testSetAuthorizationStatement() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   Properties p = new Properties();
   Mockito.stub(conn.getExecutionProperties()).toReturn(p);
   StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   assertFalse(statement.execute("set session authorization bar")); // $NON-NLS-1$
   Mockito.verify(conn).changeUser("bar", null);
 }
Пример #20
0
 @Test
 public void testBatchExecution() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   DQP dqp = Mockito.mock(DQP.class);
   ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>();
   Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage) Mockito.anyObject()))
       .toReturn(results);
   ResultsMessage rm = new ResultsMessage();
   rm.setResults(new List<?>[] {Arrays.asList(1), Arrays.asList(2)});
   rm.setUpdateResult(true);
   results.getResultsReceiver().receiveResults(rm);
   Mockito.stub(conn.getDQP()).toReturn(dqp);
   StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   statement.clearBatch(); // previously caused npe
   statement.addBatch("delete from table"); // $NON-NLS-1$
   statement.addBatch("delete from table1"); // $NON-NLS-1$
   assertTrue(Arrays.equals(new int[] {1, 2}, statement.executeBatch()));
 }
Пример #21
0
 @Test
 public void testTimeoutProperty() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   Properties p = new Properties();
   p.setProperty(ExecutionProperties.QUERYTIMEOUT, "2");
   Mockito.stub(conn.getExecutionProperties()).toReturn(p);
   StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   assertEquals(2, statement.getQueryTimeout());
 }
  @Test
  public void testSearch() throws Exception {
    String input =
        "exec native('search;SELECT Account.Id, Account.Type, Account.Name FROM Account')";

    TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
    Command command = util.parseCommand(input);
    ExecutionContext ec = Mockito.mock(ExecutionContext.class);
    RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
    SalesforceConnection connection = Mockito.mock(SalesforceConnection.class);

    QueryResult qr = Mockito.mock(QueryResult.class);
    Mockito.stub(qr.isDone()).toReturn(true);

    ArrayList<SObject> results = new ArrayList<SObject>();
    ArrayList<Object> values = new ArrayList<Object>();

    SObject s = Mockito.mock(SObject.class);
    // Mockito.stub(s.getId()).toReturn("theID");
    Mockito.stub(s.getType()).toReturn("Account");
    results.add(s);

    Element e1 = Mockito.mock(Element.class);
    Mockito.stub(e1.getTextContent()).toReturn("The ID");
    values.add(e1);

    Element e2 = Mockito.mock(Element.class);
    Mockito.stub(e2.getTextContent()).toReturn("The Type");
    values.add(e2);

    Element e3 = Mockito.mock(Element.class);
    Mockito.stub(e3.getTextContent()).toReturn("The Name");
    values.add(e3);

    Mockito.stub(s.getAny()).toReturn(values);
    Mockito.stub(qr.getRecords()).toReturn(results);
    Mockito.stub(
            connection.query(
                "SELECT Account.Id, Account.Type, Account.Name FROM Account", 0, false))
        .toReturn(qr);

    DirectQueryExecution execution =
        (DirectQueryExecution) TRANSLATOR.createExecution(command, ec, rm, connection);
    execution.execute();

    Mockito.verify(connection, Mockito.times(1))
        .query("SELECT Account.Id, Account.Type, Account.Name FROM Account", 0, false);

    assertArrayEquals(
        new Object[] {"The ID", "The Type", "The Name"}, (Object[]) execution.next().get(0));
  }
Пример #23
0
  @Test
  public void testUseJDBC4ColumnNameAndLabelSemantics() throws Exception {
    ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
    Properties p = new Properties();
    p.setProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS, "false");

    Mockito.stub(conn.getExecutionProperties()).toReturn(p);
    StatementImpl statement =
        new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    assertEquals(
        Boolean.FALSE.toString(),
        statement.getExecutionProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS));
  }
Пример #24
0
  @Test
  public void testAnyAuthenticated() {
    DQPWorkContext message = new DQPWorkContext();
    SessionMetadata mock = Mockito.mock(SessionMetadata.class);
    message.setSession(mock);
    VDBMetaData vdb = new VDBMetaData();
    DataPolicyMetadata dpm = new DataPolicyMetadata();
    dpm.setAnyAuthenticated(true);
    vdb.addDataPolicy(dpm);
    Mockito.stub(mock.getVdb()).toReturn(vdb);

    // unauthenticated
    Map<String, DataPolicy> map = message.getAllowedDataPolicies();
    assertEquals(0, map.size());

    // authenticated
    message = new DQPWorkContext();
    Mockito.stub(mock.getSubject()).toReturn(new Subject());
    message.setSession(mock);
    map = message.getAllowedDataPolicies();
    assertEquals(1, map.size());
  }
Пример #25
0
 @Test
 public void testAsynchTimeout() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   final StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   statement.setQueryTimeoutMS(1);
   DQP dqp = Mockito.mock(DQP.class);
   Mockito.stub(statement.getDQP()).toReturn(dqp);
   final AtomicInteger counter = new AtomicInteger();
   Mockito.stub(dqp.cancelRequest(0))
       .toAnswer(
           new Answer<Boolean>() {
             @Override
             public Boolean answer(InvocationOnMock invocation) throws Throwable {
               synchronized (statement) {
                 counter.incrementAndGet();
                 statement.notifyAll();
               }
               return true;
             }
           });
   ResultsFuture<ResultsMessage> future = new ResultsFuture<ResultsMessage>();
   Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage) Mockito.anyObject()))
       .toReturn(future);
   statement.submitExecute("select 'hello world'", null);
   synchronized (statement) {
     while (counter.get() != 1) {
       statement.wait();
     }
   }
   statement.setQueryTimeoutMS(1);
   statement.submitExecute("select 'hello world'", null);
   synchronized (statement) {
     while (counter.get() != 2) {
       statement.wait();
     }
   }
 }
Пример #26
0
 @Test
 public void testTransactionStatements() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   Properties p = new Properties();
   Mockito.stub(conn.getExecutionProperties()).toReturn(p);
   StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   assertFalse(statement.execute("start transaction")); // $NON-NLS-1$
   Mockito.verify(conn).setAutoCommit(false);
   assertFalse(statement.execute("commit")); // $NON-NLS-1$
   Mockito.verify(conn).setAutoCommit(true);
   assertFalse(statement.execute("start transaction")); // $NON-NLS-1$
   assertFalse(statement.execute("rollback")); // $NON-NLS-1$
   Mockito.verify(conn).rollback(false);
 }
  @Test
  public void testGetDog() {
    Dog dog =
        new Dog(
            "Martin",
            "doga",
            new LocalDate(1998, 05, 22),
            new Customer("Martin", "Sakac", "Purkynova 4", "111"));
    dog.setId(1L);

    Mockito.stub(dogDaoImplMock.getDog(Mockito.anyLong())).toReturn(dog);

    DogDto dogActual = dogService.getDogById(1L);
    Mockito.verify(dogDaoImplMock).getDog(1L);
    assertDog(dog, dogActual);
  }
  /**
   * Test method for {@link
   * org.talend.dq.writer.AElementPersistance#saveWithDependencies(org.talend.core.model.properties.Item,
   * orgomg.cwm.objectmodel.core.ModelElement)} .
   *
   * @throws PersistenceException
   */
  @Test
  public void testSaveWithDependenciesAnalysis() throws PersistenceException {
    PowerMockito.mockStatic(ProxyRepositoryFactory.class);
    ProxyRepositoryFactory mockProxyRepositoryFactory =
        PowerMockito.mock(ProxyRepositoryFactory.class);
    when(ProxyRepositoryFactory.getInstance()).thenReturn(mockProxyRepositoryFactory);
    stub(
        method(
            ProxyRepositoryFactory.class,
            "save",
            org.talend.core.model.properties.Item.class,
            boolean.class)); // $NON-NLS-1$

    PowerMockito.mockStatic(IRepositoryFactory.class);
    IRepositoryFactory mockIRepositoryFactory = PowerMockito.mock(IRepositoryFactory.class);
    when(mockProxyRepositoryFactory.getRepositoryFactoryFromProvider())
        .thenReturn(mockIRepositoryFactory);

    PowerMockito.mockStatic(XmiResourceManager.class);
    when(mockIRepositoryFactory.getResourceManager()).thenReturn(new XmiResourceManager());

    AnalysisWriter createAnalysisWrite = ElementWriterFactory.getInstance().createAnalysisWrite();
    Analysis createAnalysis = AnalysisFactory.eINSTANCE.createAnalysis();
    AnalysisResult createAnalysisResult = AnalysisFactory.eINSTANCE.createAnalysisResult();
    AnalysisContext createAnalysisContext = AnalysisFactory.eINSTANCE.createAnalysisContext();
    TDQAnalysisItem analysisItem =
        org.talend.dataquality.properties.PropertiesFactory.eINSTANCE.createTDQAnalysisItem();
    analysisItem.setAnalysis(createAnalysis);
    String anaName = "ana1"; // $NON-NLS-1$
    String exceptedFileName = anaName + "_0.1.ana"; // $NON-NLS-1$
    createAnalysis.setName(anaName);
    createAnalysis.setResults(createAnalysisResult);
    createAnalysis.setContext(createAnalysisContext);

    ReturnCode create = createAnalysisWrite.saveWithDependencies(analysisItem, createAnalysis);
    assertTrue(create.isOk());
    Assert.assertEquals(exceptedFileName, analysisItem.getFilename());

    String anaName2 = "ana2"; // $NON-NLS-1$
    String exceptedFileName2 = anaName2 + "_0.1.ana"; // $NON-NLS-1$
    createAnalysis.setName(anaName2);

    create = createAnalysisWrite.saveWithDependencies(analysisItem, createAnalysis);
    assertTrue(create.isOk());
    Assert.assertEquals(exceptedFileName2, analysisItem.getFilename());
  }
Пример #29
0
  @Test
  public void testExecutionWithDataNumberXLSX() throws Exception {
    String ddl =
        "CREATE FOREIGN TABLE Sheet1 (\n"
            + "	ROW_ID integer OPTIONS (SEARCHABLE 'All_Except_Like', \"teiid_excel:CELL_NUMBER\" 'ROW_ID'),\n"
            + "	column1 string OPTIONS (SEARCHABLE 'Unsearchable', \"teiid_excel:CELL_NUMBER\" '1'),\n"
            + "	column2 string OPTIONS (SEARCHABLE 'Unsearchable', \"teiid_excel:CELL_NUMBER\" '2'),\n"
            + "	column3 string OPTIONS (SEARCHABLE 'Unsearchable', \"teiid_excel:CELL_NUMBER\" '3'),\n"
            + "	CONSTRAINT PK0 PRIMARY KEY(ROW_ID)\n"
            + ") OPTIONS (\"teiid_excel:FILE\" 'names.xlsx', \"teiid_excel:FIRST_DATA_ROW_NUMBER\" '6');";

    FileConnection connection = Mockito.mock(FileConnection.class);
    Mockito.stub(connection.getFile("names.xlsx"))
        .toReturn(UnitTestUtil.getTestDataFile("names.xlsx"));

    ArrayList results = helpExecute(ddl, connection, "select * from Sheet1");
    assertEquals("[[6, Rocky, Dog, 3.0]]", results.toString());
  }
Пример #30
0
  @Test
  public void testExecutionWithDataNumberWithHeaderXLS() throws Exception {
    String ddl =
        "CREATE FOREIGN TABLE Sheet1 (\n"
            + "	ROW_ID integer OPTIONS (SEARCHABLE 'All_Except_Like', \"teiid_excel:CELL_NUMBER\" 'ROW_ID'),\n"
            + "	FirstName string OPTIONS (SEARCHABLE 'Unsearchable', \"teiid_excel:CELL_NUMBER\" '7'),\n"
            + "	LastName string OPTIONS (SEARCHABLE 'Unsearchable', \"teiid_excel:CELL_NUMBER\" '8'),\n"
            + "	Age double OPTIONS (SEARCHABLE 'Unsearchable', \"teiid_excel:CELL_NUMBER\" '9'),\n"
            + "	CONSTRAINT PK0 PRIMARY KEY(ROW_ID)\n"
            + ") OPTIONS (\"teiid_excel:FILE\" 'names.xls', \"teiid_excel:FIRST_DATA_ROW_NUMBER\" '18');";

    FileConnection connection = Mockito.mock(FileConnection.class);
    Mockito.stub(connection.getFile("names.xls"))
        .toReturn(UnitTestUtil.getTestDataFile("names.xls"));

    ArrayList results = helpExecute(ddl, connection, "select * from Sheet1");
    assertEquals("[[18, Rocky, Dog, 3.0], [19, Total, null, 110.0]]", results.toString());
  }