How to use assumeNotNull method of org.junit.Assume class

Best junit code snippet using org.junit.Assume.assumeNotNull

Run junit automation tests on LambdaTest cloud grid

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

copy
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4package com.azure.endtoend.identity;
5
6import com.azure.core.credential.TokenRequestContext;
7import com.azure.core.util.Configuration;
8import com.azure.identity.ManagedIdentityCredential;
9import com.azure.identity.ManagedIdentityCredentialBuilder;
10import com.azure.identity.implementation.IdentityClient;
11import com.azure.identity.implementation.IdentityClientBuilder;
12import com.azure.security.keyvault.secrets.SecretClient;
13import com.azure.security.keyvault.secrets.SecretClientBuilder;
14import com.azure.security.keyvault.secrets.models.KeyVaultSecret;
15import org.junit.Assert;
16import org.junit.Test;
17import reactor.test.StepVerifier;
18
19import java.io.IOException;
20import java.net.HttpURLConnection;
21import java.net.URL;
22import java.net.URLEncoder;
23
24public class ManagedIdentityCredentialLiveTest {
25    private static final String AZURE_VAULT_URL = "AZURE_VAULT_URL";
26    private static final String VAULT_SECRET_NAME = "secret";
27    private static final Configuration CONFIGURATION = Configuration.getGlobalConfiguration().clone();
28    private static final String PROPERTY_IDENTITY_ENDPOINT = "IDENTITY_ENDPOINT";
29    private static final String PROPERTY_IDENTITY_HEADER = "IDENTITY_HEADER";
30
31    @Test
32    public void testMSIEndpointWithSystemAssigned() throws Exception {
33        org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT));
34        org.junit.Assume.assumeTrue(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID) == null);
35        org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));
36
37        IdentityClient client = new IdentityClientBuilder().build();
38        StepVerifier.create(client.authenticateToManagedIdentityEndpoint(
39            CONFIGURATION.get(PROPERTY_IDENTITY_ENDPOINT),
40            CONFIGURATION.get(PROPERTY_IDENTITY_HEADER),
41            CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT),
42            CONFIGURATION.get(Configuration.PROPERTY_MSI_SECRET),
43            new TokenRequestContext().addScopes("https://management.azure.com/.default")))
44            .expectNextMatches(accessToken -> accessToken != null && accessToken.getToken() != null)
45            .verifyComplete();
46    }
47
48    @Test
49    public void testMSIEndpointWithSystemAssignedAccessKeyVault() throws Exception {
50        org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT));
51        org.junit.Assume.assumeTrue(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID) == null);
52        org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));
53
54        ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().build();
55
56        SecretClient client = new SecretClientBuilder()
57            .credential(credential)
58            .vaultUrl(CONFIGURATION.get(AZURE_VAULT_URL))
59            .buildClient();
60
61        KeyVaultSecret secret = client.getSecret(VAULT_SECRET_NAME);
62        Assert.assertNotNull(secret);
63        Assert.assertEquals(VAULT_SECRET_NAME, secret.getName());
64        Assert.assertNotNull(secret.getValue());
65    }
66
67    @Test
68    public void testMSIEndpointWithUserAssigned() throws Exception {
69        org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT));
70        org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID));
71        org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));
72
73        IdentityClient client = new IdentityClientBuilder()
74            .clientId(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID))
75            .build();
76        StepVerifier.create(client.authenticateToManagedIdentityEndpoint(
77            CONFIGURATION.get(PROPERTY_IDENTITY_ENDPOINT),
78            CONFIGURATION.get(PROPERTY_IDENTITY_HEADER),
79            CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT),
80            CONFIGURATION.get(Configuration.PROPERTY_MSI_SECRET),
81            new TokenRequestContext().addScopes("https://management.azure.com/.default")))
82            .expectNextMatches(accessToken -> accessToken != null && accessToken.getToken() != null)
83            .verifyComplete();
84    }
85
86    @Test
87    public void testMSIEndpointWithUserAssignedAccessKeyVault() throws Exception {
88        org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT));
89        org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID));
90        org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));
91
92        ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder()
93            .clientId(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID))
94            .build();
95
96        SecretClient client = new SecretClientBuilder()
97            .credential(credential)
98            .vaultUrl(CONFIGURATION.get(AZURE_VAULT_URL))
99            .buildClient();
100
101        KeyVaultSecret secret = client.getSecret(VAULT_SECRET_NAME);
102        Assert.assertNotNull(secret);
103        Assert.assertEquals(VAULT_SECRET_NAME, secret.getName());
104        Assert.assertNotNull(secret.getValue());
105    }
106
107    @Test
108    public void testIMDSEndpointWithSystemAssigned() throws Exception {
109        org.junit.Assume.assumeTrue(checkIMDSAvailable());
110        org.junit.Assume.assumeTrue(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID) == null);
111        org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));
112
113        IdentityClient client = new IdentityClientBuilder().build();
114        StepVerifier.create(client.authenticateToIMDSEndpoint(
115            new TokenRequestContext().addScopes("https://management.azure.com/.default")))
116            .expectNextMatches(accessToken -> accessToken != null && accessToken.getToken() != null)
117            .verifyComplete();
118    }
119
120    @Test
121    public void testIMDSEndpointWithSystemAssignedAccessKeyVault() throws Exception {
122        org.junit.Assume.assumeTrue(checkIMDSAvailable());
123        org.junit.Assume.assumeTrue(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID) == null);
124        org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));
125
126        ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().build();
127
128        SecretClient client = new SecretClientBuilder()
129            .credential(credential)
130            .vaultUrl(CONFIGURATION.get(AZURE_VAULT_URL))
131            .buildClient();
132
133        KeyVaultSecret secret = client.getSecret(VAULT_SECRET_NAME);
134        Assert.assertNotNull(secret);
135        Assert.assertEquals(VAULT_SECRET_NAME, secret.getName());
136        Assert.assertNotNull(secret.getValue());
137    }
138
139    @Test
140    public void testIMDSEndpointWithUserAssigned() throws Exception {
141        org.junit.Assume.assumeTrue(checkIMDSAvailable());
142        org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID));
143        org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));
144
145        IdentityClient client = new IdentityClientBuilder()
146            .clientId(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID))
147            .build();
148        StepVerifier.create(client.authenticateToIMDSEndpoint(
149            new TokenRequestContext().addScopes("https://management.azure.com/.default")))
150            .expectNextMatches(accessToken -> accessToken != null && accessToken.getToken() != null)
151            .verifyComplete();
152    }
153
154    @Test
155    public void testIMDSEndpointWithUserAssignedAccessKeyVault() throws Exception {
156        org.junit.Assume.assumeTrue(checkIMDSAvailable());
157        org.junit.Assume.assumeNotNull(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID));
158        org.junit.Assume.assumeNotNull(CONFIGURATION.get(AZURE_VAULT_URL));
159
160        ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder()
161            .clientId(CONFIGURATION.get(Configuration.PROPERTY_AZURE_CLIENT_ID))
162            .build();
163
164        SecretClient client = new SecretClientBuilder()
165            .credential(credential)
166            .vaultUrl(CONFIGURATION.get(AZURE_VAULT_URL))
167            .buildClient();
168
169        KeyVaultSecret secret = client.getSecret(VAULT_SECRET_NAME);
170        Assert.assertNotNull(secret);
171        Assert.assertEquals(VAULT_SECRET_NAME, secret.getName());
172        Assert.assertNotNull(secret.getValue());
173    }
174
175    private boolean checkIMDSAvailable() {
176        StringBuilder payload = new StringBuilder();
177
178        try {
179            payload.append("api-version=");
180            payload.append(URLEncoder.encode("2018-02-01", "UTF-8"));
181        } catch (IOException exception) {
182            return false;
183        }
184
185        HttpURLConnection connection = null;
186
187        try {
188            URL url = new URL(String.format("http://169.254.169.254/metadata/identity/oauth2/token?%s",
189                payload.toString()));
190
191            connection = (HttpURLConnection) url.openConnection();
192            connection.setRequestMethod("GET");
193            connection.setConnectTimeout(500);
194            connection.connect();
195            return true;
196        } catch (Exception e) {
197            return false;
198        } finally {
199            if (connection != null) {
200                connection.disconnect();
201            }
202        }
203    }
204}
205
Full Screen
copy
1import domain.users.User;
2import org.junit.BeforeClass;
3import org.junit.Rule;
4import org.junit.experimental.theories.DataPoints;
5import org.junit.experimental.theories.Theories;
6import org.junit.experimental.theories.Theory;
7import org.junit.rules.ExpectedException;
8import org.junit.runner.RunWith;
9
10import static org.hamcrest.CoreMatchers.*;
11import static org.junit.Assume.assumeNotNull;
12import static org.junit.Assume.assumeThat;
13
14@RunWith(Theories.class)
15public class UsersTest {
16    private static User user1;
17    private static User user2;
18
19    @Rule
20    public ExpectedException thrown = ExpectedException.none();
21
22    @BeforeClass
23    public static void createUsers() {
24        user1 = new User("Nataliya", "svk", 56646, "56452ghh54");
25        user2 = new User("Alexander", "kim", 46843, "54746jm458");
26    }
27
28    @DataPoints
29    public static String[] usersNames() {
30        return new String[]{user1.getName(), user2.getName()};
31    }
32
33    @Theory
34    public void testUsersNames(String name) throws Exception {
35        System.out.println(String.format("Testing with name %s and login %s", name));
36        assumeNotNull(name);
37        assumeThat(name, notNullValue());
38    }
39
40    @DataPoints
41    public static String[] usersLogin() {
42        return new String[]{user1.getLogin(), user2.getLogin()};
43    }
44
45    @Theory
46    public void testUsersLogin(String login) throws Exception {
47        System.out.println(String.format("Testing with login %s ", login));
48        assumeNotNull(login);
49        assumeThat(login, notNullValue());
50    }
51
52    @DataPoints
53    public static int[] usersPassword() {
54        return new int[]{(int) user1.getPassword(), (int) user2.getPassword()};
55    }
56
57    @Theory
58    public void testUsersPassword(int password) throws Exception {
59        System.out.println(String.format("Testing with password %d ", password));
60        assumeNotNull(password);
61        assumeThat(password, notNullValue());
62    }
63}
Full Screen
copy
1/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.os;
18
19import static org.junit.Assert.assertEquals;
20import static org.junit.Assert.assertNotEquals;
21import static org.junit.Assert.assertNull;
22import static org.junit.Assert.assertThrows;
23import static org.junit.Assert.assertTrue;
24import static org.junit.Assume.assumeNotNull;
25
26import android.os.PerformanceHintManager.Session;
27
28import androidx.test.InstrumentationRegistry;
29import androidx.test.runner.AndroidJUnit4;
30
31import org.junit.Before;
32import org.junit.Test;
33import org.junit.runner.RunWith;
34import org.mockito.Mock;
35import org.mockito.MockitoAnnotations;
36
37@RunWith(AndroidJUnit4.class)
38public class PerformanceHintManagerTest {
39    private static final long RATE_1000 = 1000L;
40    private static final long TARGET_166 = 166L;
41    private static final long DEFAULT_TARGET_NS = 16666666L;
42    private PerformanceHintManager mPerformanceHintManager;
43
44    @Mock
45    private IHintSession mIHintSessionMock;
46
47    @Before
48    public void setUp() {
49        mPerformanceHintManager =
50                InstrumentationRegistry.getInstrumentation().getContext().getSystemService(
51                        PerformanceHintManager.class);
52        MockitoAnnotations.initMocks(this);
53    }
54
55    private Session createSession() {
56        return mPerformanceHintManager.createHintSession(
57                new int[]{Process.myPid()}, DEFAULT_TARGET_NS);
58    }
59
60    @Test
61    public void testCreateHintSession() {
62        Session a = createSession();
63        Session b = createSession();
64        if (a == null) {
65            assertNull(b);
66        } else {
67            assertNotEquals(a, b);
68        }
69    }
70
71    @Test
72    public void testGetPreferredUpdateRateNanos() {
73        if (createSession() != null) {
74            assertTrue(mPerformanceHintManager.getPreferredUpdateRateNanos() > 0);
75        } else {
76            assertEquals(-1, mPerformanceHintManager.getPreferredUpdateRateNanos());
77        }
78    }
79
80    @Test
81    public void testUpdateTargetWorkDuration() {
82        Session s = createSession();
83        assumeNotNull(s);
84        s.updateTargetWorkDuration(100);
85    }
86
87    @Test
88    public void testUpdateTargetWorkDurationWithNegativeDuration() {
89        Session s = createSession();
90        assumeNotNull(s);
91        assertThrows(IllegalArgumentException.class, () -> {
92            s.updateTargetWorkDuration(-1);
93        });
94    }
95
96    @Test
97    public void testReportActualWorkDuration() {
98        Session s = createSession();
99        assumeNotNull(s);
100        s.updateTargetWorkDuration(100);
101        s.reportActualWorkDuration(1);
102        s.reportActualWorkDuration(100);
103        s.reportActualWorkDuration(1000);
104    }
105
106    @Test
107    public void testReportActualWorkDurationWithIllegalArgument() {
108        Session s = createSession();
109        assumeNotNull(s);
110        s.updateTargetWorkDuration(100);
111        assertThrows(IllegalArgumentException.class, () -> {
112            s.reportActualWorkDuration(-1);
113        });
114    }
115
116    @Test
117    public void testCloseHintSession() {
118        Session s = createSession();
119        assumeNotNull(s);
120        s.close();
121    }
122}
123
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

Trigger assumeNotNull code on LambdaTest Cloud Grid

Execute automation tests with assumeNotNull on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

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)