コード例 #1
0
  @Test
  public void testPerformOpeningHandshake() {
    Channel channelMock = EasyMock.createMock(Channel.class);

    DefaultChannelPipeline pipeline = createPipeline(channelMock);
    EasyMock.expect(channelMock.pipeline()).andReturn(pipeline);

    // capture the http response in order to verify the headers
    Capture<HttpResponse> res = new Capture<HttpResponse>();
    EasyMock.expect(channelMock.write(capture(res)))
        .andReturn(new DefaultChannelFuture(channelMock, true));

    replay(channelMock);

    HttpRequest req = new DefaultHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat");
    req.setHeader(Names.HOST, "server.example.com");
    req.setHeader(Names.UPGRADE, WEBSOCKET.toLowerCase());
    req.setHeader(Names.CONNECTION, "Upgrade");
    req.setHeader(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.setHeader(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
    req.setHeader(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
    req.setHeader(Names.SEC_WEBSOCKET_VERSION, "13");
    WebSocketServerHandshaker13 handsaker =
        new WebSocketServerHandshaker13("ws://example.com/chat", "chat", false, Integer.MAX_VALUE);
    handsaker.handshake(channelMock, req);

    Assert.assertEquals(
        "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.getValue().getHeader(Names.SEC_WEBSOCKET_ACCEPT));
    Assert.assertEquals("chat", res.getValue().getHeader(Names.SEC_WEBSOCKET_PROTOCOL));
  }
コード例 #2
0
  @Test
  public void uitloggen() {
    HttpSession httpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(servletRequest.getSession()).andReturn(httpSession).times(2);
    EasyMock.expect(httpSession.getId()).andReturn("a").times(2);
    EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("adr").times(2);
    EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent");

    Medewerker medewerker = new Medewerker();
    medewerker.setId(46L);

    Sessie sessie = new Sessie();
    sessie.setGebruiker(medewerker);
    sessie.setIpadres("adr");
    sessie.setSessie("a");
    medewerker.getSessies().add(sessie);

    try {
      EasyMock.expect(gebruikerRepository.zoekOpSessieEnIpadres("a", "adr")).andReturn(medewerker);
    } catch (NietGevondenException e1) {
    }

    gebruikerRepository.opslaan(medewerker);
    EasyMock.expectLastCall();

    replayAll();
    EasyMock.replay(httpSession);

    gebruikerService.uitloggen(servletRequest);

    verifyAll();
    EasyMock.verify(httpSession);
  }
コード例 #3
0
  public void testShouldBuildJiraOkUsingElementAndFixVersionsWithMoreThanOneFixVersion() {
    Element e = createClassMock(Element.class);
    List<JiraVersion> fixVersions = createInterfaceMock(List.class);

    setupMockActualsForElement(e, "LLU-1", "Blah", "BlahStatus", "BlahResolution", "BlahType");
    EasyMock.expect(fixVersions.get(0)).andReturn(TestObjects.Version_10);
    EasyMock.expect(fixVersions.size()).andReturn(2);

    replay();

    JiraIssue jira = jiraBuilder.buildJira(e, fixVersions);

    verify();

    assertJiraDetails(
        jira,
        "LLU-1",
        "Blah",
        "BlahStatus",
        "BlahResolution",
        "BlahType",
        new JiraVersion[] {TestObjects.Version_10});
    assertEquals(1, jira.getFixVersions().size());
    assertEquals(TestObjects.Version_10, jira.getFixVersions().get(0));
    assertEquals(null, jira.getBuildNo());
  }
コード例 #4
0
  @Test
  public void testExpandMailbox() throws Exception {
    int customerID = m_user.getCustomerID();
    int userID = m_user.getUserID();
    String maildir = m_user.getMailDir();
    long messageId = 7890;

    EasyMock.reset(m_mockStoreManager);
    executeRequest(
        500, "uid", -1, "pid", 1, "cid", customerID, "mid", messageId, "private", "true");

    EasyMock.reset(m_mockStoreManager);
    EasyMock.expect(m_mockStoreManager.expandMessageToMeta(customerID, maildir, messageId, 1, true))
        .andReturn(true);
    executeRequest(200, "pid", 1, "uid", userID, "mid", messageId, "sender", "true");

    EasyMock.reset(m_mockStoreManager);
    EasyMock.expect(
            m_mockStoreManager.expandMessageToMeta(customerID, maildir, messageId, 1, false))
        .andReturn(true);
    executeRequest(
        200, "pid", 1, "cid", customerID, "uid", userID, "mid", messageId, "sender", "false");

    EasyMock.reset(m_mockStoreManager);
    EasyMock.expect(
            m_mockStoreManager.expandMessageToMeta(customerID, maildir, messageId, 1, false))
        .andReturn(false);
    executeRequest(
        500, "pid", 1, "cid", customerID, "uid", userID, "mid", messageId, "sender", "false");
  }
  public void testGetAssetsZipFileBadAssets() throws Exception {
    String userId = "1";
    long projectId = 2;
    byte[] data = {0};
    List<String> sourceFiles = new ArrayList<String>();
    sourceFiles.add("assets/badkitty.png");
    sourceFiles.add("assets/meow.mp3");
    sourceFiles.add("src/appinventor/ai_user/HelloPurr/Screen1.blk");
    sourceFiles.add("src/appinventor/ai_user/HelloPurr/Screen1.scm");
    sourceFiles.add("youngandroidproject/project.properties");

    EasyMock.expect(storageIo.getProjectSourceFiles(userId, projectId)).andReturn(sourceFiles);
    EasyMock.expect(
            storageIo.downloadRawFile(
                EasyMock.eq(userId), EasyMock.eq(projectId), EasyMock.eq("assets/badkitty.png")))
        .andThrow(new RuntimeException());
    EasyMock.expect(
            storageIo.downloadRawFile(
                EasyMock.eq(userId), EasyMock.eq(projectId), EasyMock.eq("assets/meow.mp3")))
        .andReturn(data);

    control.replay();

    List<String> zipEntries = getZipEntries(yaWebStart.getAssetsZipFile(userId, projectId));
    ListAssert.assertContains(zipEntries, "assets/meow.mp3");
    ListAssert.assertContains(zipEntries, "badassets/badkitty.png");
  }
コード例 #6
0
  @BeforeMethod(groups = "unit")
  public void init() {
    factory = new RawExtractJobFactoryImpl();
    stagingDirectoryFactory = EasyMock.createMock(CredentialedStagingDirectoryFactory.class);
    stagingDirectory = EasyMock.createMock(StagingDirectory.class);
    EasyMock.expect(stagingDirectory.getAbsolutePath()).andStubReturn(PATH);

    EasyMock.expect(stagingDirectory.getSep()).andStubReturn("/");
    final Supplier<DisposableResourceTracker> trackerSupplier = EasyMockUtils.createMockSupplier();
    tracker = createMock(DisposableResourceTracker.class);
    expect(trackerSupplier.get()).andReturn(tracker);
    replay(trackerSupplier);
    rawPopulator = EasyMock.createMock(InputContext.class);

    converter = EasyMock.createMock(DTAToMzXMLConverter.class);
    options = new DTAToMzXMLOptions();

    factory.setDtaToMzXMLConverter(converter);
    factory.setDtaToMxXMLOptions(options);
    factory.setDisposableResourceTrackerSupplier(trackerSupplier);
    factory.setCredentialedStagingDirectoryFactory(stagingDirectoryFactory);
    mockObjects =
        MockObjectCollection.fromObjects(
            stagingDirectoryFactory, stagingDirectory, tracker, rawPopulator, converter);
  }
  @Test
  public void testForNonUniqueGroupedCodeListExistingMatch() throws Exception {
    String name = "TestCodeList";
    String catId = "1";
    String steward = "TestSteward";
    //
    // editing a code list so that it matches a different existing code list
    //
    ManageCodeListDetailModel model = new ManageCodeListDetailModel();
    model.setName(name);
    model.setCategory(catId);
    model.setSteward(steward);
    ListObject codeList = new ListObject();

    ListObject existingCl = new ListObject();
    String id = "id";
    model.setID(id);
    model.setExistingCodeList(true);
    existingCl.setId(id);
    EasyMock.expect(listObjectDAO.find(id)).andReturn(codeList);
    EasyMock.expect(
            listObjectDAO.getListObject(name, steward, catId, LoggedInUserUtil.getLoggedInUser()))
        .andReturn(existingCl);
    EasyMock.replay(listObjectDAO);

    assertTrue(codeListService.isGroupedCodeListUnique(model));
  }
コード例 #8
0
  private void prepareMocking() {
    PowerMock.mockStatic(JobCreation.class);
    EasyMock.expect(
            JobCreation.generateProcess(
                EasyMock.isA(ImportObject.class), EasyMock.isA(Process.class)))
        .andReturn(new Process());
    EasyMock.expect(
            JobCreation.generateProcess(
                EasyMock.isA(ImportObject.class), EasyMock.isA(Process.class)))
        .andReturn(new Process());
    EasyMock.expect(
            JobCreation.generateProcess(
                EasyMock.isA(ImportObject.class), EasyMock.isA(Process.class)))
        .andReturn(new Process());
    EasyMock.expect(
            JobCreation.generateProcess(
                EasyMock.isA(ImportObject.class), EasyMock.isA(Process.class)))
        .andReturn(new Process());
    EasyMock.expect(
            JobCreation.generateProcess(
                EasyMock.isA(ImportObject.class), EasyMock.isA(Process.class)))
        .andReturn(null);

    PowerMock.replayAll();
  }
コード例 #9
0
  @Test
  public void testGetDataExceptions() throws Exception {
    EasyMock.expect(uploadResource.getSize()).andStubReturn((long) Long.MAX_VALUE);
    EasyMock.expect(uploadResource.getInputStream()).andStubAnswer(INPUT_STREAM_SUPPLIER);

    environment.getControl().replay();

    try {
      uploadedFile.getData();

      fail();
    } catch (FileUploadException e) {
      // expected - ignore
    }

    environment.getControl().reset();

    EasyMock.expect(uploadResource.getSize()).andStubReturn(1L);
    EasyMock.expect(uploadResource.getInputStream())
        .andStubThrow(new IOException("No stream available"));

    environment.getControl().replay();

    try {
      uploadedFile.getData();

      fail();
    } catch (FileUploadException e) {
      // expected - ignore
      assertTrue(e.getCause() instanceof IOException);
    }
  }
コード例 #10
0
 /** Tests whether an exception is reported to the observer. */
 @Test
 public void testOnException() throws ConcurrentException {
   EntityManager em = EasyMock.createMock(EntityManager.class);
   EntityTransaction tx = EasyMock.createNiceMock(EntityTransaction.class);
   EasyMock.expect(em.getTransaction()).andReturn(tx).anyTimes();
   EasyMock.expect(init.get().createEntityManager()).andReturn(em);
   final RuntimeException err = new RuntimeException("TestException");
   observer.commandExecutionFailed(err);
   EasyMock.replay(em, tx, observer, init.get());
   ObservableCommandTestImpl cmd =
       new ObservableCommandTestImpl(init, observer, em) {
         @Override
         protected String produceResults(EntityManager em) {
           super.produceResults(em);
           throw err;
         }
       };
   try {
     cmd.execute();
     fail("Exception not thrown!");
   } catch (Exception ex) {
     assertEquals("Wrong exception", err, ex);
   }
   cmd.onException(err);
   EasyMock.verify(em, tx, observer, init.get());
 }
コード例 #11
0
 /** Test {@link DeviceSetup#setUp(ITestDevice, IBuildInfo)} when build does not boot */
 public void testSetup_buildError() throws Exception {
   mMockDevice.setRecoveryMode(RecoveryMode.ONLINE);
   mMockFlasher.overrideDeviceOptions(mMockDevice);
   mMockFlasher.setForceSystemFlash(false);
   mMockFlasher.setDataWipeSkipList(Arrays.asList(new String[] {}));
   mMockFlasher.flash(mMockDevice, mMockBuildInfo);
   mMockDevice.waitForDeviceOnline();
   EasyMock.expect(mMockDevice.enableAdbRoot()).andStubReturn(Boolean.TRUE);
   mMockDevice.setDate(null);
   EasyMock.expect(mMockDevice.getBuildId()).andReturn(mMockBuildInfo.getBuildId());
   EasyMock.expect(mMockDevice.getBuildFlavor()).andReturn(mMockBuildInfo.getBuildFlavor());
   EasyMock.expect(mMockDevice.isEncryptionSupported()).andStubReturn(Boolean.TRUE);
   EasyMock.expect(mMockDevice.isDeviceEncrypted()).andStubReturn(Boolean.FALSE);
   mMockDevice.clearLogcat();
   mMockDevice.waitForDeviceAvailable(EasyMock.anyLong());
   EasyMock.expectLastCall().andThrow(new DeviceUnresponsiveException("foo"));
   mMockDevice.setRecoveryMode(RecoveryMode.AVAILABLE);
   EasyMock.replay(mMockFlasher, mMockDevice);
   try {
     mDeviceFlashPreparer.setUp(mMockDevice, mMockBuildInfo);
     fail("DeviceFlashPreparerTest not thrown");
   } catch (BuildError e) {
     // expected; use the general version to make absolutely sure that
     // DeviceFailedToBootError properly masquerades as a BuildError.
     assertTrue(e instanceof DeviceFailedToBootError);
   }
   EasyMock.verify(mMockFlasher, mMockDevice);
 }
コード例 #12
0
  @Test
  @SuppressWarnings("unchecked")
  public void testWithOrdering() throws IOException {
    URL url1 = new URL("file://jar1.jar");
    URL sci1 = new URL("jar:file://jar1.jar!/" + CONFIG_FILE);
    URL url2 = new URL("file://dir/");
    URL sci2 = new URL("file://dir/" + CONFIG_FILE);
    loader =
        EasyMock.createMockBuilder(WebappServiceLoader.class)
            .addMockedMethod("parseConfigFile", LinkedHashSet.class, URL.class)
            .withConstructor(context)
            .createMock(control);
    List<String> jars = Arrays.asList("jar1.jar", "dir/");
    EasyMock.expect(servletContext.getAttribute(ServletContext.ORDERED_LIBS)).andReturn(jars);
    EasyMock.expect(servletContext.getResource("/WEB-INF/lib/jar1.jar")).andReturn(url1);
    loader.parseConfigFile(EasyMock.isA(LinkedHashSet.class), EasyMock.eq(sci1));
    EasyMock.expect(servletContext.getResource("/WEB-INF/lib/dir/")).andReturn(url2);
    loader.parseConfigFile(EasyMock.isA(LinkedHashSet.class), EasyMock.eq(sci2));
    EasyMock.expect(parent.getResources(CONFIG_FILE))
        .andReturn(Collections.<URL>emptyEnumeration());

    control.replay();
    Assert.assertTrue(loader.load(ServletContainerInitializer.class).isEmpty());
    control.verify();
  }
  protected void setUp() throws Exception {
    super.setUp();

    ReflectionFactory reflectionFactory = EasyMock.createNiceMock(ReflectionFactory.class);
    LifecycleInvoker invoker = EasyMock.createMock(LifecycleInvoker.class);
    EasyMock.expect(reflectionFactory.createLifecycleInvoker(EasyMock.isA(Method.class)))
        .andReturn(invoker);

    ClassLoaderRegistry classLoaderRegistry = EasyMock.createMock(ClassLoaderRegistry.class);
    EasyMock.expect(classLoaderRegistry.getClassLoader(EasyMock.anyObject()))
        .andReturn(getClass().getClassLoader())
        .anyTimes();
    EasyMock.replay(reflectionFactory, classLoaderRegistry);

    builder = new ImplementationManagerFactoryBuilderImpl(reflectionFactory, classLoaderRegistry);
    Constructor<Foo> constructor = Foo.class.getConstructor(String.class, Long.class);

    definition = new ImplementationManagerDefinition();
    definition.setImplementationClass(Foo.class);
    definition.setConstructor(constructor);
    definition.setInitMethod(Foo.class.getMethod("init"));
    definition.setDestroyMethod(Foo.class.getMethod("destroy"));
    Map<InjectionSite, Injectable> construction = definition.getConstruction();
    construction.put(
        new ConstructorInjectionSite(constructor, 0), new Injectable(InjectableType.PROPERTY, "a"));
    construction.put(
        new ConstructorInjectionSite(constructor, 1),
        new Injectable(InjectableType.REFERENCE, "b"));
  }
コード例 #14
0
  @Test
  public void installCustomerCase3() {
    PrivateEntity privateEntity = new PrivateEntity(entity, "ALIAS");
    Customer newCustomer = new Customer();

    EasyMock.expect(privateEntityRepository.findByEntityAndEntityAlias(entity, "ALIAS"))
        .andReturn(privateEntity);
    EasyMock.expect(privateEntityRepository.saveAndFlush(privateEntity)).andReturn(privateEntity);
    EasyMock.replay(privateEntityRepository);

    EasyMock.expect(
            cityRepository.findByContextAndCityCode(
                entity.getOperator(), partnerAddress.getCityCode()))
        .andReturn(city);
    EasyMock.replay(cityRepository);

    Partner customer = new Customer(privateEntity);

    EasyMock.expect(partnerRepository.findByPrivateEntityAndType(privateEntity, 'C'))
        .andReturn(customer);
    expect(partnerRepository.saveAndFlush(EasyMock.isA(Customer.class))).andReturn(newCustomer);
    EasyMock.replay(partnerRepository);

    assertSame(customer, partnerMgr.installCustomer(entity, "NAME", partnerAddress, false));
  }
コード例 #15
0
ファイル: BuckConfigTest.java プロジェクト: highgic/buck
  @Test
  public void testReferentialAliases() throws IOException, NoSuchBuildTargetException {
    BuildTargetParser parser = EasyMock.createMock(BuildTargetParser.class);
    EasyMock.expect(parser.parse("//java/com/example:foo", ParseContext.fullyQualified()))
        .andReturn(BuildTargetFactory.newInstance("//java/com/example:foo"));
    EasyMock.expect(parser.parse("//java/com/example:bar", ParseContext.fullyQualified()))
        .andReturn(BuildTargetFactory.newInstance("//java/com/example:bar"));
    EasyMock.replay(parser);

    Reader reader =
        new StringReader(
            Joiner.on('\n')
                .join(
                    "[alias]",
                    "foo            = //java/com/example:foo",
                    "bar            = //java/com/example:bar",
                    "foo_codename   = foo",
                    "",
                    "# Do not delete these: automation builds require these aliases to exist!",
                    "automation_foo = foo_codename",
                    "automation_bar = bar"));
    BuckConfig config = createWithDefaultFilesystem(reader, parser);
    assertEquals("//java/com/example:foo", config.getBuildTargetForAlias("foo"));
    assertEquals("//java/com/example:bar", config.getBuildTargetForAlias("bar"));
    assertEquals("//java/com/example:foo", config.getBuildTargetForAlias("foo_codename"));
    assertEquals("//java/com/example:foo", config.getBuildTargetForAlias("automation_foo"));
    assertEquals("//java/com/example:bar", config.getBuildTargetForAlias("automation_bar"));
    assertNull(config.getBuildTargetForAlias("baz"));

    EasyMock.verify(parser);
  }
コード例 #16
0
  public static FedoraAccessImpl prepareFedoraAccess(StatisticsAccessLog acLog)
      throws NoSuchMethodException, IOException, ParserConfigurationException, SAXException,
          LexerException {
    FedoraAccessImpl fa33 =
        createMockBuilder(FedoraAccessImpl.class)
            .withConstructor(KConfiguration.getInstance(), acLog)
            .addMockedMethod("getFedoraDescribeStream")
            .addMockedMethod("getRelsExt")
            .addMockedMethod("isImageFULLAvailable")
            .addMockedMethod("getDC")
            .addMockedMethod("getBiblioMods")
            .addMockedMethod(
                FedoraAccessImpl.class.getMethod("getKrameriusModelName", String.class))
            .createMock();

    EasyMock.expect(fa33.getFedoraDescribeStream()).andReturn(DataPrepare.fedoraProfile33());

    DataPrepare.drobnustkyRelsExt(fa33);
    DataPrepare.drobnustkyWithIMGFULL(fa33);
    DataPrepare.drobnustkyDCS(fa33);
    DataPrepare.drobnustkyMODS(fa33);

    Set<String> keySet = DocumentServiceTest.MODELS_MAPPING.keySet();
    for (String key : keySet) {
      String model = DocumentServiceTest.MODELS_MAPPING.get(key);
      PIDParser pidParser = new PIDParser(model);
      pidParser.disseminationURI();
      String modelK4Name = pidParser.getObjectId();
      EasyMock.expect(fa33.getKrameriusModelName(key)).andReturn(modelK4Name).anyTimes();
    }
    return fa33;
  }
コード例 #17
0
  @Test
  public void testConfigurationEventAdded() throws Exception {
    String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "test123";
    Configuration conf = EasyMock.createMock(Configuration.class);
    EasyMock.expect(conf.getPid()).andReturn(testPid).anyTimes();
    EasyMock.replay(conf);

    ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class);
    EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes();
    EasyMock.expect(cm.getConfiguration(testPid)).andReturn(conf).anyTimes();
    EasyMock.replay(cm);

    final List<String> generateCalled = new ArrayList<String>();
    SecuredCommandConfigTransformer scct =
        new SecuredCommandConfigTransformer() {
          @Override
          void generateServiceGuardConfig(Configuration config) throws IOException {
            generateCalled.add(config.getPid());
          }
        };
    scct.setConfigAdmin(cm);
    scct.init();

    @SuppressWarnings("unchecked")
    ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(cmRef);

    ConfigurationEvent event =
        new ConfigurationEvent(cmRef, ConfigurationEvent.CM_UPDATED, null, testPid);

    assertEquals("Precondition", 0, generateCalled.size());
    scct.configurationEvent(event);
    assertEquals(1, generateCalled.size());
    assertEquals(testPid, generateCalled.iterator().next());
  }
コード例 #18
0
  @Before
  public void setUp() throws Exception {
    jmxNodeInfo = new JMXNodeInfo(0);
    jmxCollector = new JMXCollectorImpl();
    platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName objectName = new ObjectName("org.opennms.netmgt.collectd.jmxhelper:type=JmxTest");
    JmxTestMBean testMBean = new JmxTest();
    platformMBeanServer.registerMBean(testMBean, objectName);

    collectionAgent = EasyMock.createMock(CollectionAgent.class);
    EasyMock.expect(collectionAgent.getAddress()).andReturn(InetAddress.getLocalHost()).anyTimes();
    EasyMock.expect(
            collectionAgent.getAttribute("org.opennms.netmgt.collectd.JMXCollector.nodeInfo"))
        .andReturn(jmxNodeInfo)
        .anyTimes();
    EasyMock.expect(collectionAgent.getNodeId()).andReturn(0).anyTimes();
    EasyMock.expect(collectionAgent.getStorageDir()).andReturn(new File("")).anyTimes();

    EasyMock.replay(collectionAgent);

    FileInputStream configFileStream =
        new FileInputStream("src/test/resources/etc/JmxCollectorConfigTest.xml");
    logger.debug("ConfigFileStream check '{}'", configFileStream.available());
    jmxConfigFactory = new JMXDataCollectionConfigFactory(configFileStream);
    JMXDataCollectionConfigFactory.setInstance(jmxConfigFactory);
  }
コード例 #19
0
  @Test
  public void testSetIsInFields_first_ok_second_null_isInAlreadyFilled() {
    OpenStreetMapSimpleImporter openStreetMapSimpleImporter = new OpenStreetMapSimpleImporter();

    final String cityName = "cityName";
    final Integer population = 123;
    final String adm2name = "adm2name";
    final City city = new City();
    city.setPopulation(population);
    city.setAdm2Name(adm2name);
    city.setName(cityName);
    city.setMunicipality(false);
    city.setFeatureId(1L);
    city.setId(123L);
    final Set<ZipCode> zipCodes = new HashSet<ZipCode>();
    zipCodes.add(new ZipCode("zip1"));
    city.addZipCodes(zipCodes);
    Point location = GeolocHelper.createPoint(2F, 3F);

    String countryCode = "FR";

    AlternateName an1 = new AlternateName("an1", AlternateNameSource.OPENSTREETMAP);
    AlternateName an2 = new AlternateName("an2", AlternateNameSource.OPENSTREETMAP);
    city.addAlternateName(an1);
    city.addAlternateName(an2);

    ICityDao cityDao = EasyMock.createMock(ICityDao.class);
    EasyMock.expect(
            cityDao.getByShape(
                EasyMock.anyObject(Point.class),
                EasyMock.anyObject(String.class),
                EasyMock.eq(true)))
        .andReturn(null);
    EasyMock.expect(
            cityDao.getNearest(location, countryCode, true, OpenStreetMapSimpleImporter.DISTANCE))
        .andReturn(city);
    EasyMock.expect(
            cityDao.getNearest(location, countryCode, false, OpenStreetMapSimpleImporter.DISTANCE))
        .andReturn(null);
    EasyMock.replay(cityDao);
    openStreetMapSimpleImporter.setCityDao(cityDao);

    OpenStreetMap street = new OpenStreetMap();
    street.setCountryCode(countryCode);
    street.setLocation(location);
    street.setIsIn("AlreadyFilled");
    street.setCityId(456L);
    openStreetMapSimpleImporter.setIsInFields(street);

    Set<String> expectedZip = new HashSet<String>();
    expectedZip.add("ZIP1");
    Assert.assertEquals(expectedZip, street.getIsInZip());
    Assert.assertEquals("adm2name", street.getIsInAdm());
    Assert.assertEquals("AlreadyFilled", street.getIsIn());
    Assert.assertEquals(456L, street.getCityId());
    Assert.assertEquals(null, street.getIsInPlace());
    Assert.assertTrue(street.getIsInCityAlternateNames().size() == 2);

    EasyMock.verify(cityDao);
  }
コード例 #20
0
  @Before
  public void setUp() {
    logger = new ByteArrayOutputStream();

    kpPairs = new ArrayList<GlobalKeepassPair>();
    URL url = getClass().getResource("/TestDB.kdbx");
    kpPairs.add(new GlobalKeepassPair(url.getPath(), MASTER_PASS));

    vpList = new ArrayList<VarPasswordPair>();

    config =
        EasyMock.createMockBuilder(MaskPasswordsConfig.class)
            .addMockedMethod("getGlobalVarPasswordPairs")
            .addMockedMethod("getGlobalKeepassLocations")
            .addMockedMethod("isMasked")
            .createMock();
    wrapper =
        EasyMock.createMockBuilder(MaskPasswordsBuildWrapper.class)
            .addMockedMethod("getConfig")
            .createMock();

    EasyMock.expect(config.getGlobalKeepassLocations()).andReturn(kpPairs);
    EasyMock.expect(config.getGlobalVarPasswordPairs()).andReturn(vpList);
    EasyMock.expect(config.isMasked(EasyMock.anyString())).andReturn(true).anyTimes();
    EasyMock.replay(config);
    EasyMock.expect(wrapper.getConfig()).andReturn(config).anyTimes();
    EasyMock.replay(wrapper);

    build = EasyMock.createMock(AbstractBuild.class);
    EasyMock.expect(build.getAction(ParametersAction.class)).andReturn(null);
    EasyMock.replay(build);
  }
コード例 #21
0
  @SuppressWarnings("unchecked")
  @Test
  public void testRpcException() {
    Logger logger = EasyMock.createMock(Logger.class);
    RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234);
    RpcException exception = new RpcException("TestRpcException");
    logger.error(
        EasyMock.eq(
            "Got unchecked and undeclared exception which called by 127.0.0.1. service: "
                + DemoService.class.getName()
                + ", method: sayHello, exception: "
                + RpcException.class.getName()
                + ": TestRpcException"),
        EasyMock.eq(exception));
    ExceptionFilter exceptionFilter = new ExceptionFilter(logger);
    RpcInvocation invocation =
        new RpcInvocation("sayHello", new Class<?>[] {String.class}, new Object[] {"world"});
    Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class);
    EasyMock.expect(invoker.invoke(EasyMock.eq(invocation))).andThrow(exception);

    EasyMock.replay(logger, invoker);

    try {
      exceptionFilter.invoke(invoker, invocation);
    } catch (RpcException e) {
      assertEquals("TestRpcException", e.getMessage());
    }
    EasyMock.verify(logger, invoker);
    RpcContext.removeContext();
  }
  @Test
  public void testStrategy() throws TasteException {
    FastIDSet itemIDsFromUser123 = new FastIDSet();
    itemIDsFromUser123.add(1L);

    FastIDSet itemIDsFromUser456 = new FastIDSet();
    itemIDsFromUser456.add(1L);
    itemIDsFromUser456.add(2L);

    List<Preference> prefs = new ArrayList<Preference>();
    prefs.add(new GenericPreference(123L, 1L, 1.0f));
    prefs.add(new GenericPreference(456L, 1L, 1.0f));
    PreferenceArray preferencesForItem1 = new GenericItemPreferenceArray(prefs);

    DataModel dataModel = EasyMock.createMock(DataModel.class);
    EasyMock.expect(dataModel.getPreferencesForItem(1L)).andReturn(preferencesForItem1);
    EasyMock.expect(dataModel.getItemIDsFromUser(123L)).andReturn(itemIDsFromUser123);
    EasyMock.expect(dataModel.getItemIDsFromUser(456L)).andReturn(itemIDsFromUser456);

    PreferenceArray prefArrayOfUser123 =
        new GenericUserPreferenceArray(Arrays.asList(new GenericPreference(123L, 1L, 1.0f)));

    CandidateItemsStrategy strategy = new PreferredItemsNeighborhoodCandidateItemsStrategy();

    EasyMock.replay(dataModel);

    FastIDSet candidateItems = strategy.getCandidateItems(123L, prefArrayOfUser123, dataModel);
    assertEquals(1, candidateItems.size());
    assertTrue(candidateItems.contains(2L));

    EasyMock.verify(dataModel);
  }
コード例 #23
0
  @Test
  public void testEmptyHostmapUseCase() throws Exception {
    URL configUrl = TestUtils.getResourceUrl(this.getClass(), "empty-hostmap.txt");

    UrlRewriteEnvironment environment = EasyMock.createNiceMock(UrlRewriteEnvironment.class);
    EasyMock.expect(environment.getResource("/WEB-INF/hostmap.txt"))
        .andReturn(configUrl)
        .anyTimes();
    Resolver resolver = EasyMock.createNiceMock(Resolver.class);
    EasyMock.expect(resolver.resolve("host"))
        .andReturn(Arrays.asList("test-inbound-host"))
        .anyTimes();
    EasyMock.replay(environment, resolver);

    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
    UrlRewriteRuleDescriptor rule = descriptor.addRule("test-rule");
    rule.pattern("{*}://{host}:{*}/{**}?{**}");
    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep("rewrite");
    rewrite.template("{*}://{$hostmap(host)}:{*}/{**}?{**}");

    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
    rewriter.initialize(environment, descriptor);

    Template input =
        Parser.parseLiteral(
            "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value");
    Template output = rewriter.rewrite(resolver, input, UrlRewriter.Direction.IN, null);
    // System.out.println( output );
    assertThat(output, notNullValue());
    assertThat(output.getHost().getFirstValue().getPattern(), is("test-inbound-host"));
  }
コード例 #24
0
 @Test
 public void testIteratorInSamePartition() throws Exception {
   EasyMock.expect(
           this.consumer.get(
               this.topic,
               new Partition("0-0"),
               0L,
               this.maxSize,
               this.timeoutInMills,
               TimeUnit.MILLISECONDS))
       .andReturn(new MessageIterator(this.topic, this.createMessageBuffer()))
       .once();
   EasyMock.expect(
           this.consumer.get(
               this.topic,
               new Partition("0-0"),
               25L,
               this.maxSize,
               this.timeoutInMills,
               TimeUnit.MILLISECONDS))
       .andReturn(new MessageIterator(this.topic, this.createMessageBuffer()))
       .once();
   this.control.replay();
   Iterator<Message> it = this.browser.iterator();
   if (it.hasNext()) {
     this.assertMsg(it.next());
   }
   if (it.hasNext()) {
     this.assertMsg(it.next());
   }
   this.control.verify();
   MetaTopicBrowser.Itr mit = (MetaTopicBrowser.Itr) it;
   assertEquals(2, mit.partitions.size());
   assertFalse(mit.partitions.contains(new Partition("0-0")));
 }
コード例 #25
0
  @Test
  public void getIngelogdeGebruiker() {
    HttpSession httpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(servletRequest.getSession()).andReturn(httpSession);
    EasyMock.expect(httpSession.getId()).andReturn("a");
    EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("adr");
    EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent");

    Medewerker medewerker = new Medewerker();
    medewerker.setId(46L);

    Sessie sessie = new Sessie();
    sessie.setGebruiker(medewerker);
    sessie.setIpadres("adr");
    sessie.setSessie("a");
    medewerker.getSessies().add(sessie);

    try {
      EasyMock.expect(gebruikerRepository.zoekOpSessieEnIpadres("a", "adr")).andReturn(medewerker);
    } catch (NietGevondenException e1) {
    }

    replayAll();
    EasyMock.replay(httpSession);

    try {
      assertEquals(medewerker, gebruikerService.getIngelogdeGebruiker(servletRequest));
    } catch (NietIngelogdException e) {
    }

    verifyAll();
    EasyMock.verify(httpSession);
  }
コード例 #26
0
  /** Tests {@link ControllerImpl#saveOrUpdate(Object)}. */
  @Test
  public void saveOrUpdate() {

    final String OTHER_OBJECT = "kkkkk";

    // at first, we test with a persistent object
    EasyMock.expect(dao.isPersistent(OBJECT)).andReturn(true);
    EasyMock.expect(dao.update(OBJECT)).andReturn(OTHER_OBJECT);
    EasyMock.replay(dao);

    String returned = controller.saveOrUpdate(OBJECT);
    EasyMock.verify(dao);

    assert returned == OTHER_OBJECT;

    // at last, we test with a non-persistent object
    EasyMock.reset(dao);

    EasyMock.expect(dao.isPersistent(OBJECT)).andReturn(false);
    dao.save(OBJECT);
    EasyMock.replay(dao);

    returned = controller.saveOrUpdate(OBJECT);
    EasyMock.verify(dao);

    assert returned == OBJECT;
  }
コード例 #27
0
  @Test
  public void inloggenJuist() {
    Medewerker medewerker = new Medewerker();
    medewerker.setIdentificatie("emailadres");
    medewerker.setHashWachtwoord("wachtwoord");

    try {
      EasyMock.expect(gebruikerRepository.zoek("emailadres")).andReturn(medewerker);
    } catch (NietGevondenException e1) {
      fail();
    }

    HttpSession httpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(servletRequest.getSession()).andReturn(httpSession);
    EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("1234").times(2);
    EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent");

    EasyMock.expect(httpSession.getId()).andReturn("234");

    gebruikerRepository.opslaan(medewerker);
    EasyMock.expectLastCall();

    replayAll();

    try {
      gebruikerService.inloggen("emailadres", "wachtwoord", "false", servletRequest);
    } catch (LeegVeldException | NietGevondenException | OnjuistWachtwoordException e) {
      fail(e.getMessage());
    }

    verifyAll();
  }
コード例 #28
0
ファイル: BuckConfigTest.java プロジェクト: highgic/buck
  @Test
  public void testGetBuildTargetForAlias() throws IOException, NoSuchBuildTargetException {
    BuildTargetParser parser = EasyMock.createMock(BuildTargetParser.class);
    EasyMock.expect(parser.parse("//java/com/example:foo", ParseContext.fullyQualified()))
        .andReturn(BuildTargetFactory.newInstance("//java/com/example:foo"));
    EasyMock.expect(parser.parse("//java/com/example:bar", ParseContext.fullyQualified()))
        .andReturn(BuildTargetFactory.newInstance("//java/com/example:bar"));
    EasyMock.replay(parser);

    Reader reader =
        new StringReader(
            Joiner.on('\n')
                .join("[alias]", "foo = //java/com/example:foo", "bar = //java/com/example:bar"));
    BuckConfig config = createWithDefaultFilesystem(reader, parser);
    assertEquals("//java/com/example:foo", config.getBuildTargetForAlias("foo"));
    assertEquals("//java/com/example:bar", config.getBuildTargetForAlias("bar"));
    assertNull(
        "Invalid alias names, such as build targets, should be tolerated by this method.",
        config.getBuildTargetForAlias("//java/com/example:foo"));
    assertNull(config.getBuildTargetForAlias("baz"));

    Reader noAliasesReader = new StringReader("");
    BuckConfig noAliasesConfig = createWithDefaultFilesystem(noAliasesReader, parser);
    assertNull(noAliasesConfig.getBuildTargetForAlias("foo"));
    assertNull(noAliasesConfig.getBuildTargetForAlias("bar"));
    assertNull(noAliasesConfig.getBuildTargetForAlias("baz"));

    EasyMock.verify(parser);
  }
コード例 #29
0
  /** Verify that when adding a second player to a full game, an exception is thrown */
  @Test(expected = SnowmanFullException.class)
  public void addPlayerFullTest() {
    // setup dummy entityfactory
    EntityFactory dummyEntityFactory = EasyMock.createMock(EntityFactory.class);
    SnowmanFlag dummyFlag = EasyMock.createNiceMock(SnowmanFlag.class);
    EasyMock.expect(dummyFlag.getID()).andStubReturn(new Integer(0));
    EasyMock.replay(dummyFlag);
    EasyMock.expect(
            dummyEntityFactory.createSnowmanFlag(
                EasyMock.isA(SnowmanGame.class),
                EasyMock.isA(ETeamColor.class),
                EasyMock.isA(Coordinate.class),
                EasyMock.isA(Coordinate.class)))
        .andStubReturn(dummyFlag);
    EasyMock.replay(dummyEntityFactory);

    // create the players
    SnowmanPlayer dummyPlayer = EasyMock.createMock(SnowmanPlayer.class);
    SnowmanPlayer dummyPlayer2 = EasyMock.createMock(SnowmanPlayer.class);
    SnowmanPlayer dummyPlayer3 = EasyMock.createMock(SnowmanPlayer.class);
    ETeamColor color = ETeamColor.Red;

    // create the game
    SnowmanGame game = new SnowmanGameImpl(gameName, 4, dummyEntityFactory);

    // add the players
    game.addPlayer(dummyPlayer, color);
    game.addPlayer(dummyPlayer2, color);
    game.addPlayer(dummyPlayer3, color);
  }
コード例 #30
0
 /** Tests that Har resources are sorted properly by request time. */
 @Test
 public void sortHarResources() throws Exception {
   HarResource a = EasyMock.createMock(HarResource.class);
   HarResource b = EasyMock.createMock(HarResource.class);
   HarResource c = EasyMock.createMock(HarResource.class);
   HarResource d = EasyMock.createMock(HarResource.class);
   EasyMock.expect(a.getRequestTime()).andReturn(new BigDecimal(1.328670831670000E9)).anyTimes();
   EasyMock.expect(b.getRequestTime()).andReturn(new BigDecimal(1.328670831660000E9)).anyTimes();
   EasyMock.expect(c.getRequestTime()).andReturn(new BigDecimal(1.328670831650000E9)).anyTimes();
   EasyMock.expect(d.getRequestTime()).andReturn(null).anyTimes();
   EasyMock.replay(a, b, c, d);
   HashMap<String, HarResource> map = Maps.newHashMap();
   map.put("1.1", a);
   map.put("2.2", b);
   map.put("3.3", c);
   map.put("4.4", d);
   HarObject har = new HarObject();
   List<Map.Entry<String, HarResource>> list = Lists.newArrayList(map.entrySet());
   har.sortHarResources(list);
   String[] sortedRequestIds = {"4.4", "3.3", "2.2", "1.1"};
   int i = 0;
   for (Map.Entry<String, HarResource> resource : list) {
     assertTrue(resource.getKey().equals(sortedRequestIds[i++]));
   }
   EasyMock.verify(a, b, c, d);
 }