How to use Interface Assert.ThrowingRunnable class of org.testng package

Best Testng code snippet using org.testng.Interface Assert.ThrowingRunnable

Source:MyAssert.java Github

copy

Full Screen

1package com.utils.asserts;2import com.utils.log.LoggerController;3import com.utils.screenshot.Screenshot;4import org.testng.Assert;5import org.testng.collections.Lists;6import org.testng.internal.EclipseInterface;7import java.lang.reflect.Array;8import java.util.*;9import java.util.regex.Pattern;10public class MyAssert {11 private final static LoggerController log = LoggerController.getLogger(MyAssert.class);12 /**13 * 断言字符是否已某个字符串开头14 *15 * @param message 断言错误消息16 * @param content 待断言字符串17 * @param prefix 前缀表达式18 */19 public static void assertStartWith(String content, String prefix, String message) {20 if (message != null)21 log.info(message);22 if (content.startsWith(prefix)) {23 log.info("前缀匹配校验成功");24 } else {25 log.error("前缀匹配校验失败!\n待校验的字符窜为:" + content + "\n校验的前缀表达式为:" + prefix);26 MyAssert.fail();27 }28 }29 /**30 * 断言字符是否已某个字符串开头31 *32 * @param content 待断言字符串33 * @param prefix 前缀表达式34 */35 public static void assertStartWith(String content, String prefix) {36 MyAssert.assertStartWith(content, prefix, null);37 }38 /**39 * 断言字符是否已某个字符串结尾40 *41 * @param message 断言错误消息42 * @param content 待断言字符串43 * @param endfix 前缀表达式44 */45 public static void assertEndWith(String content, String endfix, String message) {46 if (message != null)47 log.info(message);48 if (content.endsWith(endfix)) {49 log.info("后缀匹配校验成功!");50 } else {51 log.error("后缀匹配校验失败!\n待校验的字符窜为:" + content + "\n校验的后缀表达式为:" + endfix);52 MyAssert.fail();53 }54 }55 /**56 * 断言字符是否已某个字符串结尾57 *58 * @param content 待断言字符串59 * @param endfix 前缀表达式60 */61 public static void assertEndWith(String content, String endfix) {62 MyAssert.assertEndWith(content, endfix, null);63 }64 /**65 * 根据正则表达式断言是否匹配66 *67 * @param message 断言错误信息68 * @param matcher 待校验的字符串69 * @param regex 校验的正则表达式70 */71 public static void assertMatch(String matcher, String regex, String message) {72 if (message != null)73 log.info(message);74 if (Pattern.matches(regex, matcher)) {75 log.info("匹配校验成功!");76 } else {77 log.error("匹配校验失败!\n待校验的字符串为:" + matcher + "\n校验的正则表达式为:" + regex);78 MyAssert.fail();79 }80 }81 /**82 * 根据正则表达式断言是否匹配83 *84 * @param matcher 待校验的字符串85 * @param regex 校验的正则表达式86 */87 public static void assertMatch(String matcher, String regex) {88 MyAssert.assertMatch(matcher, regex, null);89 }90 /**91 * 根据正则表达式断言是否匹配92 *93 * @param message 断言错误信息94 * @param matcher 待校验的字符串95 * @param regex 校验的正则表达式96 */97 public static void assertNoMatch(String matcher, String regex, String message) {98 if (message != null)99 log.info(message);100 if (!Pattern.matches(regex, matcher)) {101 log.info("匹配校验成功!");102 } else {103 log.error("匹配校验失败!\n待校验的字符串为:" + matcher + "\n校验的正则表达式为:" + regex);104 MyAssert.fail();105 }106 }107 /**108 * 根据正则表达式断言是否匹配109 *110 * @param matcher 待校验的字符串111 * @param regex 校验的正则表达式112 */113 public static void assertNoMatch(String matcher, String regex) {114 MyAssert.assertNoMatch(matcher, regex, null);115 }116 /**117 * 断言字符串中是否包含某些字符118 *119 * @param message 断言错误消息120 * @param content 断言的字符串为121 * @param included 包含的字符串122 */123 public static void assertInclude(String content, String included, String message) {124 if (message != null)125 log.info(message);126 if (content.contains(included)) {127 log.info("匹配校验成功!");128 } else {129 log.error("匹配校验失败!\n待校验的字符串为:" + content + "\n包含字符串为:" + included);130 MyAssert.fail(message);131 }132 }133 /**134 * 断言字符串中是否包含某些字符135 *136 * @param content 断言的字符串为137 * @param included 包含的字符串138 */139 public static void assertInclude(String content, String included) {140 MyAssert.assertInclude(content, included, null);141 }142 public static void assertTrue(boolean condition, String message) {143 if (!condition) {144 failNotEquals(condition, Boolean.TRUE, message);145 }146 }147 public static void assertTrue(boolean condition) {148 assertTrue(condition, (String)null);149 }150 public static void assertFalse(boolean condition, String message) {151 if (condition) {152 failNotEquals(condition, Boolean.FALSE, message);153 }154 }155 public static void assertFalse(boolean condition) {156 assertFalse(condition, (String)null);157 }158 public static void fail(String message, Throwable realCause) {159 AssertionError ae = new AssertionError(message);160 ae.initCause(realCause);161 throw ae;162 }163 public static void fail(String message) {164 //Screenshot.screenshot("assert_fail_");165 log.error("Assert fail");166 throw new AssertionError(message);167 }168 public static void fail() {169 fail((String)null);170 }171 public static void assertEquals(Object actual, Object expected, String message) {172 if (expected != null && expected.getClass().isArray()) {173 assertArrayEquals(actual, expected, message);174 } else {175 assertEqualsImpl(actual, expected, message);176 }177 }178 private static void assertEqualsImpl(Object actual, Object expected, String message) {179 if (expected != null || actual != null) {180 if (expected == null ^ actual == null) {181 failNotEquals(actual, expected, message);182 }183 if (!expected.equals(actual) || !actual.equals(expected)) {184 fail(format(actual, expected, message, true));185 }186 }187 }188 private static void assertArrayEquals(Object actual, Object expected, String message) {189 if (expected != actual) {190 if (null == expected) {191 fail("expected a null array, but not null found. " + message);192 }193 if (null == actual) {194 fail("expected not null array, but null found. " + message);195 }196 if (!actual.getClass().isArray()) {197 failNotEquals(actual, expected, message);198 }199 int expectedLength = Array.getLength(expected);200 if (expectedLength != Array.getLength(actual)) {201 failNotEquals(Array.getLength(actual), expectedLength, message == null ? "" : message + " (Array lengths are not the same)");202 }203 for(int i = 0; i < expectedLength; ++i) {204 Object _actual = Array.get(actual, i);205 Object _expected = Array.get(expected, i);206 try {207 assertEquals(_actual, _expected);208 } catch (AssertionError var8) {209 failNotEquals(actual, expected, message == null ? "" : message + " (values at index " + i + " are not the same)");210 }211 }212 }213 }214 public static void assertEquals(byte[] actual, byte[] expected) {215 assertEquals(actual, expected, "");216 }217 public static void assertEquals(byte[] actual, byte[] expected, String message) {218 if (!checkRefEqualityAndLength(actual, expected, message)) {219 for(int i = 0; i < expected.length; ++i) {220 if (expected[i] != actual[i]) {221 fail(String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Byte.toString(expected[i]), Byte.toString(actual[i]), message));222 }223 }224 }225 }226 public static void assertEquals(short[] actual, short[] expected) {227 assertEquals(actual, expected, "");228 }229 public static void assertEquals(short[] actual, short[] expected, String message) {230 if (!checkRefEqualityAndLength(actual, expected, message)) {231 for(int i = 0; i < expected.length; ++i) {232 if (expected[i] != actual[i]) {233 fail(String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Short.toString(expected[i]), Short.toString(actual[i]), message));234 }235 }236 }237 }238 public static void assertEquals(int[] actual, int[] expected) {239 assertEquals(actual, expected, "");240 }241 public static void assertEquals(int[] actual, int[] expected, String message) {242 if (!checkRefEqualityAndLength(actual, expected, message)) {243 for(int i = 0; i < expected.length; ++i) {244 if (expected[i] != actual[i]) {245 fail(String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Integer.toString(expected[i]), Integer.toString(actual[i]), message));246 }247 }248 }249 }250 public static void assertEquals(boolean[] actual, boolean[] expected) {251 assertEquals(actual, expected, "");252 }253 public static void assertEquals(boolean[] actual, boolean[] expected, String message) {254 if (!checkRefEqualityAndLength(actual, expected, message)) {255 for(int i = 0; i < expected.length; ++i) {256 if (expected[i] != actual[i]) {257 fail(String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Boolean.toString(expected[i]), Boolean.toString(actual[i]), message));258 }259 }260 }261 }262 public static void assertEquals(char[] actual, char[] expected) {263 assertEquals(actual, expected, "");264 }265 public static void assertEquals(char[] actual, char[] expected, String message) {266 if (!checkRefEqualityAndLength(actual, expected, message)) {267 for(int i = 0; i < expected.length; ++i) {268 if (expected[i] != actual[i]) {269 fail(String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Character.toString(expected[i]), Character.toString(actual[i]), message));270 }271 }272 }273 }274 public static void assertEquals(float[] actual, float[] expected) {275 assertEquals(actual, expected, "");276 }277 public static void assertEquals(float[] actual, float[] expected, String message) {278 if (!checkRefEqualityAndLength(actual, expected, message)) {279 for(int i = 0; i < expected.length; ++i) {280 assertEquals(actual[i], expected[i], String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Float.toString(expected[i]), Float.toString(actual[i]), message));281 }282 }283 }284 public static void assertEquals(float[] actual, float[] expected, float delta) {285 assertEquals(actual, expected, delta, "");286 }287 public static void assertEquals(float[] actual, float[] expected, float delta, String message) {288 if (!checkRefEqualityAndLength(actual, expected, message)) {289 for(int i = 0; i < expected.length; ++i) {290 assertEquals(actual[i], expected[i], delta, String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Float.toString(expected[i]), Float.toString(actual[i]), message));291 }292 }293 }294 public static void assertEquals(double[] actual, double[] expected) {295 assertEquals(actual, expected, "");296 }297 public static void assertEquals(double[] actual, double[] expected, String message) {298 if (!checkRefEqualityAndLength(actual, expected, message)) {299 for(int i = 0; i < expected.length; ++i) {300 assertEquals(actual[i], expected[i], String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Double.toString(expected[i]), Double.toString(actual[i]), message));301 }302 }303 }304 public static void assertEquals(double[] actual, double[] expected, double delta) {305 assertEquals(actual, expected, delta, "");306 }307 public static void assertEquals(double[] actual, double[] expected, double delta, String message) {308 if (!checkRefEqualityAndLength(actual, expected, message)) {309 for(int i = 0; i < expected.length; ++i) {310 assertEquals(actual[i], expected[i], delta, String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Double.toString(expected[i]), Double.toString(actual[i]), message));311 }312 }313 }314 public static void assertEquals(long[] actual, long[] expected) {315 assertEquals(actual, expected, "");316 }317 public static void assertEquals(long[] actual, long[] expected, String message) {318 if (!checkRefEqualityAndLength(actual, expected, message)) {319 for(int i = 0; i < expected.length; ++i) {320 if (expected[i] != actual[i]) {321 fail(String.format("arrays differ firstly at element [%LogEventListener]; expected value is <%s> but was <%s>. %s", i, Long.toString(expected[i]), Long.toString(actual[i]), message));322 }323 }324 }325 }326 private static boolean checkRefEqualityAndLength(Object actualArray, Object expectedArray, String message) {327 if (expectedArray == actualArray) {328 return true;329 } else {330 if (null == expectedArray) {331 fail("expectedArray a null array, but not null found. " + message);332 }333 if (null == actualArray) {334 fail("expectedArray not null array, but null found. " + message);335 }336 assertEquals(Array.getLength(actualArray), Array.getLength(expectedArray), "arrays don't have the same size. " + message);337 return false;338 }339 }340 public static void assertEquals(Object actual, Object expected) {341 assertEquals((Object)actual, (Object)expected, (String)null);342 }343 public static void assertEquals(String actual, String expected, String message) {344 assertEquals((Object)actual, (Object)expected, message);345 }346 public static void assertEquals(String actual, String expected) {347 assertEquals((String)actual, (String)expected, (String)null);348 }349 public static void assertEquals(double actual, double expected, double delta, String message) {350 if (Double.isInfinite(expected)) {351 if (expected != actual) {352 failNotEquals(actual, expected, message);353 }354 } else if (Double.isNaN(expected)) {355 if (!Double.isNaN(actual)) {356 failNotEquals(actual, expected, message);357 }358 } else if (Math.abs(expected - actual) > delta) {359 failNotEquals(actual, expected, message);360 }361 }362 public static void assertEquals(double actual, double expected, double delta) {363 assertEquals(actual, expected, delta, (String)null);364 }365 public static void assertEquals(double actual, double expected, String message) {366 if (Double.isNaN(expected)) {367 if (!Double.isNaN(actual)) {368 failNotEquals(actual, expected, message);369 }370 } else if (actual != expected) {371 failNotEquals(actual, expected, message);372 }373 }374 public static void assertEquals(double actual, double expected) {375 assertEquals(actual, expected, (String)null);376 }377 public static void assertEquals(float actual, float expected, float delta, String message) {378 if (Float.isInfinite(expected)) {379 if (expected != actual) {380 failNotEquals(actual, expected, message);381 }382 } else if (Float.isNaN(expected)) {383 if (!Float.isNaN(actual)) {384 failNotEquals(actual, expected, message);385 }386 } else if (Math.abs(expected - actual) > delta) {387 failNotEquals(actual, expected, message);388 }389 }390 public static void assertEquals(float actual, float expected, float delta) {391 assertEquals(actual, expected, delta, (String)null);392 }393 public static void assertEquals(float actual, float expected, String message) {394 if (Float.isNaN(expected)) {395 if (!Float.isNaN(actual)) {396 failNotEquals(actual, expected, message);397 }398 } else if (actual != expected) {399 failNotEquals(actual, expected, message);400 }401 }402 public static void assertEquals(float actual, float expected) {403 assertEquals(actual, expected, (String)null);404 }405 public static void assertEquals(long actual, long expected, String message) {406 assertEquals((Object)actual, (Object)expected, message);407 }408 public static void assertEquals(long actual, long expected) {409 assertEquals(actual, expected, (String)null);410 }411 public static void assertEquals(boolean actual, boolean expected, String message) {412 assertEquals((Object)actual, (Object)expected, message);413 }414 public static void assertEquals(boolean actual, boolean expected) {415 assertEquals(actual, expected, (String)null);416 }417 public static void assertEquals(byte actual, byte expected, String message) {418 assertEquals((Object)actual, (Object)expected, message);419 }420 public static void assertEquals(byte actual, byte expected) {421 assertEquals((byte)actual, (byte)expected, (String)null);422 }423 public static void assertEquals(char actual, char expected, String message) {424 assertEquals((Object)actual, (Object)expected, message);425 }426 public static void assertEquals(char actual, char expected) {427 assertEquals((char)actual, (char)expected, (String)null);428 }429 public static void assertEquals(short actual, short expected, String message) {430 assertEquals((Object)actual, (Object)expected, message);431 }432 public static void assertEquals(short actual, short expected) {433 assertEquals((short)actual, (short)expected, (String)null);434 }435 public static void assertEquals(int actual, int expected, String message) {436 assertEquals((Object)actual, (Object)expected, message);437 }438 public static void assertEquals(int actual, int expected) {439 assertEquals((int)actual, (int)expected, (String)null);440 }441 public static void assertNotNull(Object object) {442 assertNotNull(object, (String)null);443 }444 public static void assertNotNull(Object object, String message) {445 if (object == null) {446 String formatted = "";447 if (message != null) {448 formatted = message + " ";449 }450 fail(formatted + "expected object to not be null");451 }452 assertTrue(object != null, message);453 }454 public static void assertNull(Object object) {455 assertNull(object, (String)null);456 }457 public static void assertNull(Object object, String message) {458 if (object != null) {459 failNotSame(object, (Object)null, message);460 }461 }462 public static void assertSame(Object actual, Object expected, String message) {463 if (expected != actual) {464 failNotSame(actual, expected, message);465 }466 }467 public static void assertSame(Object actual, Object expected) {468 assertSame(actual, expected, (String)null);469 }470 public static void assertNotSame(Object actual, Object expected, String message) {471 if (expected == actual) {472 failSame(actual, expected, message);473 }474 }475 public static void assertNotSame(Object actual, Object expected) {476 assertNotSame(actual, expected, (String)null);477 }478 private static void failSame(Object actual, Object expected, String message) {479 String formatted = "";480 if (message != null) {481 formatted = message + " ";482 }483 fail(formatted + EclipseInterface.ASSERT_LEFT2 + expected + EclipseInterface.ASSERT_MIDDLE + actual + EclipseInterface.ASSERT_RIGHT);484 }485 private static void failNotSame(Object actual, Object expected, String message) {486 String formatted = "";487 if (message != null) {488 formatted = message + " ";489 }490 fail(formatted + EclipseInterface.ASSERT_EQUAL_LEFT + expected + EclipseInterface.ASSERT_MIDDLE + actual + EclipseInterface.ASSERT_RIGHT);491 }492 private static void failNotEquals(Object actual, Object expected, String message) {493 fail(format(actual, expected, message, true));494 }495 static String format(Object actual, Object expected, String message, boolean isAssertEquals) {496 String formatted = "";497 if (null != message) {498 formatted = message + " ";499 }500 return isAssertEquals ? formatted + EclipseInterface.ASSERT_EQUAL_LEFT + expected + EclipseInterface.ASSERT_MIDDLE + actual + EclipseInterface.ASSERT_RIGHT : formatted + EclipseInterface.ASSERT_UNEQUAL_LEFT + expected + EclipseInterface.ASSERT_MIDDLE + actual + EclipseInterface.ASSERT_RIGHT;501 }502 public static void assertEquals(Collection<?> actual, Collection<?> expected) {503 assertEquals((Collection)actual, (Collection)expected, (String)null);504 }505 public static void assertEquals(Collection<?> actual, Collection<?> expected, String message) {506 if (actual != expected) {507 if (actual == null || expected == null) {508 if (message != null) {509 fail(message);510 } else {511 fail("Collections not equal: expected: " + expected + " and actual: " + actual);512 }513 }514 assertEquals(actual.size(), expected.size(), (message == null ? "" : message + ": ") + "lists don't have the same size");515 Iterator<?> actIt = actual.iterator();516 Iterator<?> expIt = expected.iterator();517 int i = -1;518 while(actIt.hasNext() && expIt.hasNext()) {519 ++i;520 Object e = expIt.next();521 Object a = actIt.next();522 String explanation = "Lists differ at element [" + i + "]: " + e + " != " + a;523 String errorMessage = message == null ? explanation : message + ": " + explanation;524 assertEqualsImpl(a, e, errorMessage);525 }526 }527 }528 public static void assertEquals(Iterator<?> actual, Iterator<?> expected) {529 assertEquals((Iterator)actual, (Iterator)expected, (String)null);530 }531 public static void assertEquals(Iterator<?> actual, Iterator<?> expected, String message) {532 if (actual != expected) {533 if (actual == null || expected == null) {534 String msg = message != null ? message : "Iterators not equal: expected: " + expected + " and actual: " + actual;535 fail(msg);536 }537 int i = -1;538 while(actual.hasNext() && expected.hasNext()) {539 ++i;540 Object e = expected.next();541 Object a = actual.next();542 String explanation = "Iterators differ at element [" + i + "]: " + e + " != " + a;543 String errorMessage = message == null ? explanation : message + ": " + explanation;544 assertEqualsImpl(a, e, errorMessage);545 }546 String explanation;547 String errorMessage;548 if (actual.hasNext()) {549 explanation = "Actual iterator returned more elements than the expected iterator.";550 errorMessage = message == null ? explanation : message + ": " + explanation;551 fail(errorMessage);552 } else if (expected.hasNext()) {553 explanation = "Expected iterator returned more elements than the actual iterator.";554 errorMessage = message == null ? explanation : message + ": " + explanation;555 fail(errorMessage);556 }557 }558 }559 public static void assertEquals(Iterable<?> actual, Iterable<?> expected) {560 assertEquals((Iterable)actual, (Iterable)expected, (String)null);561 }562 public static void assertEquals(Iterable<?> actual, Iterable<?> expected, String message) {563 if (actual != expected) {564 if (actual == null || expected == null) {565 if (message != null) {566 fail(message);567 } else {568 fail("Iterables not equal: expected: " + expected + " and actual: " + actual);569 }570 }571 Iterator<?> actIt = actual.iterator();572 Iterator<?> expIt = expected.iterator();573 assertEquals(actIt, expIt, message);574 }575 }576 public static void assertEquals(Object[] actual, Object[] expected, String message) {577 if (actual != expected) {578 if (actual == null && expected != null || actual != null && expected == null) {579 if (message != null) {580 fail(message);581 } else {582 fail("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual));583 }584 }585 if (actual.length != expected.length) {586 failAssertNoEqual("Arrays do not have the same size:" + actual.length + " != " + expected.length, message);587 }588 for(int i = 0; i < expected.length; ++i) {589 Object e = expected[i];590 Object a = actual[i];591 String explanation = "Arrays differ at element [" + i + "]: " + e + " != " + a;592 String errorMessage = message == null ? explanation : message + ": " + explanation;593 if (a != null || e != null) {594 if (a == null && e != null || a != null && e == null) {595 failNotEquals(a, e, message);596 }597 if (e.getClass().isArray()) {598 assertEquals(a, e, errorMessage);599 } else {600 assertEqualsImpl(a, e, errorMessage);601 }602 }603 }604 }605 }606 public static void assertEqualsNoOrder(Object[] actual, Object[] expected, String message) {607 if (actual != expected) {608 if (actual == null && expected != null || actual != null && expected == null) {609 failAssertNoEqual("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual), message);610 }611 if (actual.length != expected.length) {612 failAssertNoEqual("Arrays do not have the same size:" + actual.length + " != " + expected.length, message);613 }614 List<Object> actualCollection = Lists.newArrayList();615 actualCollection.addAll(Arrays.asList(actual));616 Object[] var4 = expected;617 int var5 = expected.length;618 for(int var6 = 0; var6 < var5; ++var6) {619 Object o = var4[var6];620 actualCollection.remove(o);621 }622 if (actualCollection.size() != 0) {623 failAssertNoEqual("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual), message);624 }625 }626 }627 private static void failAssertNoEqual(String defaultMessage, String message) {628 if (message != null) {629 fail(message);630 } else {631 fail(defaultMessage);632 }633 }634 public static void assertEquals(Object[] actual, Object[] expected) {635 assertEquals((Object[])actual, (Object[])expected, (String)null);636 }637 public static void assertEqualsNoOrder(Object[] actual, Object[] expected) {638 assertEqualsNoOrder(actual, expected, (String)null);639 }640 public static void assertEquals(Set<?> actual, Set<?> expected) {641 assertEquals((Set)actual, (Set)expected, (String)null);642 }643 public static void assertEquals(Set<?> actual, Set<?> expected, String message) {644 if (actual != expected) {645 if (actual == null || expected == null) {646 if (message == null) {647 fail("Sets not equal: expected: " + expected + " and actual: " + actual);648 } else {649 failNotEquals(actual, expected, message);650 }651 }652 if (!actual.equals(expected)) {653 if (message == null) {654 fail("Sets differ: expected " + expected + " but got " + actual);655 } else {656 failNotEquals(actual, expected, message);657 }658 }659 }660 }661 public static void assertEqualsDeep(Set<?> actual, Set<?> expected, String message) {662 if (actual != expected) {663 if (actual == null || expected == null) {664 if (message == null) {665 fail("Sets not equal: expected: " + expected + " and actual: " + actual);666 } else {667 failNotEquals(actual, expected, message);668 }669 }670 if (expected.size() != actual.size()) {671 if (message == null) {672 fail("Sets not equal: expected: " + expected + " and actual: " + actual);673 } else {674 fail(format(actual, expected, message, true));675 }676 }677 Iterator<?> actualIterator = actual.iterator();678 Iterator expectedIterator = expected.iterator();679 while(expectedIterator.hasNext()) {680 Object expectedValue = expectedIterator.next();681 Object value = actualIterator.next();682 if (expectedValue.getClass().isArray()) {683 assertArrayEquals(value, expectedValue, message);684 } else {685 assertEqualsImpl(value, expectedValue, message);686 }687 }688 }689 }690 public static void assertEquals(Map<?, ?> actual, Map<?, ?> expected) {691 assertEquals((Map)actual, (Map)expected, (String)null);692 }693 public static void assertEquals(Map<?, ?> actual, Map<?, ?> expected, String message) {694 if (actual != expected) {695 if (actual == null || expected == null) {696 fail("Maps not equal: expected: " + expected + " and actual: " + actual);697 }698 if (actual.size() != expected.size()) {699 fail("Maps do not have the same size:" + actual.size() + " != " + expected.size());700 }701 Set<?> entrySet = actual.entrySet();702 Iterator var4 = entrySet.iterator();703 while(var4.hasNext()) {704 Object anEntrySet = var4.next();705 Map.Entry<?, ?> entry = (Map.Entry)anEntrySet;706 Object key = entry.getKey();707 Object value = entry.getValue();708 Object expectedValue = expected.get(key);709 String assertMessage = message != null ? message : "Maps do not match for key:" + key + " actual:" + value + " expected:" + expectedValue;710 assertEqualsImpl(value, expectedValue, assertMessage);711 }712 }713 }714 public static void assertEqualsDeep(Map<?, ?> actual, Map<?, ?> expected) {715 assertEqualsDeep((Map)actual, (Map)expected, (String)null);716 }717 public static void assertEqualsDeep(Map<?, ?> actual, Map<?, ?> expected, String message) {718 if (actual != expected) {719 if (actual == null || expected == null) {720 fail("Maps not equal: expected: " + expected + " and actual: " + actual);721 }722 if (actual.size() != expected.size()) {723 fail("Maps do not have the same size:" + actual.size() + " != " + expected.size());724 }725 Set<?> entrySet = actual.entrySet();726 Iterator var4 = entrySet.iterator();727 while(var4.hasNext()) {728 Object anEntrySet = var4.next();729 Map.Entry<?, ?> entry = (Map.Entry)anEntrySet;730 Object key = entry.getKey();731 Object value = entry.getValue();732 Object expectedValue = expected.get(key);733 String assertMessage = message != null ? message : "Maps do not match for key:" + key + " actual:" + value + " expected:" + expectedValue;734 if (expectedValue.getClass().isArray()) {735 assertArrayEquals(value, expectedValue, assertMessage);736 } else {737 assertEqualsImpl(value, expectedValue, assertMessage);738 }739 }740 }741 }742 public static void assertNotEquals(Object actual1, Object actual2, String message) {743 boolean fail;744 try {745 assertEquals(actual1, actual2);746 fail = true;747 } catch (AssertionError var5) {748 fail = false;749 }750 if (fail) {751 fail(format(actual1, actual2, message, false));752 }753 }754 public static void assertNotEquals(Object actual1, Object actual2) {755 assertNotEquals((Object)actual1, (Object)actual2, (String)null);756 }757 static void assertNotEquals(String actual1, String actual2, String message) {758 assertNotEquals((Object)actual1, (Object)actual2, message);759 }760 static void assertNotEquals(String actual1, String actual2) {761 assertNotEquals((String)actual1, (String)actual2, (String)null);762 }763 static void assertNotEquals(long actual1, long actual2, String message) {764 assertNotEquals((Object)actual1, (Object)actual2, message);765 }766 static void assertNotEquals(long actual1, long actual2) {767 assertNotEquals(actual1, actual2, (String)null);768 }769 static void assertNotEquals(boolean actual1, boolean actual2, String message) {770 assertNotEquals((Object)actual1, (Object)actual2, message);771 }772 static void assertNotEquals(boolean actual1, boolean actual2) {773 assertNotEquals(actual1, actual2, (String)null);774 }775 static void assertNotEquals(byte actual1, byte actual2, String message) {776 assertNotEquals((Object)actual1, (Object)actual2, message);777 }778 static void assertNotEquals(byte actual1, byte actual2) {779 assertNotEquals((byte)actual1, (byte)actual2, (String)null);780 }781 static void assertNotEquals(char actual1, char actual2, String message) {782 assertNotEquals((Object)actual1, (Object)actual2, message);783 }784 static void assertNotEquals(char actual1, char actual2) {785 assertNotEquals((char)actual1, (char)actual2, (String)null);786 }787 static void assertNotEquals(short actual1, short actual2, String message) {788 assertNotEquals((Object)actual1, (Object)actual2, message);789 }790 static void assertNotEquals(short actual1, short actual2) {791 assertNotEquals((short)actual1, (short)actual2, (String)null);792 }793 static void assertNotEquals(int actual1, int actual2, String message) {794 assertNotEquals((Object)actual1, (Object)actual2, message);795 }796 static void assertNotEquals(int actual1, int actual2) {797 assertNotEquals((int)actual1, (int)actual2, (String)null);798 }799 public static void assertNotEquals(float actual1, float actual2, float delta, String message) {800 boolean fail;801 try {802 assertEquals(actual1, actual2, delta, message);803 fail = true;804 } catch (AssertionError var6) {805 fail = false;806 }807 if (fail) {808 fail(format(actual1, actual2, message, false));809 }810 }811 public static void assertNotEquals(float actual1, float actual2, float delta) {812 assertNotEquals(actual1, actual2, delta, (String)null);813 }814 public static void assertNotEquals(double actual1, double actual2, double delta, String message) {815 boolean fail;816 try {817 assertEquals(actual1, actual2, delta, message);818 fail = true;819 } catch (AssertionError var9) {820 fail = false;821 }822 if (fail) {823 fail(format(actual1, actual2, message, false));824 }825 }826 public static void assertNotEquals(Set<?> actual, Set<?> expected) {827 assertNotEquals((Set)actual, (Set)expected, (String)null);828 }829 public static void assertNotEquals(Set<?> actual, Set<?> expected, String message) {830 boolean fail;831 try {832 assertEquals(actual, expected, message);833 fail = true;834 } catch (AssertionError var5) {835 fail = false;836 }837 if (fail) {838 fail(format(actual, expected, message, false));839 }840 }841 public static void assertNotEqualsDeep(Set<?> actual, Set<?> expected) {842 assertNotEqualsDeep((Set)actual, (Set)expected, (String)null);843 }844 public static void assertNotEqualsDeep(Set<?> actual, Set<?> expected, String message) {845 boolean fail;846 try {847 assertEqualsDeep(actual, expected, message);848 fail = true;849 } catch (AssertionError var5) {850 fail = false;851 }852 if (fail) {853 fail(format(actual, expected, message, false));854 }855 }856 public static void assertNotEquals(Map<?, ?> actual, Map<?, ?> expected) {857 assertNotEquals((Map)actual, (Map)expected, (String)null);858 }859 public static void assertNotEquals(Map<?, ?> actual, Map<?, ?> expected, String message) {860 boolean fail;861 try {862 assertEquals(actual, expected, message);863 fail = true;864 } catch (AssertionError var5) {865 fail = false;866 }867 if (fail) {868 fail(format(actual, expected, message, false));869 }870 }871 public static void assertNotEqualsDeep(Map<?, ?> actual, Map<?, ?> expected) {872 assertNotEqualsDeep((Map)actual, (Map)expected, (String)null);873 }874 public static void assertNotEqualsDeep(Map<?, ?> actual, Map<?, ?> expected, String message) {875 boolean fail;876 try {877 assertEqualsDeep(actual, expected, message);878 fail = true;879 } catch (AssertionError var5) {880 fail = false;881 }882 if (fail) {883 fail(format(actual, expected, message, false));884 }885 }886 public static void assertNotEquals(double actual1, double actual2, double delta) {887 assertNotEquals(actual1, actual2, delta, (String)null);888 }889 public static void assertThrows(Assert.ThrowingRunnable runnable) {890 assertThrows(Throwable.class, runnable);891 }892 public static <T extends Throwable> void assertThrows(Class<T> throwableClass, Assert.ThrowingRunnable runnable) {893 expectThrows(throwableClass, runnable);894 }895 public static <T extends Throwable> T expectThrows(Class<T> throwableClass, Assert.ThrowingRunnable runnable) {896 try {897 runnable.run();898 } catch (Throwable var4) {899 if (throwableClass.isInstance(var4)) {900 return (T) throwableClass.cast(var4);901 }902 String mismatchMessage = String.format("Expected %s to be thrown, but %s was thrown", throwableClass.getSimpleName(), var4.getClass().getSimpleName());903 throw new AssertionError(mismatchMessage, var4);904 }905 String message = String.format("Expected %s to be thrown, but nothing was thrown", throwableClass.getSimpleName());906 throw new AssertionError(message);907 }908 public interface ThrowingRunnable {909 void run() throws Throwable;910 }911}...

Full Screen

Full Screen

Source:ContractServiceTest.java Github

copy

Full Screen

1package com.barclays.indiacp.test;2import static org.testng.Assert.*;3import com.barclays.indiacp.db.BlockScanner;4import com.barclays.indiacp.error.APIException;5import com.barclays.indiacp.model.Contract;6import com.barclays.indiacp.model.ContractABI;7import com.barclays.indiacp.model.Transaction;8import com.barclays.indiacp.model.Transaction.Input;9import com.barclays.indiacp.model.TransactionResult;10import com.barclays.indiacp.service.ContractService;11import com.barclays.indiacp.service.ContractService.CodeType;12import com.barclays.indiacp.service.GethHttpService;13import com.barclays.indiacp.service.TransactionService;14import java.io.IOException;15import java.math.BigInteger;16import java.util.List;17import java.util.Map;18import java.util.concurrent.TimeUnit;19import org.springframework.beans.factory.annotation.Autowired;20import org.testng.Assert.ThrowingRunnable;21import org.testng.annotations.Test;22public class ContractServiceTest extends BaseGethRpcTest {23 @Autowired24 private ContractService contractService;25 @Autowired26 private TransactionService transactionService;27 @Autowired28 private GethHttpService geth;29 @Autowired30 private BlockScanner blockScanner;31 @Test32 public void testCompile() throws IOException {33 long time = System.currentTimeMillis() / 1000;34 String code = readTestFile("contracts/simplestorage.sol");35 List<Contract> contracts = contractService.compile(code, CodeType.solidity, true);36 assertNotNull(contracts);37 assertEquals(1, contracts.size());38 Contract c = contracts.get(0);39 //StringUtils.puts(c);40 assertNotNull(c);41 assertNull(c.getAddress()); // only this field should be null42 assertNotEmptyString(c.getABI());43 assertNotEmptyString(c.getBinary());44 assertNotEmptyString(c.getCode());45 assertNotEmptyString(c.getName());46 assertEquals(c.getCodeType(), CodeType.solidity);47 assertNotNull(c.getCreatedDate());48 assertTrue(c.getCreatedDate() >= time);49 assertNotNull(c.getFunctionHashes());50 assertNotNull(c.getGasEstimates());51 Map<String, Object> gasEstimates = c.getGasEstimates();52 List<Long> creation = (List<Long>) gasEstimates.get("creation");53 assertNotNull(creation);54 assertEquals(creation.size(), 2);55 assertNotEmptyString(c.getSolidityInterface());56 }57 @Test58 public void testCreate() throws IOException {59 String code = readTestFile("contracts/simplestorage.sol");60 TransactionResult result = contractService.create(null, code, ContractService.CodeType.solidity, null, null, null, null);61 assertNotNull(result);62 assertNotNull(result.getId());63 assertTrue(!result.getId().isEmpty());64 }65 @Test66 public void testCreateWithBinary() throws IOException {67 String code = readTestFile("contracts/simplestorage.sol");68 List<Contract> contracts = contractService.compile(code, CodeType.solidity, true);69 Contract c = contracts.get(0);70 assertNotNull(c);71 TransactionResult result = contractService.create(null, code, CodeType.solidity, null, c.getBinary(), null, null);72 assertNotNull(result);73 assertNotNull(result.getId());74 assertTrue(!result.getId().isEmpty());75 }76 @Test77 public void testGet() throws IOException, InterruptedException {78 String contractAddress = createContract();79 Contract contract = contractService.get(contractAddress);80 assertNotNull(contract);81 assertNotNull(contract.getBinary(), "Binary code should be present");82 assertNotEquals(contract.getBinary(), "0x", "binary should not be '0x'");83 assertTrue(contract.getBinary().length() > 2);84 }85 @Test86 public void testGetInvalidId() throws APIException {87 assertThrows(APIException.class, new ThrowingRunnable() {88 @Override89 public void run() throws Throwable {90 contractService.get("0xdeadbeef");91 }92 });93 assertThrows(APIException.class, new ThrowingRunnable() {94 @Override95 public void run() throws Throwable {96 contractService.get("0x81635fe3d9cecbcf44aa58e967af1ab7ceefb816");97 }98 });99 }100 @Test101 public void testReadByABI() throws InterruptedException, IOException {102 String contractAddress = createContract();103 ContractABI abi = ContractABI.fromJson(readTestFile("contracts/simplestorage.abi.txt"));104 BigInteger val = (BigInteger) contractService.read(contractAddress, abi, null, "get", null, null)[0];105 assertEquals(val.intValue(), 100);106 }107 @Test108 public void testReadBytesArr() throws InterruptedException, IOException {109 String addr = createContract(readTestFile("contracts/testbytesarr.sol"), null);110 ContractABI abi = ContractABI.fromJson(readTestFile("contracts/testbytesarr.abi.txt"));111 Object[] res = (Object[]) contractService.read(addr, abi, null, "foo", null, null)[0];112 assertNotNull(res);113 assertEquals(res.length, 1);114 assertEquals(new String((byte[]) res[0]).trim(), "foobar");115 }116 @Test117 public void testConstructorArg() throws InterruptedException, IOException {118 String code = readTestFile("contracts/simplestorage2.sol");119 // create with constructor val 500120 String contractAddress = createContract(code, new Object[] { 500 });121 ContractABI abi = ContractABI.fromJson(readTestFile("contracts/simplestorage2.abi.txt"));122 BigInteger val = (BigInteger) contractService.read(contractAddress, abi, null, "get", null, null)[0];123 assertEquals(val.intValue(), 500);124 String owner = (String) contractService.read(contractAddress, abi, null, "owner", null, null)[0];125 assertEquals(owner, "0x2e219248f44546d966808cdd20cb6c36df6efa82");126 }127 @Test128 public void testRead2ByABI() throws InterruptedException, IOException {129 String contractAddress = createContract();130 String code = readTestFile("contracts/simplestorage.sol");131 String json = readTestFile("contracts/simplestorage.abi.txt");132 ContractABI abi = ContractABI.fromJson(json);133 String addr = "0x81635fe3d9cecbcf44aa58e967af1ab7ceefb817";134 String str = "foobar47";135 Object[] res = contractService.read(136 contractAddress, abi, null,137 "echo_2",138 new Object[] { addr, str },139 null);140 String hexAddr = (String) res[0];141 assertEquals(hexAddr, addr);142 assertEquals(res[1], str);143 Object[] res2 = contractService.read(144 contractAddress, abi, null,145 "echo_contract",146 new Object[] { contractAddress, "SimpleStorage", json, code, "solidity" },147 null);148 assertEquals(res2[0], contractAddress);149 assertEquals(res2[1], "SimpleStorage");150 assertEquals(res2[2], json);151 }152 @Test153 public void testTransactByABI() throws InterruptedException, IOException {154 String contractAddress = createContract();155 ContractABI abi = ContractABI.fromJson(readTestFile("contracts/simplestorage.abi.txt"));156 // 100 to start157 BigInteger val = (BigInteger) contractService.read(contractAddress, abi, null, "get", null, null)[0];158 assertEquals(val.intValue(), 100);159 // modify value160 TransactionResult tr = contractService.transact(contractAddress, abi, null, "set", new Object[]{ 200 });161 Transaction tx = transactionService.waitForTx(tr, 50, TimeUnit.MILLISECONDS);162 // should now be 200163 BigInteger val2 = (BigInteger) contractService.read(contractAddress, abi, null, "get", null, null)[0];164 assertEquals(val2.intValue(), 200);165 // read the previous value166 BigInteger valPrev = (BigInteger) contractService.read(contractAddress, abi, null, "get", null, tx.getBlockNumber().longValue() -1 )[0];167 assertEquals(valPrev.intValue(), 100);168 }169 @Test170 public void testListTransactions() throws InterruptedException, IOException {171 String contractAddress = createContract();172 ContractABI abi = ContractABI.fromJson(readTestFile("contracts/simplestorage.abi.txt"));173 // 100 to start174 BigInteger val = (BigInteger) contractService.read(contractAddress, abi, null, "get", null, null)[0];175 assertEquals(val.intValue(), 100);176 // modify value177 TransactionResult tr = contractService.transact(contractAddress, abi, null, "set", new Object[]{ 200 });178 Transaction tx = transactionService.waitForTx(tr, 50, TimeUnit.MILLISECONDS);179 ((TestBlockScanner) blockScanner).manualRun();180 List<Transaction> txns = contractService.listTransactions(contractAddress);181 assertNotNull(txns);182 assertTrue(!txns.isEmpty());183 assertEquals(txns.size(), 2);184 Transaction txSet = txns.get(1);185 Input decodedInput = txSet.getDecodedInput();186 assertNotNull(decodedInput);187 assertEquals(decodedInput.getMethod(), "set");188 val = (BigInteger) decodedInput.getArgs()[0];189 assertEquals(val.intValue(), 200);190 }191}...

Full Screen

Full Screen

Source:EnumCustomizedDeserializerTest.java Github

copy

Full Screen

1package com.gitee.qdbp.jdbc.enums;2import java.lang.reflect.Type;3import java.math.BigDecimal;4import java.math.BigInteger;5import org.testng.Assert;6import org.testng.Assert.ThrowingRunnable;7import org.testng.annotations.BeforeClass;8import org.testng.annotations.Test;9import com.alibaba.fastjson.JSONException;10import com.alibaba.fastjson.parser.DefaultJSONParser;11import com.alibaba.fastjson.parser.JSONLexer;12import com.alibaba.fastjson.parser.JSONToken;13import com.alibaba.fastjson.parser.ParserConfig;14import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;15import com.alibaba.fastjson.util.TypeUtils;16// 这个用例目前通不过, fastjson的TypeUtils.castToEnum存在逻辑错误17/**18 * 针对特殊枚举定制的反序列化处理类测试19 *20 * @author zhaohuihua21 * @version 2020072822 */23@Test24public class EnumCustomizedDeserializerTest {25 @BeforeClass26 protected void init() {27 // 给UserState注册定制的反序列化处理类28 ParserConfig.getGlobalInstance().putDeserializer(UserState.class, new CodeEnumDeserializer());29 }30 @Test(priority = 101, enabled = false)31 public void testConvert() {32 castToEnumTest("NORMAL", UserState.NORMAL);33 castToEnumTest("1", UserState.NORMAL);34 castToEnumTest(1, UserState.NORMAL);35 castToEnumTest("LOCKED", UserState.LOCKED);36 castToEnumTest("2", UserState.LOCKED);37 castToEnumTest(2, UserState.LOCKED);38 castToEnumTest("UNACTIVATED", UserState.UNACTIVATED);39 castToEnumTest("3", UserState.UNACTIVATED);40 castToEnumTest(3, UserState.UNACTIVATED);41 castToEnumTest("LOGOFF", UserState.LOGOFF);42 castToEnumTest("9", UserState.LOGOFF);43 castToEnumTest(9, UserState.LOGOFF);44 }45 46 private void castToEnumTest(Object source, UserState target) {47 String msg = "cast " + source + " to UserState";48 Assert.assertEquals(TypeUtils.castToEnum(source, UserState.class, null), target, msg);49 }50 @Test(priority = 102, enabled = false)51 public void testException() {52 Assert.assertThrows(JSONException.class, new ThrowingRunnable() {53 @Override54 public void run() throws Throwable {55 TypeUtils.castToEnum(0, UserState.class, null);56 }57 });58 Assert.assertThrows(JSONException.class, new ThrowingRunnable() {59 @Override60 public void run() throws Throwable {61 TypeUtils.castToEnum("AAA", UserState.class, null);62 }63 });64 }65 /** 自定义编号的枚举类 **/66 protected static interface CodeEnum {67 int code();68 }69 /** 用户状态 **/70 protected static enum UserState implements CodeEnum {71 /** 1.正常 **/72 NORMAL(1),73 /** 2.锁定 **/74 LOCKED(2),75 /** 3.待激活 **/76 UNACTIVATED(3),77 /** 9.已注销 **/78 LOGOFF(9);79 private int code;80 UserState(int code) {81 this.code = code;82 }83 public int code() {84 return this.code;85 }86 }87 /** 返回自定义编号的专用反序列化处理类(数字根据code转换) **/88 protected static class CodeEnumDeserializer implements ObjectDeserializer {89 @SuppressWarnings("unchecked")90 public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {91 JSONLexer lexer = parser.lexer;92 if (lexer.token() == JSONToken.NULL) {93 lexer.nextToken(JSONToken.COMMA);94 return null;95 }96 Class<?> targetClass = (Class<?>) TypeUtils.getRawClass(type);97 // CodeEnumDeserializer只能注册给既是枚举又实现了CodeEnum接口的类98 // ParserConfig.getGlobalInstance().putDeserializer(UserState.class, new CodeEnumDeserializer());99 if (!CodeEnum.class.isAssignableFrom(targetClass)) {100 throw new JSONException("CodeEnumDeserializer do not support " + targetClass.getName());101 }102 if (!Enum.class.isAssignableFrom(targetClass)) {103 throw new JSONException("CodeEnumDeserializer do not support " + targetClass.getName());104 }105 Enum<?>[] ordinalEnums = (Enum[]) targetClass.getEnumConstants();106 if (lexer.token() == JSONToken.LITERAL_INT) {107 BigDecimal number = lexer.decimalValue();108 lexer.nextToken(JSONToken.COMMA);109 return (T) convertFromNumber(number, ordinalEnums, targetClass);110 } else if (lexer.token() == JSONToken.LITERAL_FLOAT) {111 BigDecimal number = lexer.decimalValue();112 lexer.nextToken(JSONToken.COMMA);113 return (T) convertFromNumber(number, ordinalEnums, targetClass);114 } else if (lexer.token() == JSONToken.LITERAL_STRING) {115 String string = lexer.stringVal();116 if (isDigitString(string)) {117 BigDecimal number = new BigDecimal(string);118 return (T) convertFromNumber(number, ordinalEnums, targetClass);119 } else {120 return (T) convertFromString(string, ordinalEnums, targetClass);121 }122 }123 Object value = parser.parse();124 String msg = value + " can not cast to : " + targetClass.getName();125 throw new JSONException(msg);126 }127 private Enum<?> convertFromNumber(BigDecimal number, Enum<?>[] enums, Class<?> type) {128 // 整数部分129 BigInteger integer = number.toBigInteger();130 // 是不是整数131 boolean isIntegral = number.compareTo(new BigDecimal(integer)) == 0;132 if (!isIntegral) { // 不是整数133 String msg = "can not cast " + number.toPlainString() + " to : " + type.getName();134 throw new JSONException(msg);135 }136 BigInteger minInteger = BigInteger.valueOf(Integer.MIN_VALUE);137 BigInteger maxInteger = BigInteger.valueOf(Integer.MAX_VALUE);138 if (integer.compareTo(minInteger) < 0 || integer.compareTo(maxInteger) > 0) {139 // 不在Integer范围内140 throw new JSONException("can not cast " + integer + "to : " + type.getName());141 }142 // 根据code转换143 int targetValue = number.intValue();144 for (Enum<?> item : enums) {145 if (((CodeEnum) item).code() == targetValue) {146 return item;147 }148 }149 throw new JSONException("can not cast " + integer + "to : " + type.getName());150 }151 private Enum<?> convertFromString(String string, Enum<?>[] enums, Class<?> type) {152 if (string.length() == 0) {153 return null;154 }155 // 根据name转换156 for (Enum<?> item : enums) {157 if (item.name().equals(string)) {158 return item;159 }160 }161 throw new JSONException("can not cast " + string + "to : " + type.getName());162 }163 private boolean isDigitString(String string) {164 if (string == null || string.length() == 0) {165 return false;166 }167 for (int i = 0, z = string.length(); i < z; i++) {168 char c = string.charAt(i);169 if (c < '0' || c > '9') {170 return false;171 }172 }173 return true;174 }175 public int getFastMatchToken() {176 return JSONToken.UNDEFINED; // name or ordinal177 }178 }179}...

Full Screen

Full Screen

Source:TestFileBasedAccessControl.java Github

copy

Full Screen

1/*2 * Licensed under the Apache License, Version 2.0 (the "License");3 * you may not use this file except in compliance with the License.4 * You may obtain a copy of the License at5 *6 * http://www.apache.org/licenses/LICENSE-2.07 *8 * Unless required by applicable law or agreed to in writing, software9 * distributed under the License is distributed on an "AS IS" BASIS,10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11 * See the License for the specific language governing permissions and12 * limitations under the License.13 */14package com.facebook.presto.plugin.base.security;15import com.facebook.presto.spi.SchemaTableName;16import com.facebook.presto.spi.connector.ConnectorAccessControl;17import com.facebook.presto.spi.connector.ConnectorTransactionHandle;18import com.facebook.presto.spi.security.AccessDeniedException;19import com.facebook.presto.spi.security.Identity;20import com.google.common.collect.ImmutableSet;21import org.testng.Assert.ThrowingRunnable;22import org.testng.annotations.Test;23import java.io.IOException;24import java.util.Optional;25import static com.facebook.presto.spi.testing.InterfaceTestUtils.assertAllMethodsOverridden;26import static org.assertj.core.api.Assertions.assertThatThrownBy;27import static org.testng.Assert.assertThrows;28public class TestFileBasedAccessControl29{30 public static final ConnectorTransactionHandle TRANSACTION_HANDLE = new ConnectorTransactionHandle() {};31 @Test32 public void testSchemaRules()33 throws IOException34 {35 ConnectorAccessControl accessControl = createAccessControl("schema.json");36 accessControl.checkCanCreateTable(TRANSACTION_HANDLE, user("admin"), new SchemaTableName("test", "test"));37 accessControl.checkCanCreateTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bob", "test"));38 assertDenied(() -> accessControl.checkCanCreateTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("test", "test")));39 assertDenied(() -> accessControl.checkCanCreateTable(TRANSACTION_HANDLE, user("admin"), new SchemaTableName("secret", "test")));40 }41 @Test42 public void testTableRules()43 throws IOException44 {45 ConnectorAccessControl accessControl = createAccessControl("table.json");46 accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("alice"), new SchemaTableName("test", "test"), ImmutableSet.of());47 accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("alice"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());48 accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("alice"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of("bobcolumn"));49 accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());50 accessControl.checkCanInsertIntoTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable"));51 accessControl.checkCanDeleteFromTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable"));52 accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("joe"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());53 accessControl.checkCanCreateViewWithSelectFromColumns(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());54 accessControl.checkCanDropTable(TRANSACTION_HANDLE, user("admin"), new SchemaTableName("bobschema", "bobtable"));55 assertDenied(() -> accessControl.checkCanInsertIntoTable(TRANSACTION_HANDLE, user("alice"), new SchemaTableName("bobschema", "bobtable")));56 assertDenied(() -> accessControl.checkCanDropTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable")));57 assertDenied(() -> accessControl.checkCanInsertIntoTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("test", "test")));58 assertDenied(() -> accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("admin"), new SchemaTableName("secret", "secret"), ImmutableSet.of()));59 assertDenied(() -> accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("joe"), new SchemaTableName("secret", "secret"), ImmutableSet.of()));60 assertDenied(() -> accessControl.checkCanCreateViewWithSelectFromColumns(TRANSACTION_HANDLE, user("joe"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of()));61 }62 @Test63 public void testSessionPropertyRules()64 throws IOException65 {66 ConnectorAccessControl accessControl = createAccessControl("session_property.json");67 accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("admin"), "dangerous");68 accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("alice"), "safe");69 accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("alice"), "unsafe");70 accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("bob"), "safe");71 assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("bob"), "unsafe"));72 assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("alice"), "dangerous"));73 assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("charlie"), "safe"));74 }75 @Test76 public void testInvalidRules()77 {78 assertThatThrownBy(() -> createAccessControl("invalid.json"))79 .hasMessageContaining("Invalid JSON");80 }81 @Test82 public void testEverythingImplemented()83 {84 assertAllMethodsOverridden(ConnectorAccessControl.class, FileBasedAccessControl.class);85 }86 private static Identity user(String name)87 {88 return new Identity(name, Optional.empty());89 }90 private ConnectorAccessControl createAccessControl(String fileName)91 throws IOException92 {93 String path = this.getClass().getClassLoader().getResource(fileName).getPath();94 FileBasedAccessControlConfig config = new FileBasedAccessControlConfig();95 config.setConfigFile(path);96 return new FileBasedAccessControl(config);97 }98 private static void assertDenied(ThrowingRunnable runnable)99 {100 assertThrows(AccessDeniedException.class, runnable);101 }102}...

Full Screen

Full Screen

Interface Assert.ThrowingRunnable

Using AI Code Generation

copy

Full Screen

1public void testThrowingRunnable() {2 Assert.assertThrows(NullPointerException.class, new Assert.ThrowingRunnable() {3 public void run() throws Throwable {4 throw new NullPointerException();5 }6 });7}8public void testThrowingRunnable() {9 Assert.assertThrows(NullPointerException.class, () -> {10 throw new NullPointerException();11 });12}13public void testThrowingRunnable() {14 Assert.assertThrows(NullPointerException.class, () -> throw new NullPointerException());15}16public void testThrowingRunnable() {17 Assert.assertThrows(NullPointerException.class, () -> throw new NullPointerException(), "NullPointerException message");18}19public void testThrowingRunnable() {20 NullPointerException exception = Assert.expectThrows(NullPointerException.class, () -> throw new NullPointerException(), "NullPointerException message");21}22Assert.assertThrows() vs Assert.expectThrows()23Assert.expectThrows() method is used

Full Screen

Full Screen

Interface Assert.ThrowingRunnable

Using AI Code Generation

copy

Full Screen

1public void test1() {2 Assert.assertThrows(NullPointerException.class, new Assert.ThrowingRunnable() {3 public void run() throws Throwable {4 throw new NullPointerException();5 }6 });7}8public void test2() {9 Assert.assertThrows(NullPointerException.class, () -> {10 throw new NullPointerException();11 });12}13public void test3() {14 Assert.assertThrows(NullPointerException.class, this::throwNullPointerException);15}16private void throwNullPointerException() {17 throw new NullPointerException();18}

Full Screen

Full Screen

Interface Assert.ThrowingRunnable

Using AI Code Generation

copy

Full Screen

1import org.testng.Assert;2import org.testng.annotations.Test;3public class TestNGAssertion {4public void test1() {5Assert.assertEquals(12, 13);6}7public void test2() {8Assert.assertEquals("abc", "xyz");9}10public void test3() {11Assert.assertTrue("abc".equals("xyz"), "String are not equal");12}13public void test4() {14Assert.assertTrue("abc".equals("xyz"));15}16public void test5() {17Assert.assertTrue("abc".equals("abc"));18}19public void test6() {20Assert.assertTrue(0 > 1);21}22public void test7() {23Assert.assertTrue(0 < 1);24}25public void test8() {26Assert.assertTrue(0 > 1, "Comparision failed");27}28public void test9() {29Assert.assertTrue(0 < 1, "Comparision passed");30}31public void test10() {32Assert.assertTrue(0 < 1, "Comparision passed");33}34public void test11() {35Assert.assertTrue(0 < 1, "Comparision passed");36}37public void test12() {38Assert.assertFalse(0 < 1);39}40public void test13() {41Assert.assertFalse(0 > 1);42}43public void test14() {44Assert.assertFalse(0 < 1, "Comparision passed");45}46public void test15() {47Assert.assertFalse(0 > 1, "Comparision failed");48}49@Test(expectedExceptions = ArithmeticException.class)50public void test16() {51int i = 1 / 0;52}53public void test17() {54Assert.assertThrows(ArithmeticException.class, new Assert.ThrowingRunnable() {55public void run() throws Throwable {56int i = 1 / 0;57}58});59}60public void test18() {61Assert.assertThrows(ArithmeticException.class, new Assert.ThrowingRunnable() {62public void run() throws Throwable {63int i = 1 / 0;64}65}, "Divide by zero");66}67public void test19() {68Assert.assertThrows(ArithmeticException.class, new Assert.ThrowingRunnable() {69public void run() throws Throwable {70int i = 1 / 1;71}72}, "Divide by zero");73}74public void test20() {75Assert.assertThrows(NullPointerException.class, new Assert.ThrowingRunnable() {

Full Screen

Full Screen

Interface Assert.ThrowingRunnable

Using AI Code Generation

copy

Full Screen

1@Test(expectedExceptions = ArithmeticException.class)2public class TestNGExample {3 public void testArithmeticException(){4 int i = 1/0;5 }6}7@Test(expectedExceptions = ArithmeticException.class)8public class TestNGExample {9 public void testArithmeticException(){10 int i = 1/0;11 }12}13@Test(expectedExceptions = ArithmeticException.class)14public class TestNGExample {15 public void testArithmeticException(){16 int i = 1/0;17 }18}19@Test(expectedExceptions = ArithmeticException.class)20public class TestNGExample {21 public void testArithmeticException(){22 int i = 1/0;23 }24}25@Test(expectedExceptions = ArithmeticException.class)26public class TestNGExample {27 public void testArithmeticException(){28 int i = 1/0;29 }30}31@Test(expectedExceptions = ArithmeticException.class)32public class TestNGExample {33 public void testArithmeticException(){34 int i = 1/0;35 }36}37@Test(expectedExceptions = ArithmeticException.class)38public class TestNGExample {39 public void testArithmeticException(){40 int i = 1/0;41 }42}43@Test(expectedExceptions = ArithmeticException.class)44public class TestNGExample {45 public void testArithmeticException(){46 int i = 1/0;47 }48}49@Test(expectedExceptions = ArithmeticException.class)50public class TestNGExample {51 public void testArithmeticException(){52 int i = 1/0;53 }54}55@Test(expectedExceptions = ArithmeticException.class)56public class TestNGExample {

Full Screen

Full Screen

Interface Assert.ThrowingRunnable

Using AI Code Generation

copy

Full Screen

1public class TestNGTest {2 public void test() {3 Assert.assertThrows(NullPointerException.class, new ThrowingRunnable() {4 public void run() throws Throwable {5 throw new NullPointerException();6 }7 });8 }9}10public class TestNGTest {11 public void test() {12 Assert.assertThrows(NullPointerException.class, new ThrowingRunnable() {13 public void run() throws Throwable {14 throw new NullPointerException();15 }16 });17 }18}19public class TestNGTest {20 public void test() {21 Assert.assertThrows(NullPointerException.class, new ThrowingRunnable() {22 public void run() throws Throwable {23 throw new NullPointerException();24 }25 });26 }27}28public class TestNGTest {29 public void test() {30 Assert.assertThrows(NullPointerException.class, new ThrowingRunnable() {31 public void run() throws Throwable {32 throw new NullPointerException();33 }34 });35 }36}37public class TestNGTest {38 public void test() {39 Assert.assertThrows(NullPointerException.class, new ThrowingRunnable() {40 public void run() throws Throwable {41 throw new NullPointerException();42 }43 });44 }45}46public class TestNGTest {47 public void test() {48 Assert.assertThrows(NullPointerException.class, new ThrowingRunnable() {49 public void run() throws Throwable {50 throw new NullPointerException();51 }52 });

Full Screen

Full Screen

Interface Assert.ThrowingRunnable

Using AI Code Generation

copy

Full Screen

1import org.testng.Assert;2import org.testng.annotations.Test;3public class TestAssertThrowingRunnable {4 public void testAssertThrowingRunnable() {5 Assert.assertThrows(ArithmeticException.class, () -> {6 int x = 1 / 0;7 });8 }9}10Method testAssertThrowingRunnable() should not have parameters11at org.testng.internal.MethodHelper.checkParameters(MethodHelper.java:64)12at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:107)13at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:60)14at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:498)15at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:231)16at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:156)17at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:176)18at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)19at org.testng.TestRunner.privateRun(TestRunner.java:773)20at org.testng.TestRunner.run(TestRunner.java:623)21at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)22at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)23at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)24at org.testng.SuiteRunner.run(SuiteRunner.java:259)25at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)26at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)27at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)28at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)29at org.testng.TestNG.runSuites(TestNG.java:1029)30at org.testng.TestNG.run(TestNG.java:996)31at org.testng.TestNG.privateMain(TestNG.java:1354)32at org.testng.TestNG.main(TestNG.java:1323)33at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)34at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)35at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java

Full Screen

Full Screen

TestNG tutorial

TestNG is a Java-based open-source framework for test automation that includes various test types, such as unit testing, functional testing, E2E testing, etc. TestNG is in many ways similar to JUnit and NUnit. But in contrast to its competitors, its extensive features make it a lot more reliable framework. One of the major reasons for its popularity is its ability to structure tests and improve the scripts' readability and maintainability. Another reason can be the important characteristics like the convenience of using multiple annotations, reliance, and priority that make this framework popular among developers and testers for test design. You can refer to the TestNG tutorial to learn why you should choose the TestNG framework.

Chapters

  1. JUnit 5 vs. TestNG: Compare and explore the core differences between JUnit 5 and TestNG from the Selenium WebDriver viewpoint.
  2. Installing TestNG in Eclipse: Start installing the TestNG Plugin and learn how to set up TestNG in Eclipse to begin constructing a framework for your test project.
  3. Create TestNG Project in Eclipse: Get started with creating a TestNG project and write your first TestNG test script.
  4. Automation using TestNG: Dive into how to install TestNG in this Selenium TestNG tutorial, the fundamentals of developing an automation script for Selenium automation testing.
  5. Parallel Test Execution in TestNG: Here are some essential elements of parallel testing with TestNG in this Selenium TestNG tutorial.
  6. Creating TestNG XML File: Here is a step-by-step tutorial on creating a TestNG XML file to learn why and how it is created and discover how to run the TestNG XML file being executed in parallel.
  7. Automation with Selenium, Cucumber & TestNG: Explore for an in-depth tutorial on automation using Selenium, Cucumber, and TestNG, as TestNG offers simpler settings and more features.
  8. JUnit Selenium Tests using TestNG: Start running your regular and parallel tests by looking at how to run test cases in Selenium using JUnit and TestNG without having to rewrite the tests.
  9. Group Test Cases in TestNG: Along with the explanation and demonstration using relevant TestNG group examples, learn how to group test cases in TestNG.
  10. Prioritizing Tests in TestNG: Get started with how to prioritize test cases in TestNG for Selenium automation testing.
  11. Assertions in TestNG: Examine what TestNG assertions are, the various types of TestNG assertions, and situations that relate to Selenium automated testing.
  12. DataProviders in TestNG: Deep dive into learning more about TestNG's DataProvider and how to effectively use it in our test scripts for Selenium test automation.
  13. Parameterization in TestNG: Here are the several parameterization strategies used in TestNG tests and how to apply them in Selenium automation scripts.
  14. TestNG Listeners in Selenium WebDriver: Understand the various TestNG listeners to utilize them effectively for your next plan when working with TestNG and Selenium automation.
  15. TestNG Annotations: Learn more about the execution order and annotation attributes, and refer to the prerequisites required to set up TestNG.
  16. TestNG Reporter Log in Selenium: Find out how to use the TestNG Reporter Log and learn how to eliminate the need for external software with TestNG Reporter Class to boost productivity.
  17. TestNG Reports in Jenkins: Discover how to generate TestNG reports in Jenkins if you want to know how to create, install, and share TestNG reports in Jenkins.

Certification

You can push your abilities to do automated testing using TestNG and advance your career by earning a TestNG certification. Check out our TestNG certification.

YouTube

Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.

Run Testng automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in Interface-Assert.ThrowingRunnable

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful