How to use TracingOptions class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.TracingOptions

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

Tracing.cs

Source: Tracing.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Threading.Tasks;
5using PuppeteerSharp.Messaging;
6
7namespace PuppeteerSharp
8{
9    /// <summary>
10    /// You can use <see cref="Tracing.StartAsync(TracingOptions)"/> and <see cref="Tracing.StopAsync"/> to create a trace file which can be opened in Chrome DevTools or timeline viewer.
11    /// </summary>
12    /// <example>
13    /// <code>
14    /// await Page.Tracing.StartAsync(new TracingOptions
15    /// {
16    ///     Screenshots = true,
17    ///     Path = _file
18    /// });
19    /// await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
20    /// await Page.Tracing.StopAsync();
21    /// </code>
22    /// </example>
23    public class Tracing
24    {
25        private readonly CDPSession _client;
26        private bool _recording;
27        private string _path;
28        private static readonly List<string> _defaultCategories = new List<string>()
29        {
30            "-*",
31            "devtools.timeline",
32            "v8.execute",
33            "disabled-by-default-devtools.timeline",
34            "disabled-by-default-devtools.timeline.frame",
35            "toplevel",
36            "blink.console",
37            "blink.user_timing",
38            "latencyInfo",
39            "disabled-by-default-devtools.timeline.stack",
40            "disabled-by-default-v8.cpu_profiler"
41        };
42
43        internal Tracing(CDPSession client)
44        {
45            _client = client;
46        }
47
48        /// <summary>
49        /// Starts tracing.
50        /// </summary>
51        /// <returns>Start task</returns>
52        /// <param name="options">Tracing options</param>
53        public async Task StartAsync(TracingOptions options)
54        {
55            if (_recording)
56            {
57                throw new InvalidOperationException("Cannot start recording trace while already recording trace.");
58            }
59
60            if (string.IsNullOrEmpty(options.Path))
61            {
62                throw new ArgumentException("Must specify a path to write trace file to.");
63            }
64
65
66            var categories = options.Categories ?? _defaultCategories;
67
68            if (options.Screenshots)
69            {
70                categories.Add("disabled-by-default-devtools.screenshot");
71            }
72
73            _path = options.Path;
74            _recording = true;
75
76            await _client.SendAsync("Tracing.start", new
77            {
78                transferMode = "ReturnAsStream",
79                categories = string.Join(", ", categories)
80            });
81        }
82
83        /// <summary>
84        /// Stops tracing
85        /// </summary>
86        /// <returns>Stop task</returns>
87        public async Task StopAsync()
88        {
89            var taskWrapper = new TaskCompletionSource<bool>();
90
91            async void EventHandler(object sender, TracingCompleteEventArgs e)
92            {
93                await ReadStream(e.Stream, _path);
94                _client.TracingComplete -= EventHandler;
95                taskWrapper.SetResult(true);
96            }
97
98            _client.TracingComplete += EventHandler;
99
100            await _client.SendAsync("Tracing.end");
101
102            _recording = false;
103
104            await taskWrapper.Task;
105        }
106
107        private async Task ReadStream(string stream, string path)
108        {
109            using (var fs = new StreamWriter(path))
110            {
111                bool eof = false;
112
113                while (!eof)
114                {
115                    var response = await _client.SendAsync<IOReadResponse>("IO.read", new
116                    {
117                        handle = stream
118                    });
119
120                    eof = response.Eof;
121
122                    await fs.WriteAsync(response.Data);
123                }
124            }
125            await _client.SendAsync("IO.close", new
126            {
127                handle = stream
128            });
129        }
130    }
131}
Full Screen

TracingTests.cs

Source: TracingTests.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Linq;
5using System.Text;
6using System.Threading.Tasks;
7using Newtonsoft.Json;
8using Newtonsoft.Json.Linq;
9using PuppeteerSharp.Tests.Attributes;
10using PuppeteerSharp.Xunit;
11using Xunit;
12using Xunit.Abstractions;
13
14namespace PuppeteerSharp.Tests.TracingTests
15{
16    [Collection(TestConstants.TestFixtureCollectionName)]
17    public class TracingTests : PuppeteerPageBaseTest
18    {
19        private readonly string _file;
20
21        public TracingTests(ITestOutputHelper output) : base(output)
22        {
23            _file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
24        }
25
26        public override async Task DisposeAsync()
27        {
28            await base.DisposeAsync();
29
30            var attempts = 0;
31            const int maxAttempts = 5;
32
33            while (true)
34            {
35                try
36                {
37                    attempts++;
38                    if (File.Exists(_file))
39                    {
40                        File.Delete(_file);
41                    }
42                    break;
43                }
44                catch (UnauthorizedAccessException)
45                {
46                    if (attempts == maxAttempts)
47                    {
48                        break;
49                    }
50
51                    await Task.Delay(1000);
52                }
53            }
54        }
55
56        [PuppeteerTest("tracing.spec.ts", "Tracing", "should output a trace")]
57        [SkipBrowserFact(skipFirefox: true)]
58        public async Task ShouldOutputATrace()
59        {
60            await Page.Tracing.StartAsync(new TracingOptions
61            {
62                Screenshots = true,
63                Path = _file
64            });
65            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
66            await Page.Tracing.StopAsync();
67
68            Assert.True(File.Exists(_file));
69        }
70
71        [PuppeteerTest("tracing.spec.ts", "Tracing", "should run with custom categories if provided")]
72        [SkipBrowserFact(skipFirefox: true)]
73        public async Task ShouldRunWithCustomCategoriesProvided()
74        {
75            await Page.Tracing.StartAsync(new TracingOptions
76            {
77                Screenshots = true,
78                Path = _file,
79                Categories = new List<string>
80                {
81                    "disabled-by-default-v8.cpu_profiler.hires"
82                }
83            });
84
85            await Page.Tracing.StopAsync();
86
87            using (var file = File.OpenText(_file))
88            using (var reader = new JsonTextReader(file))
89            {
90                var traceJson = JToken.ReadFrom(reader);
91                Assert.Contains("disabled-by-default-v8.cpu_profiler.hires", traceJson["metadata"]["trace-config"].ToString());
92            }
93        }
94
95        [PuppeteerTest("tracing.spec.ts", "Tracing", "should throw if tracing on two pages")]
96        [SkipBrowserFact(skipFirefox: true)]
97        public async Task ShouldThrowIfTracingOnTwoPages()
98        {
99            await Page.Tracing.StartAsync(new TracingOptions
100            {
101                Path = _file
102            });
103            var newPage = await Browser.NewPageAsync();
104            await Assert.ThrowsAsync<InvalidOperationException>(async () =>
105            {
106                await Page.Tracing.StartAsync(new TracingOptions
107                {
108                    Path = _file
109                });
110            });
111
112            await newPage.CloseAsync();
113            await Page.Tracing.StopAsync();
114        }
115
116        [PuppeteerTest("tracing.spec.ts", "Tracing", "should return a buffer")]
117        [SkipBrowserFact(skipFirefox: true)]
118        public async Task ShouldReturnABuffer()
119        {
120            await Page.Tracing.StartAsync(new TracingOptions
121            {
122                Screenshots = true,
123                Path = _file
124            });
125            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
126            var trace = await Page.Tracing.StopAsync();
127            var buf = File.ReadAllText(_file);
128            Assert.Equal(trace, buf);
129        }
130
131        [PuppeteerTest("tracing.spec.ts", "Tracing", "should work without options")]
132        [SkipBrowserFact(skipFirefox: true)]
133        public async Task ShouldWorkWithoutOptions()
134        {
135            await Page.Tracing.StartAsync();
136            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
137            var trace = await Page.Tracing.StopAsync();
138            Assert.NotNull(trace);
139        }
140
141        [PuppeteerTest("tracing.spec.ts", "Tracing", "should support a buffer without a path")]
142        [SkipBrowserFact(skipFirefox: true)]
143        public async Task ShouldSupportABufferWithoutAPath()
144        {
145            await Page.Tracing.StartAsync(new TracingOptions
146            {
147                Screenshots = true
148            });
149            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
150            var trace = await Page.Tracing.StopAsync();
151            Assert.Contains("screenshot", trace);
152        }
153    }
154}
155
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 used methods in TracingOptions

    No methods found for this class 😞

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)