Search in sources :

Example 76 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project kafka-spout by HolmesNL.

the class KafkaSpoutConstructorTest method testDelegateCustomScheme.

@Test
public void testDelegateCustomScheme() {
    final Scheme scheme = new Scheme() {

        @Override
        public List<Object> deserialize(final byte[] bytes) {
            return Arrays.<Object>asList(new byte[] { bytes[0] }, Arrays.copyOfRange(bytes, 1, bytes.length));
        }

        @Override
        public Fields getOutputFields() {
            return new Fields("head", "tail");
        }
    };
    final OutputFieldsDeclarer declarer = mock(OutputFieldsDeclarer.class);
    // test for both constructors that accept a scheme
    new KafkaSpout(scheme).declareOutputFields(declarer);
    new KafkaSpout("topic", scheme).declareOutputFields(declarer);
    // Fields doesn't implement equals; match it manually
    verify(declarer, times(2)).declare(argThat(new ArgumentMatcher<Fields>() {

        @Override
        public boolean matches(final Object argument) {
            final Fields fields = (Fields) argument;
            return fields.size() == 2 && fields.get(0).equals("head") && fields.get(1).equals("tail");
        }
    }));
}
Also used : Scheme(backtype.storm.spout.Scheme) Fields(backtype.storm.tuple.Fields) ArgumentMatcher(org.mockito.ArgumentMatcher) OutputFieldsDeclarer(backtype.storm.topology.OutputFieldsDeclarer) Test(org.junit.Test)

Example 77 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project hadoop by apache.

the class TestContainer method testServiceData.

/**
   * Verify serviceData correctly sent.
   */
@Test
public void testServiceData() throws Exception {
    WrappedContainer wc = null;
    try {
        wc = new WrappedContainer(9, 314159265358979L, 4344, "yak", false, true);
        assertEquals(ContainerState.NEW, wc.c.getContainerState());
        wc.initContainer();
        for (final Map.Entry<String, ByteBuffer> e : wc.serviceData.entrySet()) {
            ArgumentMatcher<AuxServicesEvent> matchesServiceReq = new ArgumentMatcher<AuxServicesEvent>() {

                @Override
                public boolean matches(Object o) {
                    AuxServicesEvent evt = (AuxServicesEvent) o;
                    return e.getKey().equals(evt.getServiceID()) && 0 == e.getValue().compareTo(evt.getServiceData());
                }
            };
            verify(wc.auxBus).handle(argThat(matchesServiceReq));
        }
        final WrappedContainer wcf = wc;
        // verify launch on empty resource request
        ArgumentMatcher<ContainersLauncherEvent> matchesLaunchReq = new ArgumentMatcher<ContainersLauncherEvent>() {

            @Override
            public boolean matches(Object o) {
                ContainersLauncherEvent evt = (ContainersLauncherEvent) o;
                return evt.getType() == ContainersLauncherEventType.LAUNCH_CONTAINER && wcf.cId.equals(evt.getContainer().getContainerId());
            }
        };
        verify(wc.launcherBus).handle(argThat(matchesLaunchReq));
    } finally {
        if (wc != null) {
            wc.finished();
        }
    }
}
Also used : ArgumentMatcher(org.mockito.ArgumentMatcher) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ByteBuffer(java.nio.ByteBuffer) AuxServicesEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServicesEvent) ContainersLauncherEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainersLauncherEvent) Test(org.junit.Test)

Example 78 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project hadoop by apache.

the class TestResourceLocalizationService method testLocalizationHeartbeat.

@Test(timeout = 10000)
// mocked generics
@SuppressWarnings("unchecked")
public void testLocalizationHeartbeat() throws Exception {
    List<Path> localDirs = new ArrayList<Path>();
    String[] sDirs = new String[1];
    // Making sure that we have only one local disk so that it will only be
    // selected for consecutive resource localization calls.  This is required
    // to test LocalCacheDirectoryManager.
    localDirs.add(lfs.makeQualified(new Path(basedir, 0 + "")));
    sDirs[0] = localDirs.get(0).toString();
    conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
    // Adding configuration to make sure there is only one file per
    // directory
    conf.set(YarnConfiguration.NM_LOCAL_CACHE_MAX_FILES_PER_DIRECTORY, "37");
    DrainDispatcher dispatcher = new DrainDispatcher();
    dispatcher.init(conf);
    dispatcher.start();
    EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
    dispatcher.register(ApplicationEventType.class, applicationBus);
    EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
    dispatcher.register(ContainerEventType.class, containerBus);
    ContainerExecutor exec = mock(ContainerExecutor.class);
    LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
    dirsHandler.init(conf);
    DeletionService delServiceReal = new DeletionService(exec);
    DeletionService delService = spy(delServiceReal);
    delService.init(new Configuration());
    delService.start();
    ResourceLocalizationService rawService = new ResourceLocalizationService(dispatcher, exec, delService, dirsHandler, nmContext);
    ResourceLocalizationService spyService = spy(rawService);
    doReturn(mockServer).when(spyService).createServer();
    doReturn(lfs).when(spyService).getLocalFileContext(isA(Configuration.class));
    FsPermission defaultPermission = FsPermission.getDirDefault().applyUMask(lfs.getUMask());
    FsPermission nmPermission = ResourceLocalizationService.NM_PRIVATE_PERM.applyUMask(lfs.getUMask());
    final Path userDir = new Path(sDirs[0].substring("file:".length()), ContainerLocalizer.USERCACHE);
    final Path fileDir = new Path(sDirs[0].substring("file:".length()), ContainerLocalizer.FILECACHE);
    final Path sysDir = new Path(sDirs[0].substring("file:".length()), ResourceLocalizationService.NM_PRIVATE_DIR);
    final FileStatus fs = new FileStatus(0, true, 1, 0, System.currentTimeMillis(), 0, defaultPermission, "", "", new Path(sDirs[0]));
    final FileStatus nmFs = new FileStatus(0, true, 1, 0, System.currentTimeMillis(), 0, nmPermission, "", "", sysDir);
    doAnswer(new Answer<FileStatus>() {

        @Override
        public FileStatus answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            if (args.length > 0) {
                if (args[0].equals(userDir) || args[0].equals(fileDir)) {
                    return fs;
                }
            }
            return nmFs;
        }
    }).when(spylfs).getFileStatus(isA(Path.class));
    try {
        spyService.init(conf);
        spyService.start();
        // init application
        final Application app = mock(Application.class);
        final ApplicationId appId = BuilderUtils.newApplicationId(314159265358979L, 3);
        when(app.getUser()).thenReturn("user0");
        when(app.getAppId()).thenReturn(appId);
        spyService.handle(new ApplicationLocalizationEvent(LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
        ArgumentMatcher<ApplicationEvent> matchesAppInit = new ArgumentMatcher<ApplicationEvent>() {

            @Override
            public boolean matches(Object o) {
                ApplicationEvent evt = (ApplicationEvent) o;
                return evt.getType() == ApplicationEventType.APPLICATION_INITED && appId == evt.getApplicationID();
            }
        };
        dispatcher.await();
        verify(applicationBus).handle(argThat(matchesAppInit));
        // init container rsrc, localizer
        Random r = new Random();
        long seed = r.nextLong();
        System.out.println("SEED: " + seed);
        r.setSeed(seed);
        final Container c = getMockContainer(appId, 42, "user0");
        FSDataOutputStream out = new FSDataOutputStream(new DataOutputBuffer(), null);
        doReturn(out).when(spylfs).createInternal(isA(Path.class), isA(EnumSet.class), isA(FsPermission.class), anyInt(), anyShort(), anyLong(), isA(Progressable.class), isA(ChecksumOpt.class), anyBoolean());
        final LocalResource resource1 = getPrivateMockedResource(r);
        LocalResource resource2 = null;
        do {
            resource2 = getPrivateMockedResource(r);
        } while (resource2 == null || resource2.equals(resource1));
        LocalResource resource3 = null;
        do {
            resource3 = getPrivateMockedResource(r);
        } while (resource3 == null || resource3.equals(resource1) || resource3.equals(resource2));
        // above call to make sure we don't get identical resources.
        final LocalResourceRequest req1 = new LocalResourceRequest(resource1);
        final LocalResourceRequest req2 = new LocalResourceRequest(resource2);
        final LocalResourceRequest req3 = new LocalResourceRequest(resource3);
        Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs = new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>();
        List<LocalResourceRequest> privateResourceList = new ArrayList<LocalResourceRequest>();
        privateResourceList.add(req1);
        privateResourceList.add(req2);
        privateResourceList.add(req3);
        rsrcs.put(LocalResourceVisibility.PRIVATE, privateResourceList);
        spyService.handle(new ContainerLocalizationRequestEvent(c, rsrcs));
        // Sigh. Thread init of private localizer not accessible
        Thread.sleep(1000);
        dispatcher.await();
        String appStr = appId.toString();
        String ctnrStr = c.getContainerId().toString();
        ArgumentCaptor<LocalizerStartContext> contextCaptor = ArgumentCaptor.forClass(LocalizerStartContext.class);
        verify(exec).startLocalizer(contextCaptor.capture());
        LocalizerStartContext context = contextCaptor.getValue();
        Path localizationTokenPath = context.getNmPrivateContainerTokens();
        assertEquals("user0", context.getUser());
        assertEquals(appStr, context.getAppId());
        assertEquals(ctnrStr, context.getLocId());
        // heartbeat from localizer
        LocalResourceStatus rsrc1success = mock(LocalResourceStatus.class);
        LocalResourceStatus rsrc2pending = mock(LocalResourceStatus.class);
        LocalResourceStatus rsrc2success = mock(LocalResourceStatus.class);
        LocalResourceStatus rsrc3success = mock(LocalResourceStatus.class);
        LocalizerStatus stat = mock(LocalizerStatus.class);
        when(stat.getLocalizerId()).thenReturn(ctnrStr);
        when(rsrc1success.getResource()).thenReturn(resource1);
        when(rsrc2pending.getResource()).thenReturn(resource2);
        when(rsrc2success.getResource()).thenReturn(resource2);
        when(rsrc3success.getResource()).thenReturn(resource3);
        when(rsrc1success.getLocalSize()).thenReturn(4344L);
        when(rsrc2success.getLocalSize()).thenReturn(2342L);
        when(rsrc3success.getLocalSize()).thenReturn(5345L);
        URL locPath = getPath("/cache/private/blah");
        when(rsrc1success.getLocalPath()).thenReturn(locPath);
        when(rsrc2success.getLocalPath()).thenReturn(locPath);
        when(rsrc3success.getLocalPath()).thenReturn(locPath);
        when(rsrc1success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
        when(rsrc2pending.getStatus()).thenReturn(ResourceStatusType.FETCH_PENDING);
        when(rsrc2success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
        when(rsrc3success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
        // Four heartbeats with sending:
        // 1 - empty
        // 2 - resource1 FETCH_SUCCESS
        // 3 - resource2 FETCH_PENDING
        // 4 - resource2 FETCH_SUCCESS, resource3 FETCH_SUCCESS
        List<LocalResourceStatus> rsrcs4 = new ArrayList<LocalResourceStatus>();
        rsrcs4.add(rsrc2success);
        rsrcs4.add(rsrc3success);
        when(stat.getResources()).thenReturn(Collections.<LocalResourceStatus>emptyList()).thenReturn(Collections.singletonList(rsrc1success)).thenReturn(Collections.singletonList(rsrc2pending)).thenReturn(rsrcs4).thenReturn(Collections.<LocalResourceStatus>emptyList());
        String localPath = Path.SEPARATOR + ContainerLocalizer.USERCACHE + Path.SEPARATOR + "user0" + Path.SEPARATOR + ContainerLocalizer.FILECACHE;
        // First heartbeat
        LocalizerHeartbeatResponse response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
        assertEquals(1, response.getResourceSpecs().size());
        assertEquals(req1, new LocalResourceRequest(response.getResourceSpecs().get(0).getResource()));
        URL localizedPath = response.getResourceSpecs().get(0).getDestinationDirectory();
        // Appending to local path unique number(10) generated as a part of
        // LocalResourcesTracker
        assertTrue(localizedPath.getFile().endsWith(localPath + Path.SEPARATOR + "10"));
        // Second heartbeat
        response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
        assertEquals(1, response.getResourceSpecs().size());
        assertEquals(req2, new LocalResourceRequest(response.getResourceSpecs().get(0).getResource()));
        localizedPath = response.getResourceSpecs().get(0).getDestinationDirectory();
        // Resource's destination path should be now inside sub directory 0 as
        // LocalCacheDirectoryManager will be used and we have restricted number
        // of files per directory to 1.
        assertTrue(localizedPath.getFile().endsWith(localPath + Path.SEPARATOR + "0" + Path.SEPARATOR + "11"));
        // Third heartbeat
        response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
        assertEquals(1, response.getResourceSpecs().size());
        assertEquals(req3, new LocalResourceRequest(response.getResourceSpecs().get(0).getResource()));
        localizedPath = response.getResourceSpecs().get(0).getDestinationDirectory();
        assertTrue(localizedPath.getFile().endsWith(localPath + Path.SEPARATOR + "1" + Path.SEPARATOR + "12"));
        response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
        spyService.handle(new ContainerLocalizationEvent(LocalizationEventType.CONTAINER_RESOURCES_LOCALIZED, c));
        // get shutdown after receive CONTAINER_RESOURCES_LOCALIZED event
        response = spyService.heartbeat(stat);
        assertEquals(LocalizerAction.DIE, response.getLocalizerAction());
        dispatcher.await();
        // verify container notification
        ArgumentMatcher<ContainerEvent> matchesContainerLoc = new ArgumentMatcher<ContainerEvent>() {

            @Override
            public boolean matches(Object o) {
                ContainerEvent evt = (ContainerEvent) o;
                return evt.getType() == ContainerEventType.RESOURCE_LOCALIZED && c.getContainerId() == evt.getContainerID();
            }
        };
        // total 3 resource localzation calls. one for each resource.
        verify(containerBus, times(3)).handle(argThat(matchesContainerLoc));
        // Verify deletion of localization token.
        verify(delService).delete((String) isNull(), eq(localizationTokenPath));
    } finally {
        spyService.stop();
        dispatcher.stop();
        delService.stop();
    }
}
Also used : ContainerExecutor(org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor) DefaultContainerExecutor(org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor) FileStatus(org.apache.hadoop.fs.FileStatus) ContainerLocalizationRequestEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationRequestEvent) Configuration(org.apache.hadoop.conf.Configuration) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Container(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container) Random(java.util.Random) ArgumentMatcher(org.mockito.ArgumentMatcher) DataOutputBuffer(org.apache.hadoop.io.DataOutputBuffer) ApplicationLocalizationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ApplicationLocalizationEvent) FSDataOutputStream(org.apache.hadoop.fs.FSDataOutputStream) ContainerLocalizationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationEvent) ApplicationEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent) DeletionService(org.apache.hadoop.yarn.server.nodemanager.DeletionService) LocalizerStatus(org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerStatus) LocalDirsHandlerService(org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService) ChecksumOpt(org.apache.hadoop.fs.Options.ChecksumOpt) Progressable(org.apache.hadoop.util.Progressable) Collection(java.util.Collection) ApplicationId(org.apache.hadoop.yarn.api.records.ApplicationId) Application(org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application) DrainDispatcher(org.apache.hadoop.yarn.event.DrainDispatcher) URL(org.apache.hadoop.yarn.api.records.URL) LocalResourceVisibility(org.apache.hadoop.yarn.api.records.LocalResourceVisibility) LocalizerStartContext(org.apache.hadoop.yarn.server.nodemanager.executor.LocalizerStartContext) FsPermission(org.apache.hadoop.fs.permission.FsPermission) Path(org.apache.hadoop.fs.Path) ContainerEvent(org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerEvent) EnumSet(java.util.EnumSet) LocalResource(org.apache.hadoop.yarn.api.records.LocalResource) InvocationOnMock(org.mockito.invocation.InvocationOnMock) LocalizerHeartbeatResponse(org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse) LocalResourceStatus(org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalResourceStatus) Test(org.junit.Test)

Example 79 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project hadoop by apache.

the class TestGetImageServlet method testIsValidRequestor.

@Test
public void testIsValidRequestor() throws IOException {
    Configuration conf = new HdfsConfiguration();
    KerberosName.setRules("RULE:[1:$1]\nRULE:[2:$1]");
    // Set up generic HA configs.
    conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1");
    conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX, "ns1"), "nn1,nn2");
    // Set up NN1 HA configs.
    conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY, "ns1", "nn1"), "host1:1234");
    conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, "ns1", "nn1"), "hdfs/_HOST@TEST-REALM.COM");
    // Set up NN2 HA configs.
    conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY, "ns1", "nn2"), "host2:1234");
    conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, "ns1", "nn2"), "hdfs/_HOST@TEST-REALM.COM");
    // Initialize this conf object as though we're running on NN1.
    NameNode.initializeGenericKeys(conf, "ns1", "nn1");
    AccessControlList acls = Mockito.mock(AccessControlList.class);
    Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(false);
    ServletContext context = Mockito.mock(ServletContext.class);
    Mockito.when(context.getAttribute(HttpServer2.ADMINS_ACL)).thenReturn(acls);
    // Make sure that NN2 is considered a valid fsimage/edits requestor.
    assertTrue(ImageServlet.isValidRequestor(context, "hdfs/host2@TEST-REALM.COM", conf));
    // Mark atm as an admin.
    Mockito.when(acls.isUserAllowed(Mockito.argThat(new ArgumentMatcher<UserGroupInformation>() {

        @Override
        public boolean matches(Object argument) {
            return ((UserGroupInformation) argument).getShortUserName().equals("atm");
        }
    }))).thenReturn(true);
    // Make sure that NN2 is still considered a valid requestor.
    assertTrue(ImageServlet.isValidRequestor(context, "hdfs/host2@TEST-REALM.COM", conf));
    // Make sure an admin is considered a valid requestor.
    assertTrue(ImageServlet.isValidRequestor(context, "atm@TEST-REALM.COM", conf));
    // Make sure other users are *not* considered valid requestors.
    assertFalse(ImageServlet.isValidRequestor(context, "todd@TEST-REALM.COM", conf));
}
Also used : AccessControlList(org.apache.hadoop.security.authorize.AccessControlList) HdfsConfiguration(org.apache.hadoop.hdfs.HdfsConfiguration) Configuration(org.apache.hadoop.conf.Configuration) ArgumentMatcher(org.mockito.ArgumentMatcher) ServletContext(javax.servlet.ServletContext) HdfsConfiguration(org.apache.hadoop.hdfs.HdfsConfiguration) Test(org.junit.Test)

Example 80 with ArgumentMatcher

use of org.mockito.ArgumentMatcher in project mockito by mockito.

the class MatchersPrinter method applyPrintSettings.

private Iterator<FormattedText> applyPrintSettings(List<ArgumentMatcher> matchers, PrintSettings printSettings) {
    List<FormattedText> out = new LinkedList<FormattedText>();
    int i = 0;
    for (final ArgumentMatcher matcher : matchers) {
        if (matcher instanceof ContainsExtraTypeInfo && printSettings.extraTypeInfoFor(i)) {
            out.add(new FormattedText(((ContainsExtraTypeInfo) matcher).toStringWithType()));
        } else {
            out.add(new FormattedText(MatcherToString.toString(matcher)));
        }
        i++;
    }
    return out.iterator();
}
Also used : ArgumentMatcher(org.mockito.ArgumentMatcher) ContainsExtraTypeInfo(org.mockito.internal.matchers.ContainsExtraTypeInfo) LinkedList(java.util.LinkedList)

Aggregations

ArgumentMatcher (org.mockito.ArgumentMatcher)142 Test (org.junit.Test)116 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)36 Context (android.content.Context)26 Matchers.anyString (org.mockito.Matchers.anyString)26 HashMap (java.util.HashMap)25 Appender (ch.qos.logback.core.Appender)23 Logger (org.slf4j.Logger)23 ArrayList (java.util.ArrayList)19 UUID (java.util.UUID)19 Intent (android.content.Intent)18 File (java.io.File)15 ResolveInfo (android.content.pm.ResolveInfo)14 PackageManager (android.content.pm.PackageManager)13 Channel (com.microsoft.azure.mobile.channel.Channel)13 ApplicationService (org.codice.ddf.admin.application.service.ApplicationService)13 InvocationOnMock (org.mockito.invocation.InvocationOnMock)13 IOException (java.io.IOException)12 ServiceCallback (com.microsoft.appcenter.http.ServiceCallback)11 Activity (android.app.Activity)10