Exemple #1
1
  protected void assertCreateUserFromLdap(Fixture fixture, Map<String, List<String>> users) {
    LdapImpl ldap = fixture.ldap;
    for (String user : users.keySet()) {
      String dn = null;
      try {
        dn = ldap.findDN(user);
      } catch (ApiUsageException aue) {
        throw aue;
      }

      assertNotNull(dn);
      assertEquals(
          fixture.ignoreCaseLookup ? user.toLowerCase() : user,
          ldap.findExperimenter(user).getOmeName());
      fixture.createUserWithGroup(this, dn, users.get(user).get(0));
      assertNotNull(fixture.createUser(user));
      try {
        fixture.createUser("nonExistingUserShouldNotBeCreated");
      } catch (ApiUsageException aue) {
        // Expected
        continue;
      }
      fail("This user shouldn't have been created!");
    }
  }
Exemple #2
0
 protected void assertFails(Fixture fixture, Map<String, List<String>> users) {
   LdapImpl ldap = fixture.ldap;
   for (String user : users.keySet()) {
     assertEquals(1, users.get(user).size());
     try {
       String dn = ldap.findDN(user);
       assertNotNull(dn);
       fixture.createUserWithGroup(this, dn, users.get(user).get(0));
       assertNotNull(fixture.createUser(user, "password", true));
       fixture.login(user, users.get(user).get(0), "password");
       // Parsing afterwards to force an explosion to reproduce #2557
       assertEquals(user, ldap.findExperimenter(user).getOmeName());
       fail("user didn't fail");
     } catch (ValidationException e) {
       if (e.getMessage().equals("No group found for: cn=user,ou=attributeFilter")) {
         // Good. This is the expected result for #8357
       } else {
         throw e;
         // This means that we couldn't insert.
         // See the thread on case-sensitivity in #2557
       }
     } catch (ApiUsageException e) {
       // If not a ValidationException, but otherwise an
       // ApiUsageException, then this will be the
       // "Cannot find unique DN" which we are looking for.
     } catch (SecurityViolation sv) {
       // e.g. User 466 is not a member of group 54 and cannot login
       // Also good.
     }
   }
 }
Exemple #3
0
  public void setup() throws Exception {
    project = new ProjectAlpha("projectAlpha");
    releases = new ProjectBetaReleases("projectBeta-releases");

    // create one branch off of master; add a library only on the branch
    WithCwd wd = new WithCwd(project.getRepo().getWorkTree());
    {
      // add a library on the branch.
      git.args("checkout", "-b", "blue").start().get();
      assertJoy(
          Mdm.run(
              "add", releases.getRepo().getWorkTree().toString(), "--version=v1.0", "--name=beta"));

      // switch back to master
      git.args("checkout", "master").start().get();

      // make one more commit just so it's not a degenerate fast-forward merge this direction
      IOForge.saveFile("asdf", new File("somefile").getCanonicalFile());
      git.args("add", "--", "somefile").start().get();
      git.args("commit", "-m", "somecommit").start().get();

      // remove the library from the working tree.
      // this is a cheap way to force any mdm-update invocations to take the long road through
      // fetch.
      IOForge.delete(new File("lib").getCanonicalFile());
    }
    wd.close();
  }
Exemple #4
0
 private static String[] getNamesByAnnotation(Method method) {
   Fixture annotation = method.getAnnotation(Fixture.class);
   if (annotation == null) {
     return null;
   }
   return annotation.value();
 }
Exemple #5
0
 public void setDirtsActive(boolean dirtsActive) {
   this.dirtsActive = dirtsActive;
   for (Fixture fixture : dirts) {
     // fixture.setSensor(dirtsActive);
     fixture.getBody().setActive(dirtsActive);
   }
 }
 public void testAddAttachment() {
   try {
     String sampleProcessId = "150001"; // replace this with a valid id
     IBPMContext ctx = Fixture.getIBPMContext("pino", "password1");
     IInstanceQueryService queryService = Fixture.getBPMServiceClient().getInstanceQueryService();
     IProcessInstance instance = queryService.getProcessInstance(ctx, sampleProcessId);
     IInstanceManagementService service =
         Fixture.getBPMServiceClient().getInstanceManagementService();
     IProcessComment comment = new ProcessComment();
     IIdentityType identity = new IdentityType();
     identity.setDisplayName(ctx.getUser());
     identity.setId(ctx.getUser());
     identity.setType("user");
     comment.setUpdatedBy(identity);
     comment.setComment("my programmatic comment5");
     comment.setUpdatedDate(Calendar.getInstance());
     service.addComment(ctx, instance, comment);
     // check if persisted
     IProcessInstance updatedInstance = queryService.getProcessInstance(ctx, sampleProcessId);
     List<IProcessComment> comments = updatedInstance.getUserComment();
     for (IProcessComment c : comments) {
       System.out.println(c.getComment()); // the new comment should appear
     }
   } catch (BPMServiceClientException bpmsce) {
     // TODO: Add catch code
     bpmsce.printStackTrace();
   } catch (BPMException bpme) {
     // TODO: Add catch code
     bpme.printStackTrace();
   } catch (Exception e) {
     // TODO: Add catch code
     e.printStackTrace();
   }
 }
Exemple #7
0
  @Test
  public void merge_a_branch_without_a_dep() throws Exception {
    setup();

    // do a merges.
    WithCwd wd = new WithCwd(project.getRepo().getWorkTree());
    {
      // switch to the branch with the lib
      git.args("checkout", "blue").start().get();

      // merge the master branch, which doesn't have the lib yet
      git.args("merge", "--no-ff", "master").start().get();

      // that should have just committed cleanly, that's it
    }
    wd.close();

    // now verify.
    File depWorkTreePath =
        new File(project.getRepo().getWorkTree() + "/lib/beta").getCanonicalFile();
    File depGitDataPath =
        new File(project.getRepo().getDirectory() + "/modules/lib/beta").getCanonicalFile();

    // i do hope there's a filesystem there now
    assertTrue("dependency module path exists on fs", depWorkTreePath.exists());
    assertTrue("dependency module path is dir", depWorkTreePath.isDirectory());

    // check that anyone else can read this state with a straight face; status should be clean
    new Josh("git")
        .args("status")
        .cwd(project.getRepo().getWorkTree()) /*.opts(Opts.NullIO)*/
        .start()
        .get();
    new Josh("git").args("status").cwd(depWorkTreePath) /*.opts(Opts.NullIO)*/.start().get();
  }
  @Test
  public void testOutsideTollTime() {
    Config config = matsimTestUtils.loadConfig(null);
    MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config);
    Fixture.createNetwork2(scenario);

    // a basic toll where only the morning hours are tolled
    RoadPricingSchemeImpl toll = new RoadPricingSchemeImpl();
    toll.setType("area");
    toll.addLink(Id.createLinkId("5"));
    toll.addLink(Id.createLinkId("11"));
    toll.addCost(8 * 3600, 10 * 3600, 1.0); // high costs!

    Fixture.createPopulation2(scenario);
    Population population = scenario.getPopulation();

    runOnAll(testee(scenario, toll), population);
    Id id1 = Id.createPersonId("1");
    LegImpl leg1 = getLeg1(population, id1);
    LegImpl leg2 = getLeg3(population, id1);

    Fixture.compareRoutes(
        "2 5 6",
        (NetworkRoute)
            leg1
                .getRoute()); // agent should take shortest route, as tolls are not active at that
                              // time
    Fixture.compareRoutes("8 11 12", (NetworkRoute) leg2.getRoute());
  }
Exemple #9
0
  /**
   * Tests the setup with a traffic light that shows all the time green in the 0th iteration. After
   * the mobsim is run the signal settings are changed thus in the 1st iteration the signal should
   * be red in sec [0,99] and green in [100,2000]
   */
  @Test
  public void testModifySignalControlDataOnsetOffset() {
    // configure and load standard scenario
    Fixture fixture = new Fixture();
    Scenario scenario = fixture.createAndLoadTestScenario(false);
    scenario.getConfig().controler().setFirstIteration(0);
    scenario.getConfig().controler().setLastIteration(1);
    scenario.getConfig().controler().setOutputDirectory(testUtils.getOutputDirectory());

    Controler controler = new Controler(scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler.addControlerListener(
        new AfterMobsimListener() {

          @Override
          public void notifyAfterMobsim(AfterMobsimEvent event) {
            Scenario scenario = event.getServices().getScenario();
            int dropping = 0;
            int onset = 100;
            for (SignalSystemControllerData intersectionSignal :
                ((SignalsData) scenario.getScenarioElement(SignalsData.ELEMENT_NAME))
                    .getSignalControlData()
                    .getSignalSystemControllerDataBySystemId()
                    .values()) {

              for (SignalPlanData plan : intersectionSignal.getSignalPlanData().values()) {
                plan.setCycleTime(2000);
                for (SignalGroupSettingsData data :
                    plan.getSignalGroupSettingsDataByGroupId().values()) {
                  data.setDropping(dropping);
                  data.setOnset(onset);
                }
              }
            }
          }
        });

    controler.addControlerListener(
        new IterationStartsListener() {

          @Override
          public void notifyIterationStarts(IterationStartsEvent event) {
            event.getServices().getEvents().addHandler(new EventsLogger());

            TestLink2EnterEventHandler enterHandler = new TestLink2EnterEventHandler();
            if (0 == event.getIteration()) {
              enterHandler.link2EnterTime = 38.0;
            }

            if (1 == event.getIteration()) {
              enterHandler.link2EnterTime = 100.0;
              SignalGroupStateChangedEventHandler signalsHandler0 =
                  new TestSignalGroupStateChangedHandler();
              event.getServices().getEvents().addHandler(signalsHandler0);
            }
          }
        });

    controler.run();
  }
Exemple #10
0
  protected void assertPasses(Fixture fixture, Map<String, List<String>> users) throws Exception {
    LdapImpl ldap = fixture.ldap;

    for (String user : users.keySet()) {
      String dn = null;
      assertTrue(1 <= users.get(user).size());
      try {
        dn = ldap.findDN(user);
      } catch (ApiUsageException aue) {
        // This will be one of the major errors: when we can't find a
        // user that we expect to find. Adding a try/catch block for
        // debugging purposes.
        throw aue;
      }

      assertNotNull(dn);
      assertEquals(
          fixture.ignoreCaseLookup ? user.toLowerCase() : user,
          ldap.findExperimenter(user).getOmeName());
      fixture.createUserWithGroup(this, dn, users.get(user).get(0));
      assertNotNull(fixture.createUser(user, "password", true));
      fixture.login(
          fixture.ignoreCaseLookup ? user.toLowerCase() : user, users.get(user).get(0), "password");
    }
  }
Exemple #11
0
  protected Fixture createFixture(File ctxFile) throws Exception {
    Fixture fixture = new Fixture();
    fixture.ctx = new FileSystemXmlApplicationContext("file:" + ctxFile.getAbsolutePath());
    fixture.config = (LdapConfig) fixture.ctx.getBean("config");

    Map<String, LdapContextSource> sources = fixture.ctx.getBeansOfType(LdapContextSource.class);

    LdapContextSource source = sources.values().iterator().next();
    String[] urls = source.getUrls();
    assertEquals(1, urls.length);

    fixture.template = new LdapTemplate(source);

    fixture.role = mock(RoleProvider.class);
    RoleProvider provider = (RoleProvider) fixture.role.proxy();

    fixture.sql = mock(SqlAction.class);
    SqlAction sql = (SqlAction) fixture.sql.proxy();

    fixture.queryMock = mock(LocalQuery.class);
    fixture.query = (LocalQuery) fixture.queryMock.proxy();
    fixture.queryMock.expects(once()).method("findByString").will(returnValue(null));

    fixture.ldap =
        new LdapImpl(source, fixture.template, new Roles(), fixture.config, provider, sql);
    fixture.ldap.setQueryService(fixture.query);

    fixture.provider = new LdapPasswordProvider(new PasswordUtil(sql), fixture.ldap);

    return fixture;
  }
Exemple #12
0
 //    public Collection<Fixture> getFixtures() {
 //        return fxs.values();
 //    }
 public void init() {
   log.trace("Fixtures init..." + fxs.size());
   for (Fixture fx : fxs.values()) {
     log.trace(fx.getTestFixture().getFixtureName() + " init...");
     fx.init();
     log.trace(fx.getTestFixture().getFixtureName() + " init completed.");
   }
 }
Exemple #13
0
 public void hit() {
   Gyaya.manager.get("audio/music/background.ogg", Music.class).stop();
   Gyaya.manager.get("audio/sounds/uaBArt - Bell.mp3", Sound.class).play();
   playerIsDead = true;
   Filter filter = new Filter();
   filter.maskBits = Gyaya.NOTHING_BIT;
   for (Fixture fixture : b2body.getFixtureList()) fixture.setFilterData(filter);
   b2body.setLinearVelocity(new Vector2(0, 4f));
 }
 /* Added by Rick Mugridge */
 private void interpretTables(FitDocument documents) {
   for (FitTable table : documents.tables()) {
     try {
       Fixture fixture = getLinkedFixtureWithArgs(table);
       fixture.doTable(table);
       counts.tally(table.getCounts());
     } catch (Throwable e) {
       table.exception(e);
       counts.exceptions++;
     }
   }
 }
Exemple #15
0
  public void beginContact(Contact contact) {
    if (!contact.isTouching()) {
      return;
    }

    Fixture fixture0 = contact.getFixtureA();
    Fixture fixture1 = contact.getFixtureB();

    Item item0 = (Item) fixture0.getUserData();
    Item item1 = (Item) fixture1.getUserData();

    item0.contacted(item1);
  }
Exemple #16
0
  public static Body createGround(
      World world, float x, float y, float width, float height, float restituition) {

    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(new Vector2(x, y));
    Body body = world.createBody(bodyDef);
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(width / 2, height / 2);
    Fixture fixture = body.createFixture(shape, Constants.WALL_DENSITY);
    fixture.setRestitution(restituition);
    body.setUserData(new GroundUserData());
    shape.dispose();
    return body;
  }
  /**
   * First clears the table for the given Entity object. This allows fixture files to load defaults
   * without worrying about unique and primary key collisions.
   *
   * <p>Second, loads the given fixture XML file into a new instance of the given JavaBean using the
   * Java.net commons XML unmarshaller. This then uses an EntityManager from the
   * EntityManagerFactory to persist the JavaBean. This means that the bean must be an Entity.
   *
   * <p>The fixture XML format must have a root element named fixture and then child elements for
   * the objects being created. The name of the child element must be the same as the name of the
   * table that the Entity is associated with. The attributes of the child elements correspond to
   * the properties of the JavaBean. Here's an example for the class: <b>com.example.Role</b>
   *
   * <pre>
   * &lt;fixture>
   *   &lt;role name="User"/>
   *   &lt;role name="Admin"/>
   * &lt;/fixture>
   * </pre>
   *
   * <p>Notice that the ID is left out. This is because JPA freaks out if IDs are set. Therefore,
   * you will have to figure out the IDs manually in your tests.
   *
   * @param fixture The fixture file. This is relative to the directory of the current test.
   * @param type The type of objects to create and persist.
   * @throws RuntimeException If anything failed.
   */
  @SuppressWarnings(value = "unchecked")
  protected <T> void loadFixture(String fixture, Class<T> type) throws RuntimeException {
    logger.fine("Loading fixtures from [" + fixture + "] for [" + type + "]");

    // Clear the table via the annotation
    Table table = type.getAnnotation(Table.class);
    String tableName;
    if (table == null) {
      Entity entity = type.getAnnotation(Entity.class);
      if (entity == null) {
        throw new IllegalArgumentException("The type [" + type + "] is not annotated with @Entity");
      }

      tableName = type.getSimpleName();
    } else {
      tableName = table.name();
    }

    try {
      clearTable(tableName);

      String pkg = getClass().getPackage().getName();
      String location = "src/java/test/unit/" + pkg.replace(".", "/") + "/" + fixture;
      logger.fine("Mapped location to [" + location + "]");

      Map<String, String> mappings = map(tableName, "child");
      Unmarshaller um = new Unmarshaller(null);
      um.addObjectCreator(
          "fixture",
          JavaBeanObjectCreator.forClass(Fixture.class, new SimplePluralizer(), mappings));
      um.addObjectCreator("fixture/*", JavaBeanObjectCreator.forClass(type));
      Fixture<T> fix = (Fixture<T>) um.unmarshal(location);

      EntityManager em = emf.createEntityManager();
      EntityTransaction et = em.getTransaction();
      et.begin();

      List<T> objs = fix.getChildren();
      for (T obj : objs) {
        logger.fine("Running fixure for object [" + obj + "]");
        em.persist(obj);
      }

      et.commit();
      em.close();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  public void testGetProcessInstance() {
    try {
      String sampleProcessId = "150001"; // replace this with a valid id
      IBPMContext ctx = Fixture.getIBPMContext("pino", "password1");
      IInstanceQueryService queryService = Fixture.getBPMServiceClient().getInstanceQueryService();
      System.out.println("retrieve sample instance");
      IProcessInstance instance = queryService.getProcessInstance(ctx, sampleProcessId);

      printProcessInstance(instance);

    } catch (Exception e) {
      // TODO: Add catch code
      e.printStackTrace();
    }
  }
Exemple #19
0
  private Body addFinish(World world, Vector2 position) {
    final BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.StaticBody;
    final Body body = world.createBody(bodyDef);
    body.setTransform(position.x + offset.x, position.y + offset.y, 0);

    final PolygonShape shape = new PolygonShape();
    shape.setAsBox(0.1f, 0.1f);
    final FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.isSensor = true;
    final Fixture fixture = body.createFixture(fixtureDef);
    fixture.setUserData("finish");
    shape.dispose();
    return body;
  }
Exemple #20
0
  @Test
  public void update_while_merging_a_branch_without_a_dep() throws Exception {
    setup();

    // do a merges.
    WithCwd wd = new WithCwd(project.getRepo().getWorkTree());
    {
      // switch to the branch with the lib
      git.args("checkout", "blue").start().get();

      // add a conflicting file so we get halted mid merge (inb4: no, '--no-commit' isn't quite the
      // same)
      IOForge.saveFile("qwer", new File("somefile").getCanonicalFile());
      git.args("add", "--", "somefile").start().get();
      git.args("commit", "-m", "bluecommit").start().get();

      // merge the master branch, which doesn't have the lib yet.  should conflict (exit code is
      // nonzero)
      git.args("merge", "--no-ff", "master").okExit(1).start().get();

      // we're stuck in a merge conflict.  try to mdm-update during it
      assertJoy(Mdm.run("update", "--strict"));

      // finish the merge.
      git.args("add", "somefile").start().get();
      git.args("commit", "--no-edit").start().get();
    }
    wd.close();

    // now verify.
    File depWorkTreePath =
        new File(project.getRepo().getWorkTree() + "/lib/beta").getCanonicalFile();
    File depGitDataPath =
        new File(project.getRepo().getDirectory() + "/modules/lib/beta").getCanonicalFile();

    // i do hope there's a filesystem there now
    assertTrue("dependency module path exists on fs", depWorkTreePath.exists());
    assertTrue("dependency module path is dir", depWorkTreePath.isDirectory());

    // check that anyone else can read this state with a straight face; status should be clean
    new Josh("git")
        .args("status")
        .cwd(project.getRepo().getWorkTree()) /*.opts(Opts.NullIO)*/
        .start()
        .get();
    new Josh("git").args("status").cwd(depWorkTreePath) /*.opts(Opts.NullIO)*/.start().get();
  }
  /**
   * @param method
   * @param instance
   * @param convertedArgs
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  private void preInvoke(Method method, Object instance, Object[] convertedArgs)
      throws InvocationTargetException, IllegalAccessException {

    if (instance instanceof Fixture) {

      ((Fixture) instance).preInvoke(method, instance, convertedArgs);
    }
  }
Exemple #22
0
 /**
  * Runs the LDAP test suite against each of the given LDIF files, by attempting to login against
  * an embedded LDAP store with both the good names and the bad names.
  */
 @Test(dataProvider = "ldif_files")
 @SuppressWarnings("unchecked")
 public void testLdiffFile(File file) throws Exception {
   Fixture fixture = createFixture(file);
   try {
     Map<String, List<String>> good = fixture.ctx.getBean("good", Map.class);
     Map<String, List<String>> bad = fixture.ctx.getBean("bad", Map.class);
     assertPasses(fixture, good);
     assertFails(fixture, bad);
     assertCreateUserFromLdap(fixture, good);
     if (!good.isEmpty()) {
       assertDiscover(fixture, good);
     }
   } finally {
     fixture.close();
   }
 }
Exemple #23
0
  @Test
  public void canValidateBackUp() {
    Snapshot backUp = Fixture.createSnapshot();

    assertValid(backUp);
    // make member first name invalid.
    backUp.getMembers().get(3).setFirstName("");
    assertInvalid(backUp, "members[3].firstName");
  }
Exemple #24
0
 @Test
 public void canPopulateEntityManagerFromSnapshot() throws Exception {
   EntityManager manager = createEntityManager();
   Snapshot source = Fixture.createSnapshot();
   manager.getTransaction().begin();
   source.persistTo(manager);
   manager.flush();
   manager.getTransaction().commit();
   assertDataAsExpected("backup.dbunit.xml");
 }
Exemple #25
0
  protected void assertDiscover(Fixture fixture, Map<String, List<String>> users) {
    for (String user : users.keySet()) {
      Experimenter experimenter = fixture.findExperimenter(user);
      assertNotNull(experimenter);

      fixture.setDN(experimenter.getId(), null);
      List<Experimenter> discoveredExperimenters = fixture.discover();
      if (!discoveredExperimenters.isEmpty()) {
        boolean discovered = false;
        for (Experimenter e : discoveredExperimenters) {
          if (experimenter.getId().equals(e.getId())) {
            discovered = true;
            break;
          }
        }
        assertTrue(discovered);
      }
      fixture.setDN(experimenter.getId(), "dn");
    }
  }
  /** Tests a few cases where the router can decide if it is better to pay the toll or not. */
  @Test
  public void testBestAlternatives() {
    Config config = matsimTestUtils.loadConfig(null);
    MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config);
    Fixture.createNetwork2(scenario);

    // a basic toll where only the morning hours are tolled
    RoadPricingSchemeImpl toll = new RoadPricingSchemeImpl();
    toll.setType("area");
    toll.addLink(Id.createLinkId("5"));
    toll.addLink(Id.createLinkId("11"));
    Cost morningCost = toll.addCost(6 * 3600, 10 * 3600, 0.12);
    /* Start with a rather low toll. The toll is also so low, because we only
     * have small network with short links: the cost to travel across one link
     * is: 20s * (-6 EUR / h) = 20 * (-6) / 3600 = 0.03333
     */

    Fixture.createPopulation2(scenario);
    Population population = scenario.getPopulation();

    Id id1 = Id.createPersonId("1");

    // case 1: toll only in morning, it is cheaper to drive around
    runOnAll(testee(scenario, toll), population);
    Fixture.compareRoutes("2 3 4 6", (NetworkRoute) getLeg1(population, id1).getRoute());
    Fixture.compareRoutes("8 11 12", (NetworkRoute) getLeg3(population, id1).getRoute());

    // case 2: now add a toll in the afternoon too, so it is cheaper to pay the toll
    Cost afternoonCost = toll.addCost(14 * 3600, 18 * 3600, 0.12);
    runOnAll(testee(scenario, toll), population);
    Fixture.compareRoutes("2 5 6", (NetworkRoute) getLeg1(population, id1).getRoute());
    Fixture.compareRoutes("8 11 12", (NetworkRoute) getLeg3(population, id1).getRoute());

    // case 3: change the second leg to a non-car mode, than it should be the same as case 1
    String oldMode = getLeg3(population, id1).getMode();
    getLeg3(population, id1).setMode(TransportMode.pt);
    runOnAll(testee(scenario, toll), population);
    Fixture.compareRoutes("2 3 4 6", (NetworkRoute) getLeg1(population, id1).getRoute());
    // and change the mode back
    getLeg3(population, id1).setMode(oldMode);

    // case 4: now remove the costs and add them again, but with a higher amount
    toll.removeCost(morningCost);
    toll.removeCost(afternoonCost);
    toll.addCost(6 * 3600, 10 * 3600, 0.7);
    toll.addCost(14 * 3600, 18 * 3600, 0.7);
    // the agent should now decide to drive around
    runOnAll(testee(scenario, toll), population);
    Fixture.compareRoutes("2 3 4 6", (NetworkRoute) getLeg1(population, id1).getRoute());
  }
  @Test
  public void fixtureNextInvoices() {
    List<Invoice> invoices = Fixture.from(Invoice.class).gimme(3, "nextInvoices");
    assertNotNull("Invoice list should not be null", invoices);
    assertTrue("Invoice list should not be empty", !invoices.isEmpty());

    Calendar calendar = DateTimeUtil.toCalendar("2011-04-30", new SimpleDateFormat("yyyy-MM-dd"));

    for (Invoice invoice : invoices) {
      assertEquals("Calendar should be equal", calendar, invoice.getDueDate());
      calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
  }
Exemple #28
0
  public static Body createRunner(World world, float x, float y, float width, float height) {

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(new Vector2(x, y));
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(0.5f, 0.5f, new Vector2(2, 2), 45);
    Body body = world.createBody(bodyDef);

    body.setGravityScale(Constants.RUNNER_GRAVITY_SCALE);
    Fixture fixture = body.createFixture(shape, Constants.RUNNER_DENSITY);
    body.setFixedRotation(true);
    fixture.setFriction(2f);

    body.resetMassData();
    body.setUserData(new RunnerUserData());
    shape.dispose();

    body.setBullet(true);

    return body;
  }
  /**
   * Tests cases where the agent must pay the toll because one of its activities is on a tolled link
   */
  @Test
  public void testTolledActLink() {
    Config config = matsimTestUtils.loadConfig(null);
    MutableScenario scenario = (MutableScenario) ScenarioUtils.createScenario(config);
    Fixture.createNetwork2(scenario);

    // a basic toll where only the morning hours are tolled
    RoadPricingSchemeImpl toll = new RoadPricingSchemeImpl();
    toll.setType("area");
    Id.createLinkId("7");
    toll.addCost(6 * 3600, 10 * 3600, 0.06);

    Fixture.createPopulation2(scenario);
    Population population = scenario.getPopulation();

    runOnAll(testee(scenario, toll), population);
    Id id1 = Id.createPersonId("1");

    Fixture.compareRoutes(
        "2 5 6",
        (NetworkRoute) getLeg1(population, id1).getRoute()); // agent should take shortest route
    Fixture.compareRoutes("8 11 12", (NetworkRoute) getLeg3(population, id1).getRoute());
  }
Exemple #30
0
 private void setDataSetFromAnnotation(Description description) {
   Class<?> testClass = description.getTestClass();
   Fixture fixture = findFixtureAnnotation(description);
   if (fixture == null) return;
   Fixture.Type type = fixture.type();
   String[] resources = fixture.resources();
   if (resources == null || resources.length == 0) return;
   try {
     if (resources.length == 1) {
       setDataSet(loadDataSet(type, resources[0], testClass));
     } else {
       IDataSet[] dataSets = new IDataSet[resources.length];
       for (int i = 0; i < resources.length; i++) {
         dataSets[i] = loadDataSet(type, resources[i], testClass);
       }
       setDataSet(new CompositeDataSet(dataSets));
     }
   } catch (YAMLException e) {
     throw new YAMLException("Cant load fixture: " + Arrays.toString(resources), e);
   } catch (DataSetException | URISyntaxException e) {
     throw new AssertionError(e);
   }
 }