Java Code Examples for org.junit.Assert#assertArrayEquals()

The following examples show how to use org.junit.Assert#assertArrayEquals() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: neoscada   File: Test1.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Perform a common subscribe/unsubscribe with a subscriptions source being
 * present
 * before the subscription.
 * 
 * @throws Exception
 */
@Test
public void test3 () throws Exception
{
    final SubscriptionRecorder<String> recorder = new SubscriptionRecorder<String> ();
    final SubscriptionSourceTestImpl<String> source = new SubscriptionSourceTestImpl<String> ();

    this.manager.setSource ( "", source );
    this.manager.subscribe ( "", recorder );
    this.manager.unsubscribe ( "", recorder );
    this.manager.setSource ( "", null );

    Assert.assertArrayEquals ( "Events are not the same", new Object[] { new SubscriptionStateEvent ( SubscriptionState.CONNECTED ), new SubscriptionSourceEvent<String> ( true, source ), new SubscriptionSourceEvent<String> ( false, source ), new SubscriptionStateEvent ( SubscriptionState.DISCONNECTED ) }, recorder.getList ().toArray ( new Object[0] ) );

    Assert.assertEquals ( "Number of subscriptions does not match", 0, this.manager.getSubscriptionCount () );
}
 
Example 2
@Test
public void testNetcdf2D() throws Exception {
  String filename = TestDir.cdmUnitTestDir + "conventions/cf/mississippi.nc";
  logger.debug("open {}", filename);

  try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(filename)) {
    Assert.assertNotNull(filename, cc);
    CoverageCollection gcs = cc.findCoverageDataset(FeatureType.CURVILINEAR);
    Assert.assertNotNull("gcs", gcs);
    String gribId = "salt";
    Coverage coverage = gcs.findCoverage(gribId);
    Assert.assertNotNull(gribId, coverage);

    CoverageCoordSys cs = coverage.getCoordSys();
    Assert.assertNotNull("coordSys", cs);
    HorizCoordSys hcs = cs.getHorizCoordSys();
    Assert.assertNotNull("HorizCoordSys", hcs);

    int[] expectedOrgShape = new int[] {1, 20, 64, 128};
    Assert.assertArrayEquals(expectedOrgShape, cs.getShape());
    logger.debug("org shape={}", Arrays.toString(cs.getShape()));

    // just try to bisect ot along the width
    LatLonRect bbox = new LatLonRect(LatLonPoint.create(90, -180), LatLonPoint.create(-90, -90));

    SubsetParams params = new SubsetParams().set(SubsetParams.timePresent, true).set(SubsetParams.latlonBB, bbox);
    GeoReferencedArray geo = coverage.readData(params);
    logger.debug("geoCs shape={}", Arrays.toString(geo.getCoordSysForData().getShape()));

    Array data = geo.getData();
    logger.debug("data shape={}", Arrays.toString(data.getShape()));
    Assert.assertArrayEquals(geo.getCoordSysForData().getShape(), data.getShape());

    int[] expectedShape = new int[] {1, 20, 64, 75};
    Assert.assertArrayEquals(expectedShape, data.getShape());
  }
}
 
Example 3
@Test
public void testEncode() throws Exception
{
	byte[] data = new byte[1000];
	Random random = new Random(42L);
	random.nextBytes(data);

	Container container = new Container(CompressionType.NONE, -1);
	container.compress(data, null);
	byte[] compressedData = container.data;

	ArchiveResponsePacket archiveResponse = new ArchiveResponsePacket();
	archiveResponse.setIndex(0);
	archiveResponse.setArchive(1);
	archiveResponse.setData(compressedData);

	ByteBuf buf = Unpooled.buffer(1024);
	ArchiveResponseEncoder encoder = new ArchiveResponseEncoder();
	encoder.encode(null, archiveResponse, buf);

	ArchiveResponseDecoder decoder = new ArchiveResponseDecoder();
	List<Object> out = new ArrayList<>();
	decoder.decode(null, buf, out);

	Assert.assertEquals(1, out.size());
	ArchiveResponsePacket response = (ArchiveResponsePacket) out.get(0);

	Assert.assertEquals(archiveResponse.getIndex(), response.getIndex());
	Assert.assertEquals(archiveResponse.getArchive(), response.getArchive());
	Assert.assertArrayEquals(archiveResponse.getData(), response.getData());

	byte[] decompressedData = Container.decompress(response.getData(), null).data;
	Assert.assertArrayEquals(data, decompressedData);
}
 
Example 4
Source Project: AVM   File: ABIDecoderTest.java    License: MIT License 5 votes vote down vote up
@Test
public void bigIntegerArrayDecoding() {
    BigInteger[] bigIntegers = new BigInteger[3];
    bigIntegers[0] = new BigInteger(0, new byte[]{0});
    bigIntegers[1] = new BigInteger(1, new byte[]{127, 126, 5});
    bigIntegers[2] = new BigInteger(-1, new byte[]{10, 11});

    byte[] encoded = new byte[]{ABIToken.ARRAY, ABIToken.BIGINT, 0, 3, ABIToken.BIGINT, 1, 0, ABIToken.BIGINT, 3, 127, 126, 5, ABIToken.BIGINT, 2, -11, -11};
    ABIDecoder decoder = new ABIDecoder(encoded);
    Assert.assertArrayEquals(bigIntegers, decoder.decodeOneBigIntegerArray());

    bigIntegers[0] = new BigInteger(0, new byte[]{0});
    bigIntegers[1] = null;
    bigIntegers[2] = new BigInteger(-1, new byte[]{10, 11});
    encoded = new byte[]{ABIToken.ARRAY, ABIToken.BIGINT, 0, 3, ABIToken.BIGINT, 1, 0, ABIToken.NULL, ABIToken.BIGINT, ABIToken.BIGINT, 2, -11, -11};
    decoder = new ABIDecoder(encoded);
    Assert.assertArrayEquals(bigIntegers, decoder.decodeOneBigIntegerArray());

    bigIntegers[0] = null;
    bigIntegers[1] = null;
    bigIntegers[2] = null;
    encoded = new byte[]{ABIToken.ARRAY, ABIToken.BIGINT, 0, 3, ABIToken.NULL, ABIToken.BIGINT, ABIToken.NULL, ABIToken.BIGINT, ABIToken.NULL, ABIToken.BIGINT};
    decoder = new ABIDecoder(encoded);
    Assert.assertArrayEquals(bigIntegers, decoder.decodeOneBigIntegerArray());

    bigIntegers = null;
    encoded = new byte[]{ABIToken.NULL, ABIToken.ARRAY, ABIToken.BIGINT};
    decoder = new ABIDecoder(encoded);
    Assert.assertArrayEquals(bigIntegers, decoder.decodeOneBigIntegerArray());
}
 
Example 5
Source Project: arthas   File: StringUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTokenizeToStringArray() {
    Assert.assertNull(StringUtils.tokenizeToStringArray(null, "?", true, false));
    Assert.assertArrayEquals(new String[] {},
        StringUtils.tokenizeToStringArray("", "\"\"", false, false));
    Assert.assertArrayEquals(new String[] {"bar", "baz", "foo  "},
        StringUtils.tokenizeToStringArray("bar,baz,foo  ,,", ",", false, true));
    Assert.assertArrayEquals(new String[] {"bar", "baz", "foo  "},
        StringUtils.tokenizeToStringArray("bar,baz,foo  ,,", ",", false, false));

    Assert.assertArrayEquals(new String[] {"bar", "baz", "foo"},
        StringUtils.tokenizeToStringArray("bar,baz,foo  ,,", ","));
}
 
Example 6
Source Project: cidrawing   File: ListUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testShiftItemNormal() {
    List<String> list = Arrays.asList("A", "B", "C", "D", "E");
    ListUtils.shiftItem(list, 2, 1);
    Assert.assertArrayEquals(new String[]{"A", "B", "D", "C", "E"}, list.toArray());

    ListUtils.shiftItem(list, 2, -1);
    Assert.assertArrayEquals(new String[]{"A", "D", "B", "C", "E"}, list.toArray());
}
 
Example 7
Source Project: julongchain   File: GmCspTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void encryptAndDecryptTest() throws CspException {
    byte[] testData = Hex.decode("01234567454545");
    IKey sm4Key = csp.keyGen(new SM4KeyGenOpts());
    byte[] encryptData = csp.encrypt(sm4Key, testData, new SM4EncrypterOpts());
    byte[] plainText = csp.decrypt(sm4Key, encryptData, new SM4DecrypterOpts());
    Assert.assertArrayEquals(testData, plainText);
    System.out.println("plainText:" + Hex.toHexString(plainText));
}
 
Example 8
public byte[] runEncryptDecrypt(SecretKey key, String algorithm) throws Exception {
    byte[] indata = input.clone();
    byte[] cipher = encrypt(indata, key, algorithm);
    byte[] plain = decrypt(cipher, key, algorithm);
    Assert.assertArrayEquals(indata, plain);
    return plain;
}
 
Example 9
Source Project: Alink   File: BLASTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGemvSparse() throws Exception {
    DenseVector y1 = DenseVector.ones(2);
    BLAS.gemv(2.0, mat, false, spv2, 0., y1);
    Assert.assertArrayEquals(new double[]{20, 44}, y1.data, TOL);

    DenseVector y2 = DenseVector.ones(2);
    BLAS.gemv(2.0, mat, false, spv2, 1., y2);
    Assert.assertArrayEquals(new double[]{21, 45}, y2.data, TOL);
}
 
Example 10
@Test
public void test() throws Exception {
    final TransposeAndDotUDAF tad = new TransposeAndDotUDAF();

    final double[][] matrix0 = new double[][] {{1, -2}, {-1, 3}};
    final double[][] matrix1 = new double[][] {{1, 2}, {3, 4}};

    final ObjectInspector[] OIs = new ObjectInspector[] {
            ObjectInspectorFactory.getStandardListObjectInspector(
                PrimitiveObjectInspectorFactory.writableDoubleObjectInspector),
            ObjectInspectorFactory.getStandardListObjectInspector(
                PrimitiveObjectInspectorFactory.writableDoubleObjectInspector)};
    final GenericUDAFEvaluator evaluator =
            tad.getEvaluator(new SimpleGenericUDAFParameterInfo(OIs, false, false));
    evaluator.init(GenericUDAFEvaluator.Mode.PARTIAL1, OIs);
    TransposeAndDotUDAF.TransposeAndDotUDAFEvaluator.TransposeAndDotAggregationBuffer agg =
            (TransposeAndDotUDAF.TransposeAndDotUDAFEvaluator.TransposeAndDotAggregationBuffer) evaluator.getNewAggregationBuffer();
    evaluator.reset(agg);
    for (int i = 0; i < matrix0.length; i++) {
        evaluator.iterate(agg, new Object[] {WritableUtils.toWritableList(matrix0[i]),
                WritableUtils.toWritableList(matrix1[i])});
    }

    final double[][] answer = new double[][] {{-2.0, -2.0}, {7.0, 8.0}};

    for (int i = 0; i < answer.length; i++) {
        Assert.assertArrayEquals(answer[i], agg.aggMatrix[i], 0.d);
    }
}
 
Example 11
@Test
public void testPermuteCycle() throws Exception {
  MemoryWarpScriptStack stack = new MemoryWarpScriptStack(null, null);
  stack.maxLimits();

  stack.execMulti(new String(Files.readAllBytes(FILE_1), StandardCharsets.UTF_8));
  stack.execMulti("[ 3 0 1 2 ] PERMUTE ->JSON");

  stack.execMulti(new String(Files.readAllBytes(FILE_3), StandardCharsets.UTF_8));
  stack.execMulti("->JSON");

  Assert.assertArrayEquals(((String) stack.pop()).toCharArray(), ((String) stack.pop()).toCharArray());
  stack.execMulti("DEPTH 0 == ASSERT");
}
 
Example 12
Source Project: sfs   File: VertxAssert.java    License: Apache License 2.0 5 votes vote down vote up
public static void assertArrayEquals(TestContext context, String message, Object[] expected, Object[] actual) {
    try {
        Assert.assertArrayEquals(message, expected, actual);
    } catch (Throwable e) {
        context.fail(e);
    }
}
 
Example 13
@Test
public void testWrapUnwrapSecretKey_ShouldReturnTheOriginalKey() throws Exception {

    // GIVEN
    FieldLevelEncryptionConfig config = TestUtils.getTestFieldLevelEncryptionConfigBuilder().build();
    byte[] originalKeyBytes = base64Decode("mZzmzoURXI3Vk0vdsPkcFw==");
    SecretKey originalKey = new SecretKeySpec(originalKeyBytes, 0, originalKeyBytes.length, SYMMETRIC_KEY_TYPE);

    // WHEN
    byte[] wrappedKeyBytes = FieldLevelEncryptionParams.wrapSecretKey(config, originalKey);
    Key unwrappedKey = FieldLevelEncryptionParams.unwrapSecretKey(config, wrappedKeyBytes, config.oaepPaddingDigestAlgorithm);

    // THEN
    Assert.assertArrayEquals(originalKey.getEncoded(), unwrappedKey.getEncoded());
}
 
Example 14
Source Project: tls-sig-api-java   File: TestBase64.java    License: MIT License 5 votes vote down vote up
@Test
public void base64() {
    byte[] res = base64_url.base64EncodeUrl("123".getBytes());
    Assert.assertArrayEquals("MTIz".getBytes(), res);

    res = base64_url.base64DecodeUrl(res);
    Assert.assertArrayEquals("123".getBytes(), res);

    res = base64_url.base64EncodeUrl("1".getBytes());
    Assert.assertArrayEquals("MQ__".getBytes(), res);

    res = base64_url.base64DecodeUrl(res);
    Assert.assertArrayEquals("1".getBytes(), res);
}
 
Example 15
Source Project: sofa-dashboard   File: AppServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void queryStatisticsByKeyWordTest() throws Exception {
    long current = System.currentTimeMillis();
    for (String[] pattern : new String[][] { { "10.1.1.1", "service_a" },
                                             { "10.1.1.2", "service_b" },
                                             { "10.1.1.3", "service_c" },
                                             { "10.1.1.4", "service_d" },
                                             { "10.1.1.5", "service_d" } }) {
        registry.publisher(
            Application.newBuilder().appState("NORMAL").startTime(current)
                .lastRecover(System.currentTimeMillis()).hostName(pattern[0])
                .appName(pattern[1]).port(random.nextInt(65536)).build()).register();
    }

    for (String keyword : new String[] { "a", "service", "d", "f" }) {
        List<ApplicationInfo> expected = registry.all().stream()
            .filter(it -> it.getAppName().contains(keyword))
            .collect(Collectors.groupingBy(it -> it.getAppName(), Collectors.counting()))
            .entrySet().stream()
            .map(entry -> {
                ApplicationInfo statistic = new ApplicationInfo();
                statistic.setApplicationName(entry.getKey());
                statistic.setApplicationCount(entry.getValue().intValue());
                return statistic;
            })
            .collect(Collectors.toList());
        List<ApplicationInfo> query = service.getStatisticsByKeyword(keyword);

        Collections.sort(expected);
        Collections.sort(query);
        Assert.assertArrayEquals(expected.toArray(), query.toArray());
    }
}
 
Example 16
@Test
public void NotFoundAccount() {
    String smsTpl = "ECMC{{A}} {{D}} покупка {{P}}р TEREMOK METROPOLIS Баланс: {{B}}р";
    String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р";

    String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms);
    Assert.assertArrayEquals(new String[]{null, "5431", "49820.45", "01.10.17 19:50", "550", null}, matches);

    SmsTemplateBuilder.withDb(db).title("900").categoryId(18).template(smsTpl).create();
    Transaction transaction = smsProcessor.createTransactionBySms("900", sms, status, true);

    assertNull(transaction);
}
 
Example 17
Source Project: beam   File: ShuffleReaderFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
void runTestCreateGroupingShuffleReader(
    byte[] shuffleReaderConfig,
    @Nullable String start,
    @Nullable String end,
    Coder<?> keyCoder,
    Coder<?> valueCoder)
    throws Exception {
  BatchModeExecutionContext context =
      BatchModeExecutionContext.forTesting(PipelineOptionsFactory.create(), "testStage");
  GroupingShuffleReader groupingShuffleReader =
      runTestCreateShuffleReader(
          shuffleReaderConfig,
          start,
          end,
          CloudObjects.asCloudObject(
              FullWindowedValueCoder.of(
                  KvCoder.of(keyCoder, IterableCoder.of(valueCoder)), IntervalWindowCoder.of()),
              /*sdkComponents=*/ null),
          context,
          GroupingShuffleReader.class,
          "GroupingShuffleSource");
  Assert.assertArrayEquals(shuffleReaderConfig, groupingShuffleReader.shuffleReaderConfig);
  Assert.assertEquals(start, groupingShuffleReader.startShufflePosition);
  Assert.assertEquals(end, groupingShuffleReader.stopShufflePosition);

  Assert.assertEquals(keyCoder, groupingShuffleReader.keyCoder);
  Assert.assertEquals(valueCoder, groupingShuffleReader.valueCoder);
  Assert.assertEquals(context, groupingShuffleReader.executionContext);
}
 
Example 18
@Test
public void testSessionSize() throws Exception {
    final int port1 = SSLTestUtils.PORT;
    final int port2 = SSLTestUtils.SECONDARY_PORT;

    try (
            ServerSocket serverSocket1 = SSLTestUtils.createServerSocket(port1);
            ServerSocket serverSocket2 = SSLTestUtils.createServerSocket(port2)
    ) {

        final Thread acceptThread1 = startServer(serverSocket1);
        final Thread acceptThread2 = startServer(serverSocket2);
        SSLContext clientContext = SSLTestUtils.createClientSSLContext("openssl.TLSv1");

        final SSLSessionContext clientSession = clientContext.getClientSessionContext();

        byte[] host1SessionId = connectAndWrite(clientContext, port1);
        byte[] host2SessionId = connectAndWrite(clientContext, port2);

        // No cache limit was set, id's should be identical
        Assert.assertArrayEquals(host1SessionId, connectAndWrite(clientContext, port1));
        Assert.assertArrayEquals(host2SessionId, connectAndWrite(clientContext, port2));

        // Set the cache size to 1
        clientSession.setSessionCacheSize(1);
        // The second session id should be the one kept as it was the last one used
        Assert.assertArrayEquals(host2SessionId, connectAndWrite(clientContext, port2));
        // Connect again to the first host, this should not match the initial session id for the first host
        byte[] nextId = connectAndWrite(clientContext, port1);
        Assert.assertFalse(Arrays.equals(host1SessionId, nextId));
        // Once more connect to the first host and this should match the previous session id
        Assert.assertArrayEquals(nextId, connectAndWrite(clientContext, port1));
        // Connect to the second host which should be purged at this point
        Assert.assertFalse(Arrays.equals(nextId, connectAndWrite(clientContext, port2)));

        // Reset the cache limit and ensure both sessions are cached
        clientSession.setSessionCacheSize(0);
        host1SessionId = connectAndWrite(clientContext, port1);
        host2SessionId = connectAndWrite(clientContext, port2);

        // No cache limit was set, id's should be identical
        Assert.assertArrayEquals(host1SessionId, connectAndWrite(clientContext, port1));
        Assert.assertArrayEquals(host2SessionId, connectAndWrite(clientContext, port2));

        serverSocket1.close();
        serverSocket2.close();
        acceptThread1.join();
        acceptThread2.join();
    }
}
 
Example 19
Source Project: code   File: Solution2.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    //Assert.assertArrayEquals(new int[]{1, 2}, new Solution2().twoSum(new int[]{2, 7, 11, 15}, 9));
    Assert.assertArrayEquals(new int[]{1, 3}, new Solution2().twoSum(new int[]{2, 3, 4}, 6));
}
 
Example 20
Source Project: AVM   File: BigIntegerTest.java    License: MIT License 4 votes vote down vote up
@Test
public void min() {
    Assert.assertArrayEquals(testValue32Bytes.min(testValue32Bytes).toByteArray(),
            (byte[]) callStatic("min", testValue32Bytes.toByteArray()).getDecodedReturnData());
}