Java Code Examples for org.easymock.EasyMock#createNiceMock()

The following examples show how to use org.easymock.EasyMock#createNiceMock() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XContentTypeOptionsFilterTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultOptionsValue() throws Exception {
  try {
    final String expectedDefaultValue = XContentTypeOptionsFilter.DEFAULT_OPTION_VALUE;

    XContentTypeOptionsFilter filter = new XContentTypeOptionsFilter();
    Properties props = new Properties();
    props.put("xcontent-type.options.enabled", "true");
    filter.init(new TestFilterConfig(props));

    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.replay(request);
    EasyMock.replay(response);

    TestFilterChain chain = new TestFilterChain();
    filter.doFilter(request, response, chain);
    Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled );
    Assert.assertEquals(XContentTypeOptionsFilter.X_CONTENT_TYPE_OPTIONS_HEADER + " value incorrect.",
                        expectedDefaultValue, options);
    Assert.assertEquals(XContentTypeOptionsFilter.X_CONTENT_TYPE_OPTIONS_HEADER + " count incorrect.",
                        1, headers.size());
  } catch (ServletException se) {
    fail("Should NOT have thrown a ServletException.");
  }
}
 
Example 2
Source File: EventListenerSupportTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testGetListeners() {
    final EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);

    VetoableChangeListener[] listeners = listenerSupport.getListeners();
    assertEquals(0, listeners.length);
    assertEquals(VetoableChangeListener.class, listeners.getClass().getComponentType());
    VetoableChangeListener[] empty = listeners;
    //for fun, show that the same empty instance is used 
    assertSame(empty, listenerSupport.getListeners());

    VetoableChangeListener listener1 = EasyMock.createNiceMock(VetoableChangeListener.class);
    listenerSupport.addListener(listener1);
    assertEquals(1, listenerSupport.getListeners().length);
    VetoableChangeListener listener2 = EasyMock.createNiceMock(VetoableChangeListener.class);
    listenerSupport.addListener(listener2);
    assertEquals(2, listenerSupport.getListeners().length);
    listenerSupport.removeListener(listener1);
    assertEquals(1, listenerSupport.getListeners().length);
    listenerSupport.removeListener(listener2);
    assertSame(empty, listenerSupport.getListeners());
}
 
Example 3
Source File: TimelineMetricsFilterTest.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricBlacklisting() throws Exception {

  Configuration metricsConf = new Configuration();
  TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class);
  expect(configuration.getMetricsConf()).andReturn(metricsConf).once();
  replay(configuration);

  metricsConf.set("timeline.metrics.blacklist.file", getTestBlacklistFilePath());
  TimelineMetricsFilter.initializeMetricFilter(configuration);

  TimelineMetric timelineMetric = new TimelineMetric();

  timelineMetric.setMetricName("cpu_system");
  Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric));

  timelineMetric.setMetricName("cpu_idle");
  Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric));
}
 
Example 4
Source File: SwitchCaseIdentityAssertionFilterTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpperPrincipalAndGroups() throws Exception {
  FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
  EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "Upper" ).anyTimes();
  EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "Upper" ).anyTimes();
  EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
  ServletContext context = EasyMock.createNiceMock(ServletContext.class);
  EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
  EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
  EasyMock.replay( config );
  EasyMock.replay( context );

  SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();

  Subject subject = new Subject();
  subject.getPrincipals().add( new PrimaryPrincipal( "[email protected]" ) );
  subject.getPrincipals().add( new GroupPrincipal( "users" ) );
  subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );

  filter.init(config);
  String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
  String[] groups = filter.mapGroupPrincipals(actual, subject);
  assertThat( actual, is( "[email protected]" ) );
  assertThat( groups, is( arrayContainingInAnyOrder( "ADMIN", "USERS" ) ) );

}
 
Example 5
Source File: EditorAPITextPositionTest.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds the ITextEditor mock.
 *
 * @return the ITextEditor mock
 * @see #withLineOffsetLookupAnswer(int, int)
 */
private ITextEditor build() {
  IDocument document = documentBuilder.build();

  IEditorInput editorInput = EasyMock.createNiceMock(IEditorInput.class);
  EasyMock.replay(editorInput);

  IDocumentProvider documentProvider = EasyMock.createNiceMock(IDocumentProvider.class);
  EasyMock.expect(documentProvider.getDocument(editorInput)).andReturn(document).anyTimes();
  EasyMock.replay(documentProvider);

  editor = EasyMock.createNiceMock(ITextEditor.class);
  EasyMock.expect(editor.getDocumentProvider()).andReturn(documentProvider).anyTimes();
  EasyMock.expect(editor.getEditorInput()).andReturn(editorInput).anyTimes();
  EasyMock.replay(editor);

  return editor;
}
 
Example 6
Source File: RenderServiceIntegrationTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setup() throws SQLException {
    restOperations = EasyMock.createNiceMock(RestOperations.class);
    EasyMock.expect(restOperations.postForObject(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class), EasyMock.anyObject(Class.class)))
            .andReturn(VALID_METADATA);
    EasyMock.replay(restOperations);

    //Replace the real restOperations instance with a mock -- otherwise the call for gadget metadata would fail since
    //we don't have a shindig server available to hit.
    ReflectionTestUtils.setField(metadataRepository, "restOperations", restOperations);

    //Setup a mock authenticated user
    final User authUser = new UserImpl(VALID_USER_ID, VALID_USER_NAME);
    AbstractAuthenticationToken auth = EasyMock.createNiceMock(AbstractAuthenticationToken.class);
    EasyMock.expect(auth.getPrincipal()).andReturn(authUser).anyTimes();
    EasyMock.replay(auth);

    SecurityContext context = new SecurityContextImpl();
    context.setAuthentication(auth);
    SecurityContextHolder.setContext(context);
}
 
Example 7
Source File: AlarmFacadeImplTest.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void setup() {
  alarmCache = EasyMock.createNiceMock(AlarmCache.class);
  tagLocationService = EasyMock.createStrictMock(TagLocationService.class);
  OscillationUpdater oscillationUpdater = new OscillationUpdater(alarmCache, new OscillationProperties());
  alarmCacheUpdater = new AlarmCacheUpdaterImpl(alarmCache, oscillationUpdater);
  alarmFacadeImpl = new AlarmFacadeImpl(alarmCache, tagLocationService, alarmCacheUpdater);
}
 
Example 8
Source File: IsisChannelHandlerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    controller = EasyMock.createNiceMock(Controller.class);
    isisProcess = EasyMock.createNiceMock(IsisProcess.class);
    channelHandlerContext = EasyMock.createNiceMock(ChannelHandlerContext.class);
    channelStateEvent = EasyMock.createNiceMock(ChannelStateEvent.class);
    exceptionEvent = EasyMock.createNiceMock(ExceptionEvent.class);
    messageEvent = EasyMock.createNiceMock(MessageEvent.class);
    isisMessage = EasyMock.createNiceMock(L1L2HelloPdu.class);
    isisMessage.setInterfaceIndex(2);
    isisChannelHandler = new IsisChannelHandler(controller, isisProcessList);
}
 
Example 9
Source File: ServiceModelTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnTypeFromMetadataIfMetadataIsSet() throws Exception {
  final ServiceModel serviceModel = new ServiceModel();
  final Metadata metadata = EasyMock.createNiceMock(Metadata.class);
  serviceModel.setServiceMetadata(metadata);
  final ServiceModel.Type type = ServiceModel.Type.API;
  EasyMock.expect(metadata.getType()).andReturn(type.name()).anyTimes();
  EasyMock.replay(metadata);
  assertEquals(type, serviceModel.getType());
}
 
Example 10
Source File: AmbariDynamicServiceURLCreatorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void testZeppelinWsURL() throws Exception {
    final String HTTP_PORT = "8787";
    final String HTTPS_PORT = "8989";

    final String[] HOSTNAMES = {"host1", "host4"};
    final List<String> zeppelinServerHosts = Arrays.asList(HOSTNAMES);

    AmbariComponent zeppelinMaster = EasyMock.createNiceMock(AmbariComponent.class);
    EasyMock.expect(zeppelinMaster.getHostNames()).andReturn(zeppelinServerHosts).anyTimes();
    EasyMock.expect(zeppelinMaster.getConfigProperty("zeppelin.ssl")).andReturn("false").anyTimes();
    EasyMock.expect(zeppelinMaster.getConfigProperty("zeppelin.server.port")).andReturn(HTTP_PORT).anyTimes();
    EasyMock.expect(zeppelinMaster.getConfigProperty("zeppelin.server.ssl.port")).andReturn(HTTPS_PORT).anyTimes();
    EasyMock.replay(zeppelinMaster);

    AmbariCluster cluster = EasyMock.createNiceMock(AmbariCluster.class);
    EasyMock.expect(cluster.getComponent("ZEPPELIN_MASTER")).andReturn(zeppelinMaster).anyTimes();
    EasyMock.replay(cluster);

    AmbariDynamicServiceURLCreator builder = newURLCreator(cluster, null);

    // Run the test
    validateServiceURLs(builder.create("ZEPPELINWS", null), HOSTNAMES, "ws", HTTP_PORT, null);

    EasyMock.reset(zeppelinMaster);
    EasyMock.expect(zeppelinMaster.getHostNames()).andReturn(zeppelinServerHosts).anyTimes();
    EasyMock.expect(zeppelinMaster.getConfigProperty("zeppelin.ssl")).andReturn("true").anyTimes();
    EasyMock.expect(zeppelinMaster.getConfigProperty("zeppelin.server.port")).andReturn(HTTP_PORT).anyTimes();
    EasyMock.expect(zeppelinMaster.getConfigProperty("zeppelin.server.ssl.port")).andReturn(HTTPS_PORT).anyTimes();
    EasyMock.replay(zeppelinMaster);

    // Run the test
    validateServiceURLs(builder.create("ZEPPELINWS", null), HOSTNAMES, "wss", HTTPS_PORT, null);
}
 
Example 11
Source File: UrlRewriteProcessorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void testRewriteViaRuleWithComplexFlow() throws Exception {
  UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
  HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
  HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
  EasyMock.replay( environment, request, response );

  UrlRewriteProcessor processor = new UrlRewriteProcessor();
  UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
      "xml", getTestResourceReader( "rewrite.xml" ) );
  processor.initialize( environment, config );

  Template inputUrl;
  Template outputUrl;

  inputUrl = Parser.parseLiteral( "test-scheme://test-host:777/test-path" );
  outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.IN, "test-rule-with-complex-flow" );
  assertThat(
      "Expect rewrite to contain the correct path.",
      outputUrl.toString(), is( "test-scheme-output://test-host-output:42/test-path-output/test-path" ) );

  inputUrl = Parser.parseLiteral( "test-scheme://test-host:42/~/test-path" );
  outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.IN, "test-rule-with-complex-flow" );
  assertThat(
      "Expect rewrite to contain the correct path.",
      outputUrl.toString(), is( "test-scheme-output://test-host-output:777/test-path-output/test-home/test-path" ) );

  processor.destroy();
}
 
Example 12
Source File: ResourceTransportWrapperConverterTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public static void prepare() {
  /* Mocks */

  IPath filePath = EasyMock.createMock(IPath.class);
  IPath folderPath = EasyMock.createMock(IPath.class);
  pathFactory = EasyMock.createMock(IPathFactory.class);
  referencePoint = EasyMock.createNiceMock(IReferencePoint.class);
  file = EasyMock.createNiceMock(IFile.class);
  folder = EasyMock.createNiceMock(IFolder.class);

  String actualFilePath = "/foo/src/Main.java";

  expect(filePath.isAbsolute()).andStubReturn(false);
  expect(filePath.toPortableString()).andStubReturn(actualFilePath);

  String actualFolderPath = "/foo/bar/";

  expect(folderPath.isAbsolute()).andStubReturn(false);
  expect(folderPath.toPortableString()).andStubReturn(actualFolderPath);

  expect(pathFactory.fromPath(filePath)).andStubReturn(actualFilePath);
  expect(pathFactory.fromString(actualFilePath)).andStubReturn(filePath);

  expect(pathFactory.fromPath(folderPath)).andStubReturn(actualFolderPath);
  expect(pathFactory.fromString(actualFolderPath)).andStubReturn(folderPath);

  expect(referencePoint.getFile(filePath)).andStubReturn(file);
  expect(referencePoint.getFolder(folderPath)).andStubReturn(folder);

  expect(file.getReferencePoint()).andStubReturn(referencePoint);
  expect(file.getReferencePointRelativePath()).andStubReturn(filePath);
  expect(file.getType()).andStubReturn(Type.FILE);

  expect(folder.getReferencePoint()).andStubReturn(referencePoint);
  expect(folder.getReferencePointRelativePath()).andStubReturn(folderPath);
  expect(folder.getType()).andStubReturn(Type.FOLDER);

  EasyMock.replay(filePath, folderPath, pathFactory, referencePoint, file, folder);
}
 
Example 13
Source File: ActivitySequencerTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testUnregisterUserOnTransmissionFailure() {

  ITransmitter brokenTransmitter = EasyMock.createNiceMock(ITransmitter.class);

  try {
    brokenTransmitter.send(
        EasyMock.anyObject(String.class),
        EasyMock.anyObject(JID.class),
        EasyMock.anyObject(PacketExtension.class));
  } catch (IOException e) {
    // cannot happen in recording mode
  }

  EasyMock.expectLastCall().andStubThrow(new IOException());

  EasyMock.replay(brokenTransmitter);

  aliceSequencer =
      new ActivitySequencer(sessionStubAlice, brokenTransmitter, aliceReceiver, null);

  aliceSequencer.start();

  aliceSequencer.registerUser(bobUserInAliceSession);

  assertTrue("Bob is not registered", aliceSequencer.isUserRegistered(bobUser));

  aliceSequencer.sendActivity(
      Collections.singletonList(bobUserInAliceSession),
      new NOPActivity(aliceUser, bobUserInAliceSession, 0));

  aliceSequencer.flush(bobUserInAliceSession);

  assertFalse("Bob is still registered", aliceSequencer.isUserRegistered(bobUserInAliceSession));
}
 
Example 14
Source File: HostmapFunctionProcessorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void testHdfsUseCase() throws Exception {
  URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hdfs-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(Collections.singletonList("test-internal-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( "{*}://test-static-host:{*}/{**}?server={$hostmap(host)}&{**}" );

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

  Template input = Parser.parseLiteral(
      "test-scheme://test-external-host:42/test-path/test-file?test-name-1=test-value-1&test-name-2=test-value-2" );
  Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.OUT, "test-rule" );
  assertThat( output, notNullValue() );
  assertThat( output.getHost().getFirstValue().getPattern(), is( "test-static-host" ) );
  assertThat( output.getQuery().get( "server" ).getFirstValue().getPattern(), is( "test-external-host" ) );
  assertThat( output.getQuery().get( "server" ).getValues().size(), is( 1 ) );
  assertThat( output.getQuery().get( "test-name-1" ).getFirstValue().getPattern(), is( "test-value-1" ) );
  assertThat( output.getQuery().get( "test-name-1" ).getValues().size(), is( 1 ) );
  assertThat( output.getQuery().get( "test-name-2" ).getFirstValue().getPattern(), is( "test-value-2" ) );
  assertThat( output.getQuery().get( "test-name-2" ).getValues().size(), is( 1 ) );
  assertThat( output.getQuery().size(), is( 3 ) );
}
 
Example 15
Source File: JavaScriptJobManagerMinimalTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes variables required by the unit tests.
 */
@Before
public void before() {
    client_ = new WebClient();
    window_ = EasyMock.createNiceMock(WebWindow.class);
    page_ = EasyMock.createNiceMock(Page.class);
    manager_ = new JavaScriptJobManagerImpl(window_);
    EasyMock.expect(window_.getEnclosedPage()).andReturn(page_).anyTimes();
    EasyMock.expect(window_.getJobManager()).andReturn(manager_).anyTimes();
    EasyMock.replay(window_, page_);
    eventLoop_ = new DefaultJavaScriptExecutor(client_);
    eventLoop_.addWindow(window_);
}
 
Example 16
Source File: StrictTransportFilterTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfiguredOptionsValue() throws Exception {
  try {
    StrictTransportFilter filter = new StrictTransportFilter();
    Properties props = new Properties();
    props.put("strict.transport.enabled", "true");
    props.put("strict.transport", "max-age=31536010; includeSubDomains");
    filter.init(new TestFilterConfig(props));

    HttpServletRequest request = EasyMock.createNiceMock(
        HttpServletRequest.class);
    HttpServletResponse response = EasyMock.createNiceMock(
        HttpServletResponse.class);
    EasyMock.replay(request);
    EasyMock.replay(response);

    TestFilterChain chain = new TestFilterChain();
    filter.doFilter(request, response, chain);
    Assert.assertTrue("doFilterCalled should not be false.",
        chain.doFilterCalled );
    Assert.assertEquals("Options value incorrect should be max-age=31536010; includeSubDomains but is: "
                            + options, "max-age=31536010; includeSubDomains", options);

    Assert.assertEquals("Strict-Transport-Security count not equal to 1.", 1, headers.size());
  } catch (ServletException se) {
    fail("Should NOT have thrown a ServletException.");
  }
}
 
Example 17
Source File: AbstractJWTFilterTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testFailedSignatureValidationJWT() throws Exception {
  try {
    // Create a private key to sign the token
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);

    KeyPair kp = kpg.genKeyPair();

    Properties props = getProperties();
    handler.init(new TestFilterConfig(props));

    SignedJWT jwt = getJWT(AbstractJWTFilter.JWT_DEFAULT_ISSUER, "bob",
                           new Date(new Date().getTime() + 5000), (RSAPrivateKey)kp.getPrivate());

    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    setTokenOnRequest(request, jwt);

    EasyMock.expect(request.getRequestURL()).andReturn(
        new StringBuffer(SERVICE_URL)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(null);
    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
        SERVICE_URL).anyTimes();
    EasyMock.expect(response.getOutputStream()).andAnswer(() -> new ServletOutputStream() {
      @Override
      public void write(int b) {
      }

      @Override
      public void setWriteListener(WriteListener arg0) {
      }

      @Override
      public boolean isReady() {
        return false;
      }
    }).anyTimes();
    EasyMock.replay(request, response);

    TestFilterChain chain = new TestFilterChain();
    handler.doFilter(request, response, chain);
    Assert.assertTrue("doFilterCalled should not be true.", !chain.doFilterCalled);
    Assert.assertNull("No Subject should be returned.", chain.subject);
  } catch (ServletException se) {
    fail("Should NOT have thrown a ServletException.");
  }
}
 
Example 18
Source File: UrlRewriteProcessorTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testIdenticalRewriteOutputRulesWithScopes() throws IOException, URISyntaxException {
  UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
  HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
  HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
  ArrayList<String> roles = new ArrayList<>();
  roles.add("service-1");
  EasyMock.expect(environment.resolve("service.role")).andReturn(roles).anyTimes();
  EasyMock.replay( environment, request, response );

  UrlRewriteProcessor processor = new UrlRewriteProcessor();
  UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
      "xml", getTestResourceReader( "rewrite-with-same-rules-different-scope.xml" ) );
  processor.initialize( environment, config );

  Template inputUrl = Parser.parseLiteral( "scheme://input-mock-host:42/test-input-path" );
  Template outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, null );

  assertThat( "Expect rewrite to produce a new URL",
      outputUrl, notNullValue() );
  assertThat(
      "Expect rewrite to contain the correct path.",
      outputUrl.toString(), is( "output-mock-scheme-2://output-mock-host-2:42/test-input-path" ) );

  inputUrl = Parser.parseLiteral( "mock-scheme://input-mock-host:42/no-query" );
  outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, null );

  roles.remove(0);
  roles.add("service-2");

  assertThat(
      "Expect rewrite to contain the correct path.",
      outputUrl.toString(), is( "mock-scheme://output-mock-host-5:42/no-query" ) );

  outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, "service-2/test-rule-4" );

  //no scope information should pick the first one
  assertThat(
      "Expect rewrite to contain the correct path.",
      outputUrl.toString(), is( "mock-scheme://output-mock-host-4:42/no-query" ) );

  outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "service-2/test-rule-4" );

  assertThat(
      "Expect rewrite to contain the correct path.",
      outputUrl.toString(), is( "mock-scheme://output-mock-host-4:42/no-query" ) );

  //Test the IN direction
  inputUrl = Parser.parseLiteral( "scheme://input-mock-host:42/test-input-path" );
  outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.IN, null );

  assertThat( "Expect rewrite to produce a new URL",
      outputUrl, notNullValue() );
  assertThat(
      "Expect rewrite to contain the correct path.",
      outputUrl.toString(), is( "input-mock-scheme-2://input-mock-host-2:42/test-input-path" ) );

  //Test the scenario where input could match two different rules
  inputUrl = Parser.parseLiteral( "/foo/bar" );

  roles.remove(0);
  roles.add("service-1");
  outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, null);

  assertThat(
          "Expect rewrite to contain the correct path.",
          outputUrl.toString(), is( "/foo/service-1" ) );

  roles.remove(0);
  roles.add("service-2");

  outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, null);

  assertThat(
          "Expect rewrite to contain the correct path.",
          outputUrl.toString(), is( "/foo/service-2" ) );

  processor.destroy();
}
 
Example 19
Source File: TokenServiceResourceTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testCustomTTL() throws Exception {
  ServletContext context = EasyMock.createNiceMock(ServletContext.class);
  EasyMock.expect(context.getInitParameter("knox.token.audiences")).andReturn("recipient1,recipient2");
  EasyMock.expect(context.getInitParameter("knox.token.ttl")).andReturn("60000");
  EasyMock.expect(context.getInitParameter("knox.token.target.url")).andReturn(null);
  EasyMock.expect(context.getInitParameter("knox.token.client.data")).andReturn(null);

  HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
  EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes();
  Principal principal = EasyMock.createNiceMock(Principal.class);
  EasyMock.expect(principal.getName()).andReturn("alice").anyTimes();
  EasyMock.expect(request.getUserPrincipal()).andReturn(principal).anyTimes();

  GatewayServices services = EasyMock.createNiceMock(GatewayServices.class);
  EasyMock.expect(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(services);

  JWTokenAuthority authority = new TestJWTokenAuthority(publicKey, privateKey);
  EasyMock.expect(services.getService(ServiceType.TOKEN_SERVICE)).andReturn(authority);

  EasyMock.replay(principal, services, context, request);

  TokenResource tr = new TokenResource();
  tr.request = request;
  tr.context = context;
  tr.init();

  // Issue a token
  Response retResponse = tr.doGet();

  assertEquals(200, retResponse.getStatus());

  // Parse the response
  String retString = retResponse.getEntity().toString();
  String accessToken = getTagValue(retString, "access_token");
  assertNotNull(accessToken);
  String expiry = getTagValue(retString, "expires_in");
  assertNotNull(expiry);

  // Verify the token
  JWT parsedToken = new JWTToken(accessToken);
  assertEquals("alice", parsedToken.getSubject());
  assertTrue(authority.verifyToken(parsedToken));

  Date expiresDate = parsedToken.getExpiresDate();
  Date now = new Date();
  assertTrue(expiresDate.after(now));
  long diff = expiresDate.getTime() - now.getTime();
  assertTrue(diff < 60000L && diff > 30000L);
}
 
Example 20
Source File: AnnotationManagerTest.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/** Tests removing all annotations as part of the annotation manager disposal. */
@Test
public void testRemoveAllAnnotations() throws Exception {
  /* setup */
  IFile file2 = EasyMock.createNiceMock(IFile.class);

  int start = 94;
  int end = 112;
  List<Pair<Integer, Integer>> expectedSelectionRanges = createSelectionRange(start, end);
  List<Pair<Integer, Integer>> expectedContributionRanges = createContributionRanges(start, end);

  prepareMockAddRemoveRangeHighlighters();
  mockAddRemoveSelectionRangeHighlighters(expectedSelectionRanges, file, editor);
  mockAddRemoveSelectionRangeHighlighters(expectedSelectionRanges, file2, editor);
  mockAddRemoveCaretRangeHighlighters(end, file, editor);
  mockAddRemoveCaretRangeHighlighters(end, file2, editor);
  mockAddRemoveContributionRangeHighlighters(expectedContributionRanges, file, editor);
  mockAddRemoveContributionRangeHighlighters(expectedContributionRanges, file2, editor);
  replayMockAddRemoveRangeHighlighters();

  SelectionAnnotation selectionAnnotation1 =
      new SelectionAnnotation(user, file, start, end, editor, false);
  selectionAnnotationStore.addAnnotation(selectionAnnotation1);

  ContributionAnnotation contributionAnnotation1 =
      new ContributionAnnotation(user, file, start, end, editor);
  contributionAnnotationQueue.addAnnotation(contributionAnnotation1);

  SelectionAnnotation selectionAnnotation2 =
      new SelectionAnnotation(user2, file, start, end, editor, false);
  selectionAnnotationStore.addAnnotation(selectionAnnotation2);

  ContributionAnnotation contributionAnnotation2 =
      new ContributionAnnotation(user2, file, start, end, editor);
  contributionAnnotationQueue.addAnnotation(contributionAnnotation2);

  SelectionAnnotation selectionAnnotation3 =
      new SelectionAnnotation(user, file2, start, end, editor, false);
  selectionAnnotationStore.addAnnotation(selectionAnnotation3);

  ContributionAnnotation contributionAnnotation3 =
      new ContributionAnnotation(user, file2, start, end, editor);
  contributionAnnotationQueue.addAnnotation(contributionAnnotation3);

  SelectionAnnotation selectionAnnotation4 =
      new SelectionAnnotation(user2, file2, start, end, editor, false);
  selectionAnnotationStore.addAnnotation(selectionAnnotation4);

  ContributionAnnotation contributionAnnotation4 =
      new ContributionAnnotation(user2, file2, start, end, editor);
  contributionAnnotationQueue.addAnnotation(contributionAnnotation4);

  /* calls to test */
  annotationManager.dispose();

  /* check assertions */
  verifyRemovalCall();

  List<SelectionAnnotation> selectionAnnotations = selectionAnnotationStore.getAnnotations();
  assertEquals(0, selectionAnnotations.size());

  List<ContributionAnnotation> contributionAnnotations =
      contributionAnnotationQueue.getAnnotations();
  assertEquals(0, contributionAnnotations.size());
}