Debian Codegraph @

cache/perf_test.go

raw
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License. See LICENSE in the project root for license information.
3
4 package cache
5
6 import (
7 "fmt"
8 "path/filepath"
9 "sync"
10 "testing"
11
12 "github.com/AzureAD/microsoft-authentication-extensions-for-go/cache/accessor/file"
13 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache"
14 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
15 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public"
16 "github.com/stretchr/testify/require"
17 )
18
19 // this file benchmarks MSAL clients using Cache and file.Accessor
20
21 func newCache(b *testing.B) *Cache {
22 p := filepath.Join(b.TempDir(), b.Name())
23 a, err := file.New(p)
24 require.NoError(b, err)
25 c, err := New(a, p+".timestamp")
26 require.NoError(b, err)
27 return c
28 }
29
30 func BenchmarkConfidentialClient(b *testing.B) {
31 for _, baseline := range []bool{false, true} {
32 name := "file accessor"
33 if baseline {
34 name = "no persistence"
35 }
36 b.Run(name, func(b *testing.B) {
37 var c cache.ExportReplace
38 if !baseline {
39 c = newCache(b)
40 }
41 cred, err := confidential.NewCredFromSecret("*")
42 require.NoError(b, err)
43 client, err := confidential.New(
44 "https://login.microsoftonline.com/tenant", "ID", cred, confidential.WithCache(c), confidential.WithHTTPClient(&mockSTS{}),
45 )
46 require.NoError(b, err)
47
48 gr := 10
49 wg := sync.WaitGroup{}
50 b.ResetTimer()
51 for i := 0; i < b.N; i++ {
52 for i := 0; i < gr; i++ {
53 wg.Add(1)
54 go func(n int) {
55 defer wg.Done()
56 s := fmt.Sprint(n)
57 _, _ = client.AcquireTokenByCredential(ctx, []string{s})
58 _, _ = client.AcquireTokenSilent(ctx, []string{s})
59 }(i)
60 }
61 wg.Wait()
62 }
63 })
64 }
65 }
66
67 func BenchmarkPublicClient(b *testing.B) {
68 for _, baseline := range []bool{false, true} {
69 name := "file accessor"
70 if baseline {
71 name = "no persistence"
72 }
73 b.Run(name, func(b *testing.B) {
74 var c cache.ExportReplace
75 if !baseline {
76 c = newCache(b)
77 }
78 client, err := public.New("clientID", public.WithCache(c), public.WithHTTPClient(&mockSTS{}))
79 require.NoError(b, err)
80
81 gr := 10
82 wg := sync.WaitGroup{}
83 b.ResetTimer()
84 for i := 0; i < b.N; i++ {
85 for i := 0; i < gr; i++ {
86 wg.Add(1)
87 go func(n int) {
88 defer wg.Done()
89 s := fmt.Sprint(n)
90 ar, _ := client.AcquireTokenByUsernamePassword(ctx, []string{s}, s, "password")
91 _, _ = client.AcquireTokenSilent(ctx, []string{s}, public.WithSilentAccount(ar.Account))
92 }(i)
93 }
94 wg.Wait()
95 }
96 })
97 }
98 }