@Test
  public void testDelayedStart() throws Exception {
    expectJobAccepted();
    expectJobFetch();

    // Query to test if live tasks exist for the job.
    expectActiveTaskFetch(TASK);

    // Live tasks exist, so the cron manager must delay the cron launch.
    delayExecutor.execute(capture(delayLaunchCapture));

    // The cron manager will then try to initiate the kill.
    scheduler.killTasks((Query.Builder) anyObject(), eq(CronJobManager.CRON_USER));

    // Immediate query and delayed query.
    expectActiveTaskFetch(TASK).times(2);

    // Simulate the live task disappearing.
    expectActiveTaskFetch();

    stateManager.insertPendingTasks(sanitizedConfiguration.getTaskConfigs());

    control.replay();

    cron.receiveJob(sanitizedConfiguration);
    cron.startJobNow(job.getKey());
    assertEquals(ImmutableSet.of(job.getKey()), cron.getPendingRuns());
    delayLaunchCapture.getValue().run();
    assertEquals(ImmutableSet.<IJobKey>of(), cron.getPendingRuns());
  }
  @Test
  public void testListTypesByFilter() throws Exception {
    AttributeDefinition attr = TypesUtil.createOptionalAttrDef("attr", DataTypes.STRING_TYPE);
    String a =
        createType(
                TypesSerialization.toJson(
                    TypesUtil.createClassTypeDef(
                        "A" + randomString(), ImmutableSet.<String>of(), attr),
                    false))
            .get(0);
    String a1 =
        createType(
                TypesSerialization.toJson(
                    TypesUtil.createClassTypeDef("A1" + randomString(), ImmutableSet.of(a), attr),
                    false))
            .get(0);
    String b =
        createType(
                TypesSerialization.toJson(
                    TypesUtil.createClassTypeDef(
                        "B" + randomString(), ImmutableSet.<String>of(), attr),
                    false))
            .get(0);
    String c =
        createType(
                TypesSerialization.toJson(
                    TypesUtil.createClassTypeDef("C" + randomString(), ImmutableSet.of(a, b), attr),
                    false))
            .get(0);

    List<String> results = serviceClient.listTypes(DataTypes.TypeCategory.CLASS, a, b);
    assertEquals(results, Arrays.asList(a1), "Results: " + results);
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testGetAggregatorStepsWithParDoBoundMultiExtractsSteps() {
    @SuppressWarnings("rawtypes")
    ParDo.BoundMulti bound = mock(ParDo.BoundMulti.class, "BoundMulti");
    AggregatorProvidingDoFn<Object, Void> fn = new AggregatorProvidingDoFn<>();
    when(bound.getFn()).thenReturn(fn);

    Aggregator<Long, Long> aggregatorOne = fn.addAggregator(new Max.MaxLongFn());
    Aggregator<Double, Double> aggregatorTwo = fn.addAggregator(new Min.MinDoubleFn());

    TransformTreeNode transformNode = mock(TransformTreeNode.class);
    when(transformNode.getTransform()).thenReturn(bound);

    doAnswer(new VisitNodesAnswer(ImmutableList.of(transformNode)))
        .when(p)
        .traverseTopologically(Mockito.any(PipelineVisitor.class));

    AggregatorPipelineExtractor extractor = new AggregatorPipelineExtractor(p);

    Map<Aggregator<?, ?>, Collection<PTransform<?, ?>>> aggregatorSteps =
        extractor.getAggregatorSteps();

    assertEquals(ImmutableSet.<PTransform<?, ?>>of(bound), aggregatorSteps.get(aggregatorOne));
    assertEquals(ImmutableSet.<PTransform<?, ?>>of(bound), aggregatorSteps.get(aggregatorTwo));
    assertEquals(2, aggregatorSteps.size());
  }
    @VisibleForTesting // productionVisibility = Visibility.PRIVATE
    public CppCompilationContext build(ActionOwner owner, MiddlemanFactory middlemanFactory) {
      // We don't create middlemen in LIPO collector subtree, because some target CT
      // will do that instead.
      Artifact prerequisiteStampFile =
          (ruleContext != null
                  && ruleContext.getFragment(CppConfiguration.class).isLipoContextCollector())
              ? getMiddlemanArtifact(middlemanFactory)
              : createMiddleman(owner, middlemanFactory);

      return new CppCompilationContext(
          new CommandLineContext(
              ImmutableList.copyOf(includeDirs),
              ImmutableList.copyOf(quoteIncludeDirs),
              ImmutableList.copyOf(systemIncludeDirs),
              ImmutableList.copyOf(defines)),
          prerequisiteStampFile == null
              ? ImmutableSet.<Artifact>of()
              : ImmutableSet.of(prerequisiteStampFile),
          declaredIncludeDirs.build(),
          declaredIncludeWarnDirs.build(),
          declaredIncludeSrcs.build(),
          pregreppedHdrs.build(),
          moduleInfo.build(),
          picModuleInfo.build(),
          transitiveModuleMaps.build(),
          directModuleMaps.build(),
          cppModuleMap,
          provideTransitiveModuleMaps,
          useHeaderModules);
    }
  /**
   * Used source from jclouds project. {@link
   * org.jclouds.ec2.compute.EC2TemplateBuilderTest#newTemplateBuilder}
   */
  @SuppressWarnings("unchecked")
  protected TemplateBuilder newTemplateBuilder(
      Supplier<Set<? extends Image>> images,
      Supplier<LoadingCache<RegionAndName, ? extends Image>> imageCache) {

    Provider<TemplateOptions> optionsProvider = mock(Provider.class);
    Provider<TemplateBuilder> templateBuilderProvider = mock(Provider.class);
    TemplateOptions defaultOptions = mock(TemplateOptions.class);
    GetImageStrategy getImageStrategy = mock(GetImageStrategy.class);

    when(optionsProvider.get()).thenReturn(defaultOptions);

    Supplier<Set<? extends Location>> locations =
        Suppliers.<Set<? extends Location>>ofInstance(ImmutableSet.of(jcloudsDomainLocation));
    Supplier<Set<? extends Hardware>> sizes =
        Suppliers.<Set<? extends Hardware>>ofInstance(ImmutableSet.of(HARDWARE_SUPPORTING_BOGUS));

    return new EC2TemplateBuilderImpl(
        locations,
        new ImageCacheSupplier(images, 60),
        sizes,
        Suppliers.ofInstance(jcloudsDomainLocation),
        optionsProvider,
        templateBuilderProvider,
        getImageStrategy,
        imageCache) {
      @Override
      protected ToStringHelper string() {
        return super.string().add("type", "Stubbed-TemplateBuilder");
      }
    };
  }
  @Test
  public void testLibraryHeaderGroups() throws NoSuchBuildTargetException {
    NewNativeTargetProjectMutator mutator = mutatorWithCommonDefaults();

    SourcePath foo = new FakeSourcePath("HeaderGroup1/foo.h");
    SourcePath bar = new FakeSourcePath("HeaderGroup1/bar.h");
    SourcePath baz = new FakeSourcePath("HeaderGroup2/baz.h");
    mutator.setPublicHeaders(ImmutableSet.of(bar, baz));
    mutator.setPrivateHeaders(ImmutableSet.of(foo));
    NewNativeTargetProjectMutator.Result result =
        mutator.buildTargetAndAddToProject(generatedProject);

    PBXGroup sourcesGroup = result.targetGroup.getOrCreateChildGroupByName("Sources");

    assertThat(sourcesGroup.getChildren(), hasSize(2));

    PBXGroup group1 = (PBXGroup) Iterables.get(sourcesGroup.getChildren(), 0);
    assertEquals("HeaderGroup1", group1.getName());
    assertThat(group1.getChildren(), hasSize(2));
    PBXFileReference fileRefBar = (PBXFileReference) Iterables.get(group1.getChildren(), 0);
    assertEquals("bar.h", fileRefBar.getName());
    PBXFileReference fileRefFoo = (PBXFileReference) Iterables.get(group1.getChildren(), 1);
    assertEquals("foo.h", fileRefFoo.getName());

    PBXGroup group2 = (PBXGroup) Iterables.get(sourcesGroup.getChildren(), 1);
    assertEquals("HeaderGroup2", group2.getName());
    assertThat(group2.getChildren(), hasSize(1));
    PBXFileReference fileRefBaz = (PBXFileReference) Iterables.get(group2.getChildren(), 0);
    assertEquals("baz.h", fileRefBaz.getName());
  }
  @Test
  public void testFetchContentSignedOwner() throws Exception {
    oauth.httpResponse = CACHEABLE;
    signedRequest.getOAuthArguments().setSignViewer(false);
    HttpResponse httpResponse = requestPipeline.execute(signedRequest);
    assertEquals(CACHEABLE, httpResponse);
    assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize());

    // Invalidate by owner only
    service.invalidateUserResources(ImmutableSet.of("OwnerX"), appxToken);

    oauth.httpResponse =
        new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT1").create();
    httpResponse = requestPipeline.execute(signedRequest);
    assertEquals("NEWCONTENT1", httpResponse.getResponseAsString());
    assertEquals("o=1;", httpResponse.getHeader(DefaultInvalidationService.INVALIDATION_HEADER));
    assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize());

    // Invalidating viewer has no effect
    service.invalidateUserResources(ImmutableSet.of("ViewerX"), appxToken);
    oauth.httpResponse =
        new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT2").create();
    httpResponse = requestPipeline.execute(signedRequest);
    assertEquals("NEWCONTENT1", httpResponse.getResponseAsString());
    assertEquals("o=1;", httpResponse.getHeader(DefaultInvalidationService.INVALIDATION_HEADER));
    assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize());
  }
Example #8
0
  @Test
  public void testAssignNoVetoes() throws Exception {
    expect(offerManager.getOffers(GROUP_KEY)).andReturn(ImmutableSet.of(OFFER));
    offerManager.launchTask(MESOS_OFFER.getId(), TASK_INFO);
    expect(tierManager.getTier(TASK.getAssignedTask().getTask())).andReturn(DEFAULT);
    expect(filter.filter(UNUSED, RESOURCE_REQUEST)).andReturn(ImmutableSet.of());
    expect(
            stateManager.assignTask(
                storeProvider,
                Tasks.id(TASK),
                MESOS_OFFER.getHostname(),
                MESOS_OFFER.getSlaveId(),
                ImmutableMap.of(PORT_NAME, PORT)))
        .andReturn(TASK.getAssignedTask());
    expect(taskFactory.createFrom(TASK.getAssignedTask(), MESOS_OFFER.getSlaveId()))
        .andReturn(TASK_INFO);

    control.replay();

    assertTrue(
        assigner.maybeAssign(
            storeProvider,
            new ResourceRequest(TASK.getAssignedTask().getTask(), EMPTY),
            TaskGroupKey.from(TASK.getAssignedTask().getTask()),
            Tasks.id(TASK),
            ImmutableMap.of(SLAVE_ID, GROUP_KEY)));
  }
Example #9
0
  @Test
  public void testAssignmentClearedOnError() throws Exception {
    expect(offerManager.getOffers(GROUP_KEY)).andReturn(ImmutableSet.of(OFFER));
    offerManager.launchTask(MESOS_OFFER.getId(), TASK_INFO);
    expectLastCall().andThrow(new OfferManager.LaunchException("expected"));
    expect(tierManager.getTier(TASK.getAssignedTask().getTask())).andReturn(DEFAULT);
    expect(filter.filter(UNUSED, RESOURCE_REQUEST)).andReturn(ImmutableSet.of());
    expect(
            stateManager.assignTask(
                storeProvider,
                Tasks.id(TASK),
                MESOS_OFFER.getHostname(),
                MESOS_OFFER.getSlaveId(),
                ImmutableMap.of(PORT_NAME, PORT)))
        .andReturn(TASK.getAssignedTask());
    expect(
            stateManager.changeState(
                storeProvider, Tasks.id(TASK), Optional.of(PENDING), LOST, LAUNCH_FAILED_MSG))
        .andReturn(StateChangeResult.SUCCESS);
    expect(taskFactory.createFrom(TASK.getAssignedTask(), MESOS_OFFER.getSlaveId()))
        .andReturn(TASK_INFO);

    control.replay();

    assertFalse(
        assigner.maybeAssign(
            storeProvider,
            new ResourceRequest(TASK.getAssignedTask().getTask(), EMPTY),
            TaskGroupKey.from(TASK.getAssignedTask().getTask()),
            Tasks.id(TASK),
            NO_RESERVATION));
  }
  @Test
  public void testWhenComputeServiceSaysAllNodesAreDeadBothGroupsAreReturned() {

    ServerInZone withoutHost =
        new ServerInZone(
            new ServerInZoneToNodeMetadataTest().expectedServer(), "az-1.region-a.geo-1");
    ServerInZone withHost =
        new ServerInZone(new ParseServerTest().expected(), "az-1.region-a.geo-1");

    ServerInZoneToNodeMetadata converter =
        new ServerInZoneToNodeMetadata(
            NovaComputeServiceContextModule.toPortableNodeStatus,
            locationIndex,
            Suppliers.<Set<? extends Image>>ofInstance(ImmutableSet.<Image>of()),
            Suppliers.<Set<? extends Hardware>>ofInstance(ImmutableSet.<Hardware>of()),
            namingConvention);

    Set<? extends NodeMetadata> set =
        ImmutableSet.of(converter.apply(withHost), converter.apply(withoutHost));

    assertEquals(
        new OrphanedGroupsByZoneId(Predicates.<ZoneAndName>alwaysTrue()).apply(set),
        ImmutableMultimap.<String, String>builder()
            .putAll("az-1.region-a.geo-1", "sample", "test")
            .build());
  }
Example #11
0
  @Test(groups = "slow")
  public void testPermissions() throws Exception {
    logout();

    try {
      killBillClient.getPermissions();
      Assert.fail();
    } catch (final KillBillClientException e) {
      Assert.assertEquals(e.getResponse().getStatusCode(), Status.UNAUTHORIZED.getStatusCode());
    }

    // See src/test/resources/shiro.ini

    final List<String> pierresPermissions = getPermissions("pierre", "password");
    Assert.assertEquals(pierresPermissions.size(), 2);
    Assert.assertEquals(
        new HashSet<String>(pierresPermissions),
        ImmutableSet.<String>of(
            Permission.INVOICE_CAN_CREDIT.toString(),
            Permission.INVOICE_CAN_ITEM_ADJUST.toString()));

    final List<String> stephanesPermissions = getPermissions("stephane", "password");
    Assert.assertEquals(stephanesPermissions.size(), 1);
    Assert.assertEquals(
        new HashSet<String>(stephanesPermissions),
        ImmutableSet.<String>of(Permission.PAYMENT_CAN_REFUND.toString()));
  }
  @Test
  public void test() {
    ChefClient chef = createMock(ChefClient.class);

    Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall>of();

    Node node = new Node("name", ImmutableSet.<String>of());

    Supplier<Map<String, JsonBall>> automaticSupplier =
        Suppliers.<Map<String, JsonBall>>ofInstance(automatic);

    Node nodeWithAutomatic =
        new Node(
            "name",
            ImmutableMap.<String, JsonBall>of(),
            ImmutableMap.<String, JsonBall>of(),
            ImmutableMap.<String, JsonBall>of(),
            automatic,
            ImmutableSet.<String>of());

    expect(chef.getNode("name")).andReturn(node);
    node.getAutomatic().putAll(automaticSupplier.get());
    expect(chef.updateNode(nodeWithAutomatic)).andReturn(null);

    replay(chef);

    UpdateAutomaticAttributesOnNodeImpl updater =
        new UpdateAutomaticAttributesOnNodeImpl(chef, automaticSupplier);

    updater.execute("name");
    verify(chef);
  }
Example #13
0
 @ConstructorProperties({
   "id",
   "creationTimestamp",
   "selfLink",
   "name",
   "description",
   "status",
   "maintenanceWindows",
   "availableMachineTypes"
 })
 private Zone(
     String id,
     Date creationTimestamp,
     URI selfLink,
     String name,
     String description,
     Status status,
     Set<MaintenanceWindow> maintenanceWindows,
     Set<String> availableMachineTypes) {
   super(Kind.ZONE, id, creationTimestamp, selfLink, name, description);
   this.status = checkNotNull(status, "status of %name", name);
   this.maintenanceWindows =
       maintenanceWindows == null
           ? ImmutableSet.<MaintenanceWindow>of()
           : ImmutableSet.copyOf(maintenanceWindows);
   this.availableMachineTypes =
       availableMachineTypes == null
           ? ImmutableSet.<String>of()
           : ImmutableSet.copyOf(availableMachineTypes);
 }
  @Test
  public void processesExternModules() throws IOException {
    Path extern = path("root/externs/xml.js");
    Path module = path("root/source/foo.js");

    createDirectories(extern.getParent());
    write(
        extern,
        lines(
                "/** @const */",
                "var xml = {};",
                "/** @param {string} str",
                " *  @return {!Object}",
                " */",
                "xml.parse = function(str) {};",
                "module.exports = xml;")
            .getBytes(StandardCharsets.UTF_8));

    CompilerUtil compiler = createCompiler(ImmutableSet.of(extern), ImmutableSet.of(module));
    compiler.compile(module, "var xml = require('xml');", "xml.parse('abc');");

    assertThat(compiler.toSource())
        .contains(
            lines(
                "var xml = $jscomp.scope.xml_module;",
                "var module$root$source$foo = {};",
                "$jscomp.scope.xml_module.parse(\"abc\");"));
  }
  @Test
  public void testNoHosts() throws Exception {
    assertEquals(ImmutableSet.of(), getGroupMonitor().get());

    startGroupMonitor();
    assertEquals(ImmutableSet.of(), getGroupMonitor().get());
  }
  @Test
  public void testApplyWhereImageFoundAndHardwareNotFound()
      throws UnknownHostException, NoSuchMethodException, ClassNotFoundException,
          URISyntaxException {
    Map<ServerStatus, Status> serverStateToNodeStatus =
        NovaComputeServiceContextModule.serverToNodeStatus;
    org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage();
    Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
    Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
    Server server = ParseServerFromJsonResponseTest.parseServer();

    ServerToNodeMetadata parser =
        new ServerToNodeMetadata(
            serverStateToNodeStatus,
            Suppliers.<Set<? extends Image>>ofInstance(images),
            Suppliers.ofInstance(provider),
            Suppliers.<Set<? extends Hardware>>ofInstance(hardwares),
            namingConvention);

    NodeMetadata metadata = parser.apply(server);

    NodeMetadata constructedMetadata =
        newNodeMetadataBuilder()
            .imageId("2")
            .operatingSystem(
                new OperatingSystem.Builder()
                    .family(OsFamily.CENTOS)
                    .description("CentOS 5.2")
                    .version("5.2")
                    .is64Bit(true)
                    .build())
            .build();

    assertEquals(metadata, constructedMetadata);
  }
  /**
   * In devstack and going forward, namespaces are being deprecated. When namespace is missing (or
   * replaced with a "fake" /fake namespace), allow matching by name and alias.
   */
  public void testPresentWhenNameSpaceIsFakeAndMatchByNameOrAlias()
      throws SecurityException, NoSuchMethodException {
    // Revert to alias
    Extension floatingIpsWithFakeNamespace =
        floatingIps.toBuilder().namespace(URI.create("http://docs.openstack.org/ext/fake")).build();

    // Revert to name
    Extension floatingIpsWithFakeNamespaceAndAlias =
        floatingIps
            .toBuilder()
            .namespace(URI.create("http://docs.openstack.org/ext/fake"))
            .alias("fake")
            .build();

    Multimap<URI, URI> aliases = ImmutableMultimap.of();

    assertEquals(
        whenExtensionsAndAliasesInRegionInclude(
                "region", ImmutableSet.of(floatingIpsWithFakeNamespace), aliases)
            .apply(getFloatingIPExtension(ImmutableList.<Object>of("region"))),
        Optional.of("foo"));

    assertEquals(
        whenExtensionsAndAliasesInRegionInclude(
                "region", ImmutableSet.of(floatingIpsWithFakeNamespaceAndAlias), aliases)
            .apply(getFloatingIPExtension(ImmutableList.<Object>of("region"))),
        Optional.of("foo"));
  }
 @Test
 public void testInvalidRecursivePkgKeys() throws Exception {
   invalidHelper(new PathFragment(""), ImmutableSet.of(new PathFragment("")));
   invalidHelper(new PathFragment("a"), ImmutableSet.of(new PathFragment("a")));
   invalidHelper(new PathFragment("a"), ImmutableSet.of(new PathFragment("b")));
   invalidHelper(new PathFragment("a/b"), ImmutableSet.of(new PathFragment("a")));
 }
  @Test
  public void testFetchContentWithMarker() throws Exception {
    oauth.httpResponse = CACHEABLE;

    // First entry added to cache is unmarked
    HttpResponse httpResponse = requestPipeline.execute(signedRequest);
    assertEquals(CACHEABLE, httpResponse);
    assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize());

    // Invalidate content for OwnerX. Next entry will have owner mark
    service.invalidateUserResources(ImmutableSet.of("OwnerX"), appxToken);

    oauth.httpResponse =
        new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT1").create();
    httpResponse = requestPipeline.execute(signedRequest);
    assertEquals("NEWCONTENT1", httpResponse.getResponseAsString());
    assertEquals("o=1;", httpResponse.getHeader(DefaultInvalidationService.INVALIDATION_HEADER));
    assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize());

    // Invalidate content for ViewerX. Next entry will have both owner and viewer mark
    service.invalidateUserResources(ImmutableSet.of("ViewerX"), appxToken);
    oauth.httpResponse =
        new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT2").create();
    httpResponse = requestPipeline.execute(signedRequest);
    assertEquals("NEWCONTENT2", httpResponse.getResponseAsString());
    assertEquals(
        "o=1;v=2;", httpResponse.getHeader(DefaultInvalidationService.INVALIDATION_HEADER));
    assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize());
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    LocalWaveletContainer.Factory localFactory = mock(LocalWaveletContainer.Factory.class);

    WaveletNotificationSubscriber notifiee = mock(WaveletNotificationSubscriber.class);

    SettableFuture<ImmutableSet<WaveletId>> lookedupWavelets = SettableFuture.create();
    lookedupWavelets.set(ImmutableSet.of(WAVELET_NAME.waveletId));

    Wave wave =
        new Wave(
            WAVELET_NAME.waveId,
            lookedupWavelets,
            notifiee,
            localFactory,
            null,
            WAVELET_NAME.waveId.getDomain());
    Map<WaveId, Wave> waves = Maps.newHashMap();
    waves.put(WAVELET_NAME.waveId, wave);
    when(waveMap.getWaves()).thenReturn(waves);
    ImmutableSet<WaveletId> wavelets = ImmutableSet.of(WAVELET_NAME.waveletId);
    when(waveMap.lookupWavelets(WAVELET_NAME.waveId)).thenReturn(wavelets);

    LocalWaveletContainer c = mock(LocalWaveletContainer.class);
    when(c.hasParticipant(PARTICIPANT)).thenReturn(true);
    when(waveMap.getLocalWavelet(WAVELET_NAME)).thenReturn(c);
  }
Example #21
0
  @Test
  public void testListTables() {
    // all schemas
    assertEquals(
        ImmutableSet.copyOf(metadata.listTables(SESSION, null)),
        ImmutableSet.of(
            new SchemaTableName("example", "numbers"),
            new SchemaTableName("example", "view_source"),
            new SchemaTableName("example", "view"),
            new SchemaTableName("tpch", "orders"),
            new SchemaTableName("tpch", "lineitem"),
            new SchemaTableName("exa_ple", "num_ers")));

    // specific schema
    assertEquals(
        ImmutableSet.copyOf(metadata.listTables(SESSION, "example")),
        ImmutableSet.of(
            new SchemaTableName("example", "numbers"),
            new SchemaTableName("example", "view_source"),
            new SchemaTableName("example", "view")));
    assertEquals(
        ImmutableSet.copyOf(metadata.listTables(SESSION, "tpch")),
        ImmutableSet.of(
            new SchemaTableName("tpch", "orders"), new SchemaTableName("tpch", "lineitem")));
    assertEquals(
        ImmutableSet.copyOf(metadata.listTables(SESSION, "exa_ple")),
        ImmutableSet.of(new SchemaTableName("exa_ple", "num_ers")));

    // unknown schema
    assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, "unknown")), ImmutableSet.of());
  }
  @Test
  public void setContains() {
    check(ImmutableOrdinalSet.of(b0, b1).containsAll(ImmutableOrdinalSet.of(b0)));
    check(ImmutableOrdinalSet.of(b0, b1).containsAll(ImmutableOrdinalSet.of(b0, b1)));

    check(ImmutableOrdinalSet.of(b0, b1).containsAny(ImmutableOrdinalSet.of(b0)));
    check(ImmutableOrdinalSet.of(b1).containsAny(ImmutableOrdinalSet.of(b0, b1)));
    check(ImmutableOrdinalSet.of(b0, b1).containsAny(ImmutableOrdinalSet.of(b0, b1)));
    check(!ImmutableOrdinalSet.of().containsAny(ImmutableOrdinalSet.of(b0, b1)));

    check(!ImmutableOrdinalSet.of(b0, b1).containsAll(ImmutableOrdinalSet.of(a0, a1)));

    check(
        !ImmutableOrdinalSet.of(b0, b1)
            .containsAll(ImmutableOrdinalSet.of(db.get(120), db.get(130))));

    check(
        !ImmutableOrdinalSet.of(db.get(30), db.get(70))
            .containsAll(ImmutableOrdinalSet.of(db.get(30), db.get(60))));

    check(ImmutableOrdinalSet.of(b0, b1)).hasAll(b0);
    check(ImmutableOrdinalSet.of(b0, b1)).not().hasAll(a0, a1);
    check(ImmutableOrdinalSet.of(b0, b1)).not().hasAll(b0, a1);
    check(ImmutableOrdinalSet.of(b0, b1)).not().has(a1);

    check(ImmutableOrdinalSet.of(b0, b1).containsAll(ImmutableSet.of()));
    check(ImmutableOrdinalSet.of(b0, b1).containsAll(ImmutableSet.of(b0, b1)));
    check(!ImmutableOrdinalSet.of(b0, b1).contains(1));
    check(!ImmutableOrdinalSet.of(b0, b1).containsAll(ImmutableSet.of(0, 1)));
  }
  @Test
  public void testGetJobUpdateDiffWithUpdateRemove() throws Exception {
    TaskConfig task1 = defaultTask(false).setNumCpus(1.0);
    TaskConfig task2 = defaultTask(false).setNumCpus(2.0);
    TaskConfig task3 = defaultTask(false).setNumCpus(3.0);

    ImmutableSet.Builder<IScheduledTask> tasks = ImmutableSet.builder();
    makeTasks(0, 10, task1, tasks);
    makeTasks(10, 20, task2, tasks);
    makeTasks(20, 30, task3, tasks);

    expect(storageUtil.jobStore.fetchJob(JOB_KEY)).andReturn(Optional.absent());
    storageUtil.expectTaskFetch(Query.jobScoped(JOB_KEY).active(), tasks.build());

    control.replay();

    JobUpdateRequest request =
        new JobUpdateRequest()
            .setTaskConfig(defaultTask(false).setNumCpus(6.0))
            .setInstanceCount(20)
            .setSettings(new JobUpdateSettings());

    GetJobUpdateDiffResult expected =
        new GetJobUpdateDiffResult()
            .setRemove(ImmutableSet.of(group(task3, new Range(20, 29))))
            .setUpdate(
                ImmutableSet.of(group(task1, new Range(0, 9)), group(task2, new Range(10, 19))))
            .setAdd(ImmutableSet.of())
            .setUnchanged(ImmutableSet.of());

    Response response = assertOkResponse(thrift.getJobUpdateDiff(request));
    assertEquals(expected, response.getResult().getGetJobUpdateDiffResult());
  }
Example #24
0
 protected Instance(
     String id,
     Date creationTimestamp,
     URI selfLink,
     String name,
     String description,
     Tags tags,
     URI machineType,
     Status status,
     String statusMessage,
     URI zone,
     Set<NetworkInterface> networkInterfaces,
     Set<AttachedDisk> disks,
     Metadata metadata,
     Set<ServiceAccount> serviceAccounts) {
   super(Kind.INSTANCE, id, creationTimestamp, selfLink, name, description);
   this.tags = checkNotNull(tags, "tags");
   this.machineType = checkNotNull(machineType, "machineType of %s", name);
   this.status = checkNotNull(status, "status");
   this.statusMessage = fromNullable(statusMessage);
   this.zone = checkNotNull(zone, "zone of %s", name);
   this.networkInterfaces =
       networkInterfaces == null ? ImmutableSet.<NetworkInterface>of() : networkInterfaces;
   this.disks = disks == null ? ImmutableSet.<AttachedDisk>of() : disks;
   this.metadata = checkNotNull(metadata, "metadata");
   this.serviceAccounts =
       serviceAccounts == null ? ImmutableSet.<ServiceAccount>of() : serviceAccounts;
 }
  @Test
  public void testUpdate() throws Exception {
    HierarchicalTypeDefinition<ClassType> typeDefinition =
        TypesUtil.createClassTypeDef(
            randomString(),
            ImmutableSet.<String>of(),
            TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE));
    List<String> typesCreated =
        serviceClient.createType(TypesSerialization.toJson(typeDefinition, false));
    assertEquals(typesCreated.size(), 1);
    assertEquals(typesCreated.get(0), typeDefinition.typeName);

    // Add attribute description
    typeDefinition =
        TypesUtil.createClassTypeDef(
            typeDefinition.typeName,
            ImmutableSet.<String>of(),
            TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE),
            createOptionalAttrDef("description", DataTypes.STRING_TYPE));
    TypesDef typeDef =
        TypesUtil.getTypesDef(
            ImmutableList.<EnumTypeDefinition>of(),
            ImmutableList.<StructTypeDefinition>of(),
            ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(),
            ImmutableList.of(typeDefinition));
    List<String> typesUpdated = serviceClient.updateType(typeDef);
    assertEquals(typesUpdated.size(), 1);
    Assert.assertTrue(typesUpdated.contains(typeDefinition.typeName));

    HierarchicalTypeDefinition<ClassType> updatedType =
        serviceClient.getType(typeDefinition.typeName).classTypesAsJavaList().get(0);
    assertEquals(updatedType.attributeDefinitions.length, 2);
  }
 @Test
 public void shouldInsertOptionalConsonant() {
   final SuffixFormSequence.SuffixFormSequenceRuleType RULE_TYPE =
       SuffixFormSequence.SuffixFormSequenceRuleType.INSERT_OPTIONAL_CONSONANT;
   {
     final SuffixFormSequence.SuffixFormSequenceRule rule =
         new SuffixFormSequenceRuleStub('k', RULE_TYPE);
     ImmutableSet<PhoneticAttribute> phoneticAttributes = ImmutableSet.of();
     assertThat(applier.apply(rule, phoneticAttributes), nullValue());
   }
   {
     final SuffixFormSequence.SuffixFormSequenceRule rule =
         new SuffixFormSequenceRuleStub('l', RULE_TYPE);
     ImmutableSet<PhoneticAttribute> phoneticAttributes =
         ImmutableSet.of(PhoneticAttribute.LastLetterConsonant);
     assertThat(applier.apply(rule, phoneticAttributes), nullValue());
   }
   {
     final SuffixFormSequence.SuffixFormSequenceRule rule =
         new SuffixFormSequenceRuleStub('m', RULE_TYPE);
     ImmutableSet<PhoneticAttribute> phoneticAttributes =
         ImmutableSet.of(PhoneticAttribute.LastLetterVowel);
     assertThat(applier.apply(rule, phoneticAttributes), equalTo('m'));
   }
 }
  private List<HierarchicalTypeDefinition> createHiveTypes() throws Exception {
    ArrayList<HierarchicalTypeDefinition> typeDefinitions = new ArrayList<>();

    HierarchicalTypeDefinition<ClassType> databaseTypeDefinition =
        TypesUtil.createClassTypeDef(
            "database",
            ImmutableSet.<String>of(),
            TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE),
            TypesUtil.createRequiredAttrDef("description", DataTypes.STRING_TYPE));
    typeDefinitions.add(databaseTypeDefinition);

    HierarchicalTypeDefinition<ClassType> tableTypeDefinition =
        TypesUtil.createClassTypeDef(
            "table",
            ImmutableSet.<String>of(),
            TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE),
            TypesUtil.createRequiredAttrDef("description", DataTypes.STRING_TYPE),
            createOptionalAttrDef("columnNames", DataTypes.arrayTypeName(DataTypes.STRING_TYPE)),
            createOptionalAttrDef("created", DataTypes.DATE_TYPE),
            createOptionalAttrDef(
                "parameters", DataTypes.mapTypeName(DataTypes.STRING_TYPE, DataTypes.STRING_TYPE)),
            TypesUtil.createRequiredAttrDef("type", DataTypes.STRING_TYPE),
            new AttributeDefinition(
                "database", "database", Multiplicity.REQUIRED, false, "database"));
    typeDefinitions.add(tableTypeDefinition);

    HierarchicalTypeDefinition<TraitType> fetlTypeDefinition =
        TypesUtil.createTraitTypeDef(
            "fetl",
            ImmutableSet.<String>of(),
            TypesUtil.createRequiredAttrDef("level", DataTypes.INT_TYPE));
    typeDefinitions.add(fetlTypeDefinition);

    return typeDefinitions;
  }
 @Test
 public void shouldInsertVowel_A_WithHarmony() {
   final SuffixFormSequence.SuffixFormSequenceRuleType RULE_TYPE =
       SuffixFormSequence.SuffixFormSequenceRuleType.INSERT_VOWEL_A_WITH_HARMONY;
   {
     final SuffixFormSequence.SuffixFormSequenceRule rule =
         new SuffixFormSequenceRuleStub(RULE_TYPE);
     ImmutableSet<PhoneticAttribute> phoneticAttributes = ImmutableSet.of();
     assertThat(applier.apply(rule, phoneticAttributes), equalTo('a'));
   }
   {
     final SuffixFormSequence.SuffixFormSequenceRule rule =
         new SuffixFormSequenceRuleStub(RULE_TYPE);
     ImmutableSet<PhoneticAttribute> phoneticAttributes =
         ImmutableSet.of(PhoneticAttribute.LastVowelBack);
     assertThat(applier.apply(rule, phoneticAttributes), equalTo('a'));
   }
   {
     final SuffixFormSequence.SuffixFormSequenceRule rule =
         new SuffixFormSequenceRuleStub(RULE_TYPE);
     ImmutableSet<PhoneticAttribute> phoneticAttributes =
         ImmutableSet.of(PhoneticAttribute.LastVowelFrontal);
     assertThat(applier.apply(rule, phoneticAttributes), equalTo('e'));
   }
 }
  public void test_presentValue() {
    Currency ccy1 = TRADE.getProduct().getNonDeliverableCurrency();
    Currency ccy2 = TRADE.getProduct().getSettlementCurrency();
    LocalDate valDate = TRADE.getProduct().getPaymentDate().plusDays(7);

    FunctionConfig<FxNdfTrade> config =
        FxNdfFunctionGroups.discounting().functionConfig(TRADE, Measure.PRESENT_VALUE).get();
    CalculationSingleFunction<FxNdfTrade, ?> function = config.createFunction();
    FunctionRequirements reqs = function.requirements(TRADE);
    assertThat(reqs.getOutputCurrencies()).containsOnly(ccy1, ccy2);
    assertThat(reqs.getSingleValueRequirements())
        .isEqualTo(ImmutableSet.of(DiscountCurveKey.of(ccy1), DiscountCurveKey.of(ccy2)));
    assertThat(reqs.getTimeSeriesRequirements()).isEqualTo(ImmutableSet.of());
    assertThat(function.defaultReportingCurrency(TRADE)).hasValue(GBP);
    DiscountFactors df1 =
        SimpleDiscountFactors.of(
            ccy1, valDate, ConstantNodalCurve.of(Curves.discountFactors("Test", ACT_360), 0.99));
    DiscountFactors df2 =
        SimpleDiscountFactors.of(
            ccy2, valDate, ConstantNodalCurve.of(Curves.discountFactors("Test", ACT_360), 0.99));
    TestMarketDataMap md =
        new TestMarketDataMap(
            valDate,
            ImmutableMap.of(DiscountCurveKey.of(ccy1), df1, DiscountCurveKey.of(ccy2), df2),
            ImmutableMap.of());
    assertThat(function.execute(TRADE, md))
        .isEqualTo(FxConvertibleList.of(ImmutableList.of(CurrencyAmount.zero(GBP))));
  }
Example #30
0
 public void testPowerSetEmpty() {
   ImmutableSet<Integer> elements = ImmutableSet.of();
   Set<Set<Integer>> powerSet = powerSet(elements);
   assertEquals(1, powerSet.size());
   assertEquals(ImmutableSet.of(ImmutableSet.of()), powerSet);
   assertEquals(0, powerSet.hashCode());
 }