2 * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 /* Internal tests for the OpenSSL library context */
12 #include "internal/cryptlib.h"
16 * Everything between BEGIN EXAMPLE and END EXAMPLE is copied from
17 * doc/internal/man3/ossl_lib_ctx_get_data.pod
21 * ======================================================================
25 typedef struct foo_st {
30 static void *foo_new(OSSL_LIB_CTX *ctx)
32 FOO *ptr = OPENSSL_zalloc(sizeof(*ptr));
37 static void foo_free(void *ptr)
41 static const OSSL_LIB_CTX_METHOD foo_method = {
42 OSSL_LIB_CTX_METHOD_DEFAULT_PRIORITY,
49 * ======================================================================
52 static int test_context(OSSL_LIB_CTX *ctx)
56 return TEST_ptr(data = ossl_lib_ctx_get_data(ctx, 0, &foo_method))
57 /* OPENSSL_zalloc in foo_new() initialized it to zero */
58 && TEST_int_eq(data->i, 42);
61 static int test_app_context(void)
63 OSSL_LIB_CTX *ctx = NULL;
65 TEST_ptr(ctx = OSSL_LIB_CTX_new())
68 OSSL_LIB_CTX_free(ctx);
72 static int test_def_context(void)
74 return test_context(NULL);
77 static int test_set0_default(void)
79 OSSL_LIB_CTX *global = OSSL_LIB_CTX_get0_global_default();
80 OSSL_LIB_CTX *local = OSSL_LIB_CTX_new();
87 || !TEST_ptr_eq(global, OSSL_LIB_CTX_set0_default(NULL))
88 || !TEST_ptr(data = ossl_lib_ctx_get_data(local, 0, &foo_method)))
91 /* Set local "i" value to 43. Global "i" should be 42 */
93 if (!TEST_int_eq(data->i, 43))
96 /* The default context should still be the "global" default */
97 if (!TEST_ptr(data = ossl_lib_ctx_get_data(NULL, 0, &foo_method))
98 || !TEST_int_eq(data->i, 42))
101 /* Check we can change the local default context */
102 if (!TEST_ptr(prev = OSSL_LIB_CTX_set0_default(local))
103 || !TEST_ptr_eq(global, prev)
104 || !TEST_ptr(data = ossl_lib_ctx_get_data(NULL, 0, &foo_method))
105 || !TEST_int_eq(data->i, 43))
108 /* Calling OSSL_LIB_CTX_set0_default() with a NULL should be a no-op */
109 if (!TEST_ptr_eq(local, OSSL_LIB_CTX_set0_default(NULL))
110 || !TEST_ptr(data = ossl_lib_ctx_get_data(NULL, 0, &foo_method))
111 || !TEST_int_eq(data->i, 43))
114 /* Global default should be unchanged */
115 if (!TEST_ptr_eq(global, OSSL_LIB_CTX_get0_global_default()))
118 /* Check we can swap back to the global default */
119 if (!TEST_ptr(prev = OSSL_LIB_CTX_set0_default(global))
120 || !TEST_ptr_eq(local, prev)
121 || !TEST_ptr(data = ossl_lib_ctx_get_data(NULL, 0, &foo_method))
122 || !TEST_int_eq(data->i, 42))
127 OSSL_LIB_CTX_free(local);
131 int setup_tests(void)
133 ADD_TEST(test_app_context);
134 ADD_TEST(test_def_context);
135 ADD_TEST(test_set0_default);