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

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

Run Testng automation tests on LambdaTest cloud grid

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

copy
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 at
5 *
6 *     http://www.apache.org/licenses/LICENSE-2.0
7 *
8 * Unless required by applicable law or agreed to in writing, software
9 * 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 and
12 * limitations under the License.
13 */
14package com.facebook.presto.plugin.base.security;
15
16import com.facebook.presto.spi.SchemaTableName;
17import com.facebook.presto.spi.connector.ConnectorAccessControl;
18import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
19import com.facebook.presto.spi.security.AccessDeniedException;
20import com.facebook.presto.spi.security.Identity;
21import com.google.common.collect.ImmutableSet;
22import org.testng.Assert.ThrowingRunnable;
23import org.testng.annotations.Test;
24
25import java.io.IOException;
26import java.util.Optional;
27
28import static com.facebook.presto.spi.testing.InterfaceTestUtils.assertAllMethodsOverridden;
29import static org.assertj.core.api.Assertions.assertThatThrownBy;
30import static org.testng.Assert.assertThrows;
31
32public class TestFileBasedAccessControl
33{
34    public static final ConnectorTransactionHandle TRANSACTION_HANDLE = new ConnectorTransactionHandle() {};
35
36    @Test
37    public void testSchemaRules()
38            throws IOException
39    {
40        ConnectorAccessControl accessControl = createAccessControl("schema.json");
41        accessControl.checkCanCreateTable(TRANSACTION_HANDLE, user("admin"), new SchemaTableName("test", "test"));
42        accessControl.checkCanCreateTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bob", "test"));
43        assertDenied(() -> accessControl.checkCanCreateTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("test", "test")));
44        assertDenied(() -> accessControl.checkCanCreateTable(TRANSACTION_HANDLE, user("admin"), new SchemaTableName("secret", "test")));
45    }
46
47    @Test
48    public void testTableRules()
49            throws IOException
50    {
51        ConnectorAccessControl accessControl = createAccessControl("table.json");
52        accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("alice"), new SchemaTableName("test", "test"), ImmutableSet.of());
53        accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("alice"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
54        accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("alice"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of("bobcolumn"));
55        accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
56        accessControl.checkCanInsertIntoTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable"));
57        accessControl.checkCanDeleteFromTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable"));
58        accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("joe"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
59        accessControl.checkCanCreateViewWithSelectFromColumns(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of());
60        accessControl.checkCanDropTable(TRANSACTION_HANDLE, user("admin"), new SchemaTableName("bobschema", "bobtable"));
61        assertDenied(() -> accessControl.checkCanInsertIntoTable(TRANSACTION_HANDLE, user("alice"), new SchemaTableName("bobschema", "bobtable")));
62        assertDenied(() -> accessControl.checkCanDropTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("bobschema", "bobtable")));
63        assertDenied(() -> accessControl.checkCanInsertIntoTable(TRANSACTION_HANDLE, user("bob"), new SchemaTableName("test", "test")));
64        assertDenied(() -> accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("admin"), new SchemaTableName("secret", "secret"), ImmutableSet.of()));
65        assertDenied(() -> accessControl.checkCanSelectFromColumns(TRANSACTION_HANDLE, user("joe"), new SchemaTableName("secret", "secret"), ImmutableSet.of()));
66        assertDenied(() -> accessControl.checkCanCreateViewWithSelectFromColumns(TRANSACTION_HANDLE, user("joe"), new SchemaTableName("bobschema", "bobtable"), ImmutableSet.of()));
67    }
68
69    @Test
70    public void testSessionPropertyRules()
71            throws IOException
72    {
73        ConnectorAccessControl accessControl = createAccessControl("session_property.json");
74        accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("admin"), "dangerous");
75        accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("alice"), "safe");
76        accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("alice"), "unsafe");
77        accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("bob"), "safe");
78        assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("bob"), "unsafe"));
79        assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("alice"), "dangerous"));
80        assertDenied(() -> accessControl.checkCanSetCatalogSessionProperty(TRANSACTION_HANDLE, user("charlie"), "safe"));
81    }
82
83    @Test
84    public void testInvalidRules()
85    {
86        assertThatThrownBy(() -> createAccessControl("invalid.json"))
87                .hasMessageContaining("Invalid JSON");
88    }
89
90    @Test
91    public void testEverythingImplemented()
92    {
93        assertAllMethodsOverridden(ConnectorAccessControl.class, FileBasedAccessControl.class);
94    }
95
96    private static Identity user(String name)
97    {
98        return new Identity(name, Optional.empty());
99    }
100
101    private ConnectorAccessControl createAccessControl(String fileName)
102            throws IOException
103    {
104        String path = this.getClass().getClassLoader().getResource(fileName).getPath();
105        FileBasedAccessControlConfig config = new FileBasedAccessControlConfig();
106        config.setConfigFile(path);
107        return new FileBasedAccessControl(config);
108    }
109
110    private static void assertDenied(ThrowingRunnable runnable)
111    {
112        assertThrows(AccessDeniedException.class, runnable);
113    }
114}
115
Full Screen
copy
1package com.gitee.qdbp.jdbc.enums;
2
3import java.lang.reflect.Type;
4import java.math.BigDecimal;
5import java.math.BigInteger;
6import org.testng.Assert;
7import org.testng.Assert.ThrowingRunnable;
8import org.testng.annotations.BeforeClass;
9import org.testng.annotations.Test;
10import com.alibaba.fastjson.JSONException;
11import com.alibaba.fastjson.parser.DefaultJSONParser;
12import com.alibaba.fastjson.parser.JSONLexer;
13import com.alibaba.fastjson.parser.JSONToken;
14import com.alibaba.fastjson.parser.ParserConfig;
15import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
16import com.alibaba.fastjson.util.TypeUtils;
17
18// 这个用例目前通不过, fastjson的TypeUtils.castToEnum存在逻辑错误
19/**
20 * 针对特殊枚举定制的反序列化处理类测试
21 *
22 * @author zhaohuihua
23 * @version 20200728
24 */
25@Test
26public class EnumCustomizedDeserializerTest {
27
28    @BeforeClass
29    protected void init() {
30        // 给UserState注册定制的反序列化处理类
31        ParserConfig.getGlobalInstance().putDeserializer(UserState.class, new CodeEnumDeserializer());
32    }
33
34    @Test(priority = 101, enabled = false)
35    public void testConvert() {
36        castToEnumTest("NORMAL", UserState.NORMAL);
37        castToEnumTest("1", UserState.NORMAL);
38        castToEnumTest(1, UserState.NORMAL);
39        castToEnumTest("LOCKED", UserState.LOCKED);
40        castToEnumTest("2", UserState.LOCKED);
41        castToEnumTest(2, UserState.LOCKED);
42        castToEnumTest("UNACTIVATED", UserState.UNACTIVATED);
43        castToEnumTest("3", UserState.UNACTIVATED);
44        castToEnumTest(3, UserState.UNACTIVATED);
45        castToEnumTest("LOGOFF", UserState.LOGOFF);
46        castToEnumTest("9", UserState.LOGOFF);
47        castToEnumTest(9, UserState.LOGOFF);
48    }
49    
50    private void castToEnumTest(Object source, UserState target) {
51        String msg = "cast " + source + " to UserState";
52        Assert.assertEquals(TypeUtils.castToEnum(source, UserState.class, null), target, msg);
53    }
54
55    @Test(priority = 102, enabled = false)
56    public void testException() {
57        Assert.assertThrows(JSONException.class, new ThrowingRunnable() {
58            @Override
59            public void run() throws Throwable {
60                TypeUtils.castToEnum(0, UserState.class, null);
61            }
62        });
63
64        Assert.assertThrows(JSONException.class, new ThrowingRunnable() {
65            @Override
66            public void run() throws Throwable {
67                TypeUtils.castToEnum("AAA", UserState.class, null);
68            }
69        });
70    }
71
72    /** 自定义编号的枚举类 **/
73    protected static interface CodeEnum {
74        int code();
75    }
76
77    /** 用户状态 **/
78    protected static enum UserState implements CodeEnum {
79
80        /** 1.正常 **/
81        NORMAL(1),
82        /** 2.锁定 **/
83        LOCKED(2),
84        /** 3.待激活 **/
85        UNACTIVATED(3),
86        /** 9.已注销 **/
87        LOGOFF(9);
88
89        private int code;
90
91        UserState(int code) {
92            this.code = code;
93        }
94
95        public int code() {
96            return this.code;
97        }
98    }
99
100    /** 返回自定义编号的专用反序列化处理类(数字根据code转换) **/
101    protected static class CodeEnumDeserializer implements ObjectDeserializer {
102
103        @SuppressWarnings("unchecked")
104        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
105            JSONLexer lexer = parser.lexer;
106            if (lexer.token() == JSONToken.NULL) {
107                lexer.nextToken(JSONToken.COMMA);
108                return null;
109            }
110
111            Class<?> targetClass = (Class<?>) TypeUtils.getRawClass(type);
112            // CodeEnumDeserializer只能注册给既是枚举又实现了CodeEnum接口的类
113            // ParserConfig.getGlobalInstance().putDeserializer(UserState.class, new CodeEnumDeserializer());
114            if (!CodeEnum.class.isAssignableFrom(targetClass)) {
115                throw new JSONException("CodeEnumDeserializer do not support " + targetClass.getName());
116            }
117            if (!Enum.class.isAssignableFrom(targetClass)) {
118                throw new JSONException("CodeEnumDeserializer do not support " + targetClass.getName());
119            }
120            Enum<?>[] ordinalEnums = (Enum[]) targetClass.getEnumConstants();
121            if (lexer.token() == JSONToken.LITERAL_INT) {
122                BigDecimal number = lexer.decimalValue();
123                lexer.nextToken(JSONToken.COMMA);
124                return (T) convertFromNumber(number, ordinalEnums, targetClass);
125            } else if (lexer.token() == JSONToken.LITERAL_FLOAT) {
126                BigDecimal number = lexer.decimalValue();
127                lexer.nextToken(JSONToken.COMMA);
128                return (T) convertFromNumber(number, ordinalEnums, targetClass);
129            } else if (lexer.token() == JSONToken.LITERAL_STRING) {
130                String string = lexer.stringVal();
131                if (isDigitString(string)) {
132                    BigDecimal number = new BigDecimal(string);
133                    return (T) convertFromNumber(number, ordinalEnums, targetClass);
134                } else {
135                    return (T) convertFromString(string, ordinalEnums, targetClass);
136                }
137            }
138
139            Object value = parser.parse();
140            String msg = value + " can not cast to : " + targetClass.getName();
141            throw new JSONException(msg);
142        }
143
144        private Enum<?> convertFromNumber(BigDecimal number, Enum<?>[] enums, Class<?> type) {
145            // 整数部分
146            BigInteger integer = number.toBigInteger();
147            // 是不是整数
148            boolean isIntegral = number.compareTo(new BigDecimal(integer)) == 0;
149            if (!isIntegral) { // 不是整数
150                String msg = "can not cast " + number.toPlainString() + " to : " + type.getName();
151                throw new JSONException(msg);
152            }
153            BigInteger minInteger = BigInteger.valueOf(Integer.MIN_VALUE);
154            BigInteger maxInteger = BigInteger.valueOf(Integer.MAX_VALUE);
155            if (integer.compareTo(minInteger) < 0 || integer.compareTo(maxInteger) > 0) {
156                // 不在Integer范围内
157                throw new JSONException("can not cast " + integer + "to : " + type.getName());
158            }
159            // 根据code转换
160            int targetValue = number.intValue();
161            for (Enum<?> item : enums) {
162                if (((CodeEnum) item).code() == targetValue) {
163                    return item;
164                }
165            }
166            throw new JSONException("can not cast " + integer + "to : " + type.getName());
167        }
168
169        private Enum<?> convertFromString(String string, Enum<?>[] enums, Class<?> type) {
170            if (string.length() == 0) {
171                return null;
172            }
173            // 根据name转换
174            for (Enum<?> item : enums) {
175                if (item.name().equals(string)) {
176                    return item;
177                }
178            }
179            throw new JSONException("can not cast " + string + "to : " + type.getName());
180        }
181
182        private boolean isDigitString(String string) {
183            if (string == null || string.length() == 0) {
184                return false;
185            }
186            for (int i = 0, z = string.length(); i < z; i++) {
187                char c = string.charAt(i);
188                if (c < '0' || c > '9') {
189                    return false;
190                }
191            }
192            return true;
193        }
194
195        public int getFastMatchToken() {
196            return JSONToken.UNDEFINED; // name or ordinal
197        }
198
199    }
200}
201
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on Interface-Assert.ThrowingRunnable

    No relevant questions found for this class 😞

Most used methods in Interface-Assert.ThrowingRunnable

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)