コード例 #1
0
  public void testGetNumberOfSections() throws Exception {

    ______TS("Typical case");

    CourseAttributes course = dataBundle.courses.get("typicalCourse1");
    int sectionNum = coursesLogic.getNumberOfSections(course.id);

    assertEquals(2, sectionNum);

    ______TS("Course with no sections");

    course = dataBundle.courses.get("typicalCourse2");
    sectionNum = coursesLogic.getNumberOfSections(course.id);

    assertEquals(0, sectionNum);

    ______TS("non-existent");

    try {
      coursesLogic.getNumberOfSections("non-existent-course");
      signalFailureToDetectException();
    } catch (EntityDoesNotExistException e) {
      AssertHelper.assertContains("does not exist", e.getMessage());
    }

    ______TS("null parameter");

    try {
      coursesLogic.getNumberOfSections(null);
      signalFailureToDetectException();
    } catch (AssertionError e) {
      assertEquals("Supplied parameter was null\n", e.getMessage());
    }
  }
コード例 #2
0
  public void testIsSampleCourse() {

    ______TS("typical case: not a sample course");

    CourseAttributes c = new CourseAttributes();
    c.id = "course.id";

    assertEquals(false, coursesLogic.isSampleCourse(c.id));

    ______TS("typical case: is a sample course");

    c.id = c.id.concat("-demo3");
    assertEquals(true, coursesLogic.isSampleCourse(c.id));

    ______TS("typical case: is a sample course with '-demo' in the middle of its id");

    c.id = c.id.concat("-demo33");
    assertEquals(true, coursesLogic.isSampleCourse(c.id));

    ______TS("Null parameter");

    try {
      coursesLogic.isSampleCourse(null);
      signalFailureToDetectException();
    } catch (AssertionError e) {
      assertEquals("Course ID is null", e.getMessage());
    }
  }
コード例 #3
0
  public void testGetCourse() throws Exception {

    ______TS("failure: course doesn't exist");

    assertNull(coursesLogic.getCourse("nonexistant-course"));

    ______TS("success: typical case");

    CourseAttributes c = new CourseAttributes();
    c.id = "Computing101-getthis";
    c.name = "Basic Computing Getting";
    coursesDb.createEntity(c);

    assertEquals(c.id, coursesLogic.getCourse(c.id).id);
    assertEquals(c.name, coursesLogic.getCourse(c.id).name);

    coursesDb.deleteEntity(c);
    ______TS("Null parameter");

    try {
      coursesLogic.getCourse(null);
      signalFailureToDetectException();
    } catch (AssertionError e) {
      assertEquals("Supplied parameter was null\n", e.getMessage());
    }
  }
コード例 #4
0
  public void testGetCoursesForInstructor() throws Exception {

    ______TS("success: instructor with present courses");

    String instructorId = dataBundle.accounts.get("instructor3").googleId;

    List<CourseAttributes> courses = coursesLogic.getCoursesForInstructor(instructorId);

    assertEquals(2, courses.size());

    ______TS("boundary: instructor without any courses");

    instructorId = dataBundle.accounts.get("instructorWithoutCourses").googleId;

    courses = coursesLogic.getCoursesForInstructor(instructorId);

    assertEquals(0, courses.size());

    ______TS("Null parameter");

    try {
      coursesLogic.getCoursesForInstructor(null);
      signalFailureToDetectException();
    } catch (AssertionError e) {
      assertEquals("Supplied parameter was null\n", e.getMessage());
    }
  }
コード例 #5
0
  @Test
  public void testSourceFormatter() throws Exception {
    SourceFormatterArgs sourceFormatterArgs = new SourceFormatterArgs();

    sourceFormatterArgs.setAutoFix(false);
    sourceFormatterArgs.setBaseDirName("../../../");
    sourceFormatterArgs.setPrintErrors(false);
    sourceFormatterArgs.setThrowException(true);
    sourceFormatterArgs.setUseProperties(false);

    SourceFormatter sourceFormatter = new SourceFormatter(sourceFormatterArgs);

    try {
      sourceFormatter.format();
    } catch (SourceMismatchException sme) {
      try {
        Assert.assertEquals(sme.getFileName(), sme.getFormattedSource(), sme.getOriginalSource());
      } catch (AssertionError ae) {
        String message = ae.getMessage();

        if (message.length() >= _MAX_MESSAGE_SIZE) {
          message = "Truncated message :\n" + message.substring(0, _MAX_MESSAGE_SIZE);

          throw new AssertionError(message, ae.getCause());
        }

        throw ae;
      }
    }
  }
  /** This method should fail because the value is not null. */
  @Test
  @NeedReload
  public void should_fail_because_value_is_not_null() {
    Table table = new Table(source, "test");
    Changes changes = new Changes(table).setStartPointNow();
    update("update test set var14 = 1 where var1 = 1");
    changes.setEndPointNow();

    try {
      assertThat(changes).change().column("var3").valueAtEndPoint().isNull();
      fail("An exception must be raised");
    } catch (AssertionError e) {
      Assertions.assertThat(e.getMessage())
          .isEqualTo(
              String.format(
                  "[Value at end point of Column at index 2 (column name : VAR3) of Change at index 0 (with primary key : [1]) of Changes on TEST table of 'sa/jdbc:h2:mem:test' source] expected:<null> but was:<2>"));
    }
    try {
      assertThat(table).column("var3").value().isNull();
      fail("An exception must be raised");
    } catch (AssertionError e) {
      Assertions.assertThat(e.getMessage())
          .isEqualTo(
              String.format(
                  "[Value at index 0 of Column at index 2 (column name : VAR3) of TEST table] expected:<null> but was:<2>"));
    }
  }
コード例 #7
0
ファイル: RequestValidator.java プロジェクト: pageone/jbosh
 /**
  * Validate a request.
  *
  * @param message number (zero-based)
  * @param first message sent
  * @param previous previous request, or {@code null} if this is the first request ever sent
  * @param request request message
  */
 private void validateRequest(
     final int idx, final Node first, final Node previous, final Node request) {
   try {
     assertValidXML(request);
     assertSingleBodyElement(request);
     assertNoComments(request);
     assertNoProcessingInstructions(request);
     assertRequestIDSequential(request, previous);
     if (previous == null) {
       validateRequestHeaders(idx, request, previous);
       assertSessionCreationRequestID(request);
       assertSessionCreationRequestIDRange(request);
       validateSessionCreationAck(idx, request);
       validateSessionCreationSID(idx, request);
       validateSessionCreationHold(idx, request);
     } else {
       validateRequestHeaders(idx, request, previous);
       validateSubsequentRequestSID(idx, request);
       validateSubsequestRequestAck(idx, first, request);
       validateSubsequentPause(idx, request, previous);
     }
   } catch (AssertionError err) {
     LOG.info(
         "Assertion failed for request #"
             + idx
             + ": "
             + err.getMessage()
             + "\n"
             + request.getBody().toXML());
     throw (err);
   }
 }
コード例 #8
0
  /** Tests that the current file does what it is supposed to when compiled. */
  @Test
  public void testFrontEnd() throws IOException {
    try {
      System.out.println("Testing " + filename + "... ");
      Reader reader = new FileReader(TEST_DIRECTORY + "/" + filename);

      Compiler compiler = new Compiler();

      if (filename.startsWith("synerror")) {
        // Expect at least one error during syntax checking
        compiler.checkSyntax(reader);
        assertTrue("Supposed to have syntax errors", compiler.getErrorCount() != 0);

      } else if (filename.startsWith("semerror")) {
        // Expect no syntax errors, but one or more semantic errors
        Script script = compiler.checkSyntax(reader);
        assertTrue("Supposed to have NO syntax errors", compiler.getErrorCount() == 0);
        compiler.checkSemantics(script);
        assertTrue("Supposed to have semantic errors", compiler.getErrorCount() != 0);

      } else {
        // Expect no errors even after all semantic checks
        compiler.checkSemantics(reader);
        assertTrue("Supposed to be error free", compiler.getErrorCount() == 0);
      }
      System.out.println("PASS");
    } catch (AssertionError e) {
      System.out.println("FAIL: " + e.getMessage());
      throw e;
    }
  }
コード例 #9
0
  @Test
  public void test() {
    Volume.Factory fab = Volume.memoryFactory(false, 0L, false);
    Engine e = new StoreDirect(fab);
    e = new EngineWrapper.ImmutabilityCheckEngine(e);

    List rec = new ArrayList();
    rec.add("aa");
    long recid = e.put(rec, Serializer.BASIC);
    rec.add("bb");

    try {
      e.update(recid, rec, Serializer.BASIC);
      fail("should throw exception");
    } catch (AssertionError ee) {
      assertTrue(ee.getMessage().startsWith("Record instance was modified"));
    }

    try {
      e.close();
      fail("should throw exception");
    } catch (AssertionError ee) {
      assertTrue(ee.getMessage().startsWith("Record instance was modified"));
    }
  }
コード例 #10
0
ファイル: SFSB2LC.java プロジェクト: fduchatelet/jboss-as
  /** Check if disabling 2LC works as expected */
  public String disabled2LCCheck() {

    EntityManager em = emfNo2LC.createEntityManager();
    Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
    stats.clear();

    try {
      // check if entities are NOT cached in 2LC
      String names[] = stats.getSecondLevelCacheRegionNames();
      assertEquals("There aren't any 2LC regions.", 0, names.length);

      createEmployee(em, "Martin", "Prague 132", 1);
      assertEquals("There aren't any puts in the 2LC.", 0, stats.getSecondLevelCachePutCount());

      // check if queries are NOT cached in 2LC
      Employee emp = getEmployeeQuery(em, 1);
      assertNotNull("Employee returned", emp);
      assertEquals("There aren't any query puts in the 2LC.", 0, stats.getQueryCachePutCount());

      // cleanup
      em.remove(emp);

    } catch (AssertionError e) {
      return e.getMessage();
    } finally {
      em.close();
    }
    return "OK";
  }
コード例 #11
0
  public void testHasIndicatedSections() throws Exception {

    ______TS("Typical case: course with sections");

    CourseAttributes typicalCourse1 = dataBundle.courses.get("typicalCourse1");
    assertTrue(coursesLogic.hasIndicatedSections(typicalCourse1.id));

    ______TS("Typical case: course without sections");

    CourseAttributes typicalCourse2 = dataBundle.courses.get("typicalCourse2");
    assertEquals(false, coursesLogic.hasIndicatedSections(typicalCourse2.id));

    ______TS("Failure case: course does not exists");

    try {
      coursesLogic.hasIndicatedSections("non-existent-course");
      signalFailureToDetectException();
    } catch (EntityDoesNotExistException e) {
      AssertHelper.assertContains("does not exist", e.getMessage());
    }

    ______TS("Failure case: null parameter");

    try {
      coursesLogic.hasIndicatedSections(null);
      signalFailureToDetectException();
    } catch (AssertionError e) {
      assertEquals("Supplied parameter was null\n", e.getMessage());
    }
  }
コード例 #12
0
  public static void main(String[] args) {
    int success = 0;
    int failure = 0;
    int error = 0;
    try {
      Method[] methods = TestGregorianCalendar.class.getDeclaredMethods();
      for (Method method : methods) {
        if (Modifier.isStatic(method.getModifiers()) == false
            && method.getName().startsWith("test")) {
          try {
            try {
              method.invoke(new TestGregorianCalendar());
            } catch (InvocationTargetException itex) {
              throw itex.getCause();
            }
            System.out.println(method.getName() + " SUCCEEDED");
            success++;
          } catch (AssertionError ex) {
            System.out.println(method.getName() + " FAILED");
            ex.printStackTrace(System.out);
            failure++;
          } catch (Throwable ex) {
            ex.printStackTrace();
            error++;
          }
        }
      }

    } catch (Throwable th) {
      th.printStackTrace();
    }
    System.out.println("Success: " + success);
    System.out.println("Failure: " + failure);
    System.out.println("Error:   " + error);
  }
 /** This method should fail because the value at end point is a stringbuilder. */
 @Test
 public void should_fail_because_value_at_end_point_is_a_stringbuilder() throws Exception {
   WritableAssertionInfo info = new WritableAssertionInfo();
   info.description("description");
   Table table = new Table();
   TableAssert tableAssert = assertThat(table);
   try {
     AssertionsOnColumnOfChangeType.isBoolean(
         tableAssert,
         info,
         getValue(null, false),
         getValue(null, new StringBuilder("test")),
         false);
     fail("An exception must be raised");
   } catch (AssertionError e) {
     Assertions.assertThat(e.getMessage())
         .isEqualTo(
             String.format(
                 "[description] %n"
                     + "Expecting that the value at end point:%n"
                     + "  <test>%n"
                     + "to be of type%n"
                     + "  <BOOLEAN>%n"
                     + "but was of type%n"
                     + "  <NOT_IDENTIFIED> (java.lang.StringBuilder)"));
   }
 }
コード例 #14
0
 public static void main(String[] args) {
   System.setProperty("webdriver.chrome.driver", "C:/WebServerSelenium/chromedriver.exe");
   WebDriver driver = new ChromeDriver();
   driver.navigate().to(Configurations.HOMEPAGE);
   driver.manage().window().maximize();
   try {
     driver
         .findElement(By.xpath("html/body/form/table/tbody/tr/td/div/center[1]/input[1]"))
         .sendKeys("*****@*****.**");
     driver
         .findElement(By.xpath("html/body/form/table/tbody/tr/td/div/center[1]/input[2]"))
         .sendKeys("Asdfghjkl123");
     driver
         .findElement(By.xpath("html/body/form/table/tbody/tr/td/div/center[2]/input[1]"))
         .click();
     driver.findElement(By.xpath("html/body/div/div/table/tbody/tr[2]/td[1]/a")).click();
     driver.findElement(By.xpath(".//*[@id='textNomeMedico']")).sendKeys("Vincenzo");
     driver.findElement(By.xpath(".//*[@id='textCognomeMedico']")).sendKeys("Nunziata");
     driver.findElement(By.xpath("html/body/table/tbody/tr/td[1]/form/input[3]")).sendKeys("");
     driver.findElement(By.xpath("html/body/table/tbody/tr/td[1]/form/input[5]")).click();
     driver.findElement(By.xpath(".//*[@id='selectRisultati']/option")).click();
     driver.findElement(By.xpath(".//*[@id='confirmButton']/input")).click();
     List<WebElement> list =
         driver.findElements(
             By.xpath("//*[contains(text(),'" + "Richiesta inviata con successo" + "')]"));
     Assert.assertTrue(list.size() > 0, "Richiesta inviata con successo");
     System.out.println("Test Passed");
   } catch (AssertionError e) {
     System.out.println("Test Failed");
     System.out.println(e.getMessage());
   }
   driver.close();
 }
コード例 #15
0
ファイル: OAuth2Test.java プロジェクト: kingsfleet/jersey
    @POST
    @Path("access-token")
    @Produces(MediaType.APPLICATION_JSON)
    public MyTokenResult getAccessToken(
        @FormParam("grant_type") String grantType,
        @FormParam("code") String code,
        @FormParam("redirect_uri") String redirectUri,
        @FormParam("client_id") String clientId) {
      try {
        assertEquals("authorization_code", grantType);
        assertEquals("urn:ietf:wg:oauth:2.0:oob", redirectUri);
        assertEquals(CODE, code);
        assertEquals(CLIENT_PUBLIC, clientId);
      } catch (AssertionError e) {
        e.printStackTrace();
        throw new BadRequestException(Response.status(400).entity(e.getMessage()).build());
      }

      final MyTokenResult myTokenResult = new MyTokenResult();
      myTokenResult.setAccessToken("access-token-aab999f");
      myTokenResult.setExpiresIn("3600");
      myTokenResult.setTokenType("access-token");
      myTokenResult.setRefreshToken("refresh-xyz");
      return myTokenResult;
    }
コード例 #16
0
ファイル: Log.java プロジェクト: JSansalone/NetBeansIDE
 static Throwable wrapWithAddendum(Throwable ex, String addendum, boolean after) {
   if (ex instanceof AssertionFailedError) {
     AssertionFailedError ne = new AssertionFailedError(combineMessages(ex, addendum, after));
     if (ex.getCause() != null) {
       ne.initCause(ex.getCause());
     }
     ne.setStackTrace(ex.getStackTrace());
     return ne;
   }
   if (ex instanceof AssertionError) { // preferred in JUnit 4
     AssertionError ne = new AssertionError(combineMessages(ex, addendum, after));
     if (ex.getCause() != null) {
       ne.initCause(ex.getCause());
     }
     ne.setStackTrace(ex.getStackTrace());
     return ne;
   }
   if (ex instanceof IOException) { // #66208
     IOException ne = new IOException(combineMessages(ex, addendum, after));
     if (ex.getCause() != null) {
       ne.initCause(ex.getCause());
     }
     ne.setStackTrace(ex.getStackTrace());
     return ne;
   }
   if (ex instanceof Exception) {
     return new InvocationTargetException(ex, combineMessages(ex, addendum, after));
   }
   return ex;
 }
コード例 #17
0
  // ToDo Convert to parametric test
  private static boolean testCase(String inFile, String expectedFile) throws IOException {
    BufferedReader in = new BufferedReader(new FileReader(inFile));

    int N = Integer.parseInt(in.readLine().trim());

    int[] a = new int[N];

    for (int i = 0; i < N; i++) {
      a[i] = Integer.parseInt(in.readLine().trim());
    }

    BufferedReader expected = new BufferedReader(new FileReader(expectedFile));
    boolean error = false;

    final String filename = new File(inFile).getName();
    try {
      final int maxSum = Integer.parseInt(expected.readLine());
      final int nonCont = Integer.parseInt(expected.readLine());
      assertEquals("Error in file " + filename + ",", new Response(maxSum, nonCont), maxsum(a, N));
    } catch (AssertionError e) {
      System.out.print(HEADER);
      e.printStackTrace(System.out);
      error = true;
    }

    return error;
  }
コード例 #18
0
ファイル: SFSB2LC.java プロジェクト: fduchatelet/jboss-as
  /** Check if eviction of entity cache is working */
  public String evict2LCCheck(String CACHE_REGION_NAME) {

    EntityManager em = emf.createEntityManager();
    Statistics stats = em.unwrap(Session.class).getSessionFactory().getStatistics();
    stats.clear();
    SecondLevelCacheStatistics emp2LCStats =
        stats.getSecondLevelCacheStatistics(CACHE_REGION_NAME + "Employee");

    try {
      createEmployee(em, "Jan", "Ostrava", 20);
      createEmployee(em, "Martin", "Brno", 30);
      assertEquals(
          "There are 2 puts in the 2LC" + generateEntityCacheStats(emp2LCStats),
          2,
          emp2LCStats.getPutCount());

      assertTrue(
          "Expected entities stored in the cache" + generateEntityCacheStats(emp2LCStats),
          emp2LCStats.getElementCountInMemory() > 0);

      // evict cache and check if is empty
      emf.getCache().evictAll();
      assertEquals(
          "Expected no entities stored in the cache" + generateEntityCacheStats(emp2LCStats),
          0,
          emp2LCStats.getElementCountInMemory());

    } catch (AssertionError e) {
      return e.getMessage();
    } finally {
      em.close();
    }
    return "OK";
  }
コード例 #19
0
  public void testGetArchivedCoursesForInstructor() throws Exception {

    ______TS("success: instructor with archive course");
    String instructorId = dataBundle.instructors.get("instructorOfArchivedCourse").googleId;

    List<CourseAttributes> archivedCourses =
        coursesLogic.getArchivedCoursesForInstructor(instructorId);

    assertEquals(1, archivedCourses.size());
    assertEquals(true, archivedCourses.get(0).isArchived);

    ______TS("boundary: instructor without archive courses");
    instructorId = dataBundle.instructors.get("instructor1OfCourse1").googleId;

    archivedCourses = coursesLogic.getArchivedCoursesForInstructor(instructorId);

    assertEquals(0, archivedCourses.size());

    ______TS("Null parameter");

    try {
      coursesLogic.getArchivedCoursesForInstructor(null);
      signalFailureToDetectException();
    } catch (AssertionError e) {
      assertEquals("Supplied parameter was null\n", e.getMessage());
    }
  }
コード例 #20
0
 public static void performPostRequest() {
   try {
     response =
         given()
             .urlEncodingEnabled(urlEncoding)
             .headers(requestHeaders)
             .body(requestBody)
             .filter(new RequestLoggingFilter(psRequest))
             .filter(new ResponseLoggingFilter(psResponse))
             .expect()
             .statusCode(statusCode)
             .headers(responseHeaders)
             .post(requestURL);
     responseString = response.asString();
   } catch (AssertionError e) {
     fail(
         e.getMessage()
             + "\n\n"
             + baosRequest.toString()
             + "\nResponse:\n"
             + baosResponse.toString());
   } finally {
     psRequest.close();
   }
 }
コード例 #21
0
 public void testWriteableReaderReturnsWrongName() throws IOException {
   BytesStreamOutput out = new BytesStreamOutput();
   NamedWriteableRegistry namedWriteableRegistry =
       new NamedWriteableRegistry(
           Collections.singletonList(
               new NamedWriteableRegistry.Entry(
                   BaseNamedWriteable.class,
                   TestNamedWriteable.NAME,
                   (StreamInput in) ->
                       new TestNamedWriteable(in) {
                         @Override
                         public String getWriteableName() {
                           return "intentionally-broken";
                         }
                       })));
   TestNamedWriteable namedWriteableIn =
       new TestNamedWriteable(
           randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
   out.writeNamedWriteable(namedWriteableIn);
   byte[] bytes = BytesReference.toBytes(out.bytes());
   StreamInput in =
       new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes), namedWriteableRegistry);
   assertEquals(in.available(), bytes.length);
   AssertionError e =
       expectThrows(AssertionError.class, () -> in.readNamedWriteable(BaseNamedWriteable.class));
   assertThat(
       e.getMessage(),
       endsWith(
           " claims to have a different name [intentionally-broken] than it was read from [test-named-writeable]."));
 }
コード例 #22
0
  @Test
  public void prepopulatedFields() throws Exception {
    assume().that(notesMigration.enabled()).isFalse();
    TestRepository<Repo> repo = createProject("repo");
    Change change = newChange(repo, null, null, null, null).insert();

    db = new DisabledReviewDb();
    requestContext.setContext(newRequestContext(userId));
    // Use QueryProcessor directly instead of API so we get ChangeDatas back.
    List<ChangeData> cds =
        queryProcessor.queryChanges(queryBuilder.parse(change.getId().toString())).changes();
    assertThat(cds).hasSize(1);

    ChangeData cd = cds.get(0);
    cd.change();
    cd.patchSets();
    cd.currentApprovals();
    cd.changedLines();
    cd.reviewedBy();

    // TODO(dborowitz): Swap out GitRepositoryManager somehow? Will probably be
    // necessary for notedb anyway.
    cd.isMergeable();

    // Don't use ExpectedException since that wouldn't distinguish between
    // failures here and on the previous calls.
    try {
      cd.messages();
    } catch (AssertionError e) {
      assertThat(e.getMessage()).isEqualTo(DisabledReviewDb.MESSAGE);
    }
  }
コード例 #23
0
 public static void main(String[] args) {
   System.setProperty("webdriver.chrome.driver", "C:/WebServerSelenium/chromedriver.exe");
   WebDriver driver = new ChromeDriver();
   driver.navigate().to(Configurations.HOMEPAGE);
   driver.manage().window().maximize();
   try {
     driver
         .findElement(By.xpath("html/body/form/table/tbody/tr/td/div/center[1]/input[1]"))
         .sendKeys("*****@*****.**");
     driver
         .findElement(By.xpath("html/body/form/table/tbody/tr/td/div/center[1]/input[2]"))
         .sendKeys("Asdfghjkl123");
     driver
         .findElement(By.xpath("html/body/form/table/tbody/tr/td/div/center[2]/input[1]"))
         .click();
     driver.findElement(By.xpath("html/body/div/div/table/tbody/tr[2]/td[1]/a")).click();
     driver.findElement(By.xpath("html/body/form/table/tbody/tr/td[1]/input[2]")).click();
     List<WebElement> list =
         driver.findElements(
             By.xpath(
                 "//*[contains(text(),'"
                     + "Nessun paziente selezionato o nessun indirizzo email inserito."
                     + "')]"));
     Assert.assertTrue(
         list.size() > 0, "Nessun paziente selezionato o nessun indirizzo email inserito.");
     System.out.println("Test Passed");
   } catch (AssertionError e) {
     System.out.println("Test Failed");
     System.out.println(e.getMessage());
   }
   driver.close();
 }
コード例 #24
0
  @Test(enabled = true)
  public void testShellAccess() throws IOException {
    final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
    serversToDeleteAfterTheTests.add(nameOfServer);

    Set<Ip> availableIps = client.getIpServices().getUnassignedIpList();
    Ip availableIp = Iterables.getLast(availableIps);

    Server createdServer =
        client
            .getServerServices()
            .addServer(
                nameOfServer, "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", "1", availableIp.getIp());
    assertNotNull(createdServer);
    assert serverLatestJobCompleted.apply(createdServer);

    // get server by name
    Set<Server> response = client.getServerServices().getServersByName(nameOfServer);
    assert (response.size() == 1);
    createdServer = Iterables.getOnlyElement(response);

    Map<String, Credentials> credsMap = client.getServerServices().getServerCredentialsList();
    LoginCredentials instanceCredentials =
        LoginCredentials.fromCredentials(credsMap.get(createdServer.getName()));
    assertNotNull(instanceCredentials);

    HostAndPort socket = HostAndPort.fromParts(createdServer.getIp().getIp(), 22);

    Predicate<HostAndPort> socketOpen = retry(new InetSocketAddressConnect(), 180, 5, SECONDS);

    socketOpen.apply(socket);

    SshClient sshClient =
        gocontext
            .utils()
            .injector()
            .getInstance(SshClient.Factory.class)
            .create(socket, instanceCredentials);
    sshClient.connect();
    String output = sshClient.exec("df").getOutput();
    assertTrue(
        output.contains("Filesystem"),
        "The output should've contained filesystem information, but it didn't. Output: " + output);
    sshClient.disconnect();

    // check that the get credentials call is the same as this
    assertEquals(
        client.getServerServices().getServerCredentials(createdServer.getId()),
        instanceCredentials);

    try {
      assertEquals(client.getServerServices().getServerCredentials(Long.MAX_VALUE), null);
    } catch (AssertionError e) {
      e.printStackTrace();
    }

    // delete the server
    client.getServerServices().deleteByName(nameOfServer);
  }
コード例 #25
0
 @Test
 public void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() {
   try {
     integersWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), 0);
   } catch (AssertionError e) {
     assertEquals(e.getMessage(), "<0> should not be equal to:<0>");
   }
 }
コード例 #26
0
 @Test
 public void should_fail_since_actual_is_zero_whatever_custom_comparison_strategy_is() {
   try {
     floatsWithAbsValueComparisonStrategy.assertIsZero(someInfo(), 2.0f);
   } catch (AssertionError e) {
     assertThat(e.getMessage()).isEqualTo("expected:<[0].0f> but was:<[2].0f>");
   }
 }
コード例 #27
0
 @Test
 public void should_fail_since_actual_is_not_zero() {
   try {
     floats.assertIsZero(someInfo(), 2.0f);
   } catch (AssertionError e) {
     assertThat(e.getMessage()).isEqualTo("expected:<[0].0f> but was:<[2].0f>");
   }
 }
コード例 #28
0
 @Test
 public void should_fail_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() {
   try {
     bigDecimalsWithComparatorComparisonStrategy.assertIsZero(someInfo(), BigDecimal.ONE);
   } catch (AssertionError e) {
     assertThat(e.getMessage()).isEqualTo("expected:<[0]> but was:<[1]>");
   }
 }
コード例 #29
0
 public SingleLineClause withErrorContaining(final String messageFragment) {
   try {
     return new SingleLineClause(unsuccessful.withErrorContaining(messageFragment).in(source));
   } catch (AssertionError e) {
     failureStrategy.fail(e.getMessage());
   }
   return null;
 }
コード例 #30
0
 @Test
 public void should_fail_since_actual_is_not_zero() {
   try {
     bigDecimals.assertIsZero(someInfo(), BigDecimal.ONE);
   } catch (AssertionError e) {
     assertThat(e.getMessage()).isEqualTo("expected:<[0]> but was:<[1]>");
   }
 }