How to use ShouldSetACookieOnADifferentDomain method of PuppeteerSharp.Tests.CookiesTests.SetCookiesTests class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tests.CookiesTests.SetCookiesTests.ShouldSetACookieOnADifferentDomain

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

SetCookiesTests.cs

Source: SetCookiesTests.cs Github

copy
1using System;
2using System.Threading.Tasks;
3using PuppeteerSharp.Tests.Attributes;
4using PuppeteerSharp.Xunit;
5using Xunit;
6using Xunit.Abstractions;
7
8namespace PuppeteerSharp.Tests.CookiesTests
9{
10    [Collection(TestConstants.TestFixtureCollectionName)]
11    public class SetCookiesTests : PuppeteerPageBaseTest
12    {
13        public SetCookiesTests(ITestOutputHelper output) : base(output)
14        {
15        }
16
17        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should work")]
18        [SkipBrowserFact(skipFirefox: true)]
19        public async Task ShouldWork()
20        {
21            await Page.GoToAsync(TestConstants.EmptyPage);
22            await Page.SetCookieAsync(new CookieParam
23            {
24                Name = "password",
25                Value = "123456"
26            });
27            Assert.Equal("password=123456", await Page.EvaluateExpressionAsync<string>("document.cookie"));
28        }
29
30        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should isolate cookies in browser contexts")]
31        [SkipBrowserFact(skipFirefox: true)]
32        public async Task ShouldIsolateCookiesInBrowserContexts()
33        {
34            var anotherContext = await Browser.CreateIncognitoBrowserContextAsync();
35            var anotherPage = await anotherContext.NewPageAsync();
36
37            await Page.GoToAsync(TestConstants.EmptyPage);
38            await anotherPage.GoToAsync(TestConstants.EmptyPage);
39
40            await Page.SetCookieAsync(new CookieParam
41            {
42                Name = "page1cookie",
43                Value = "page1value"
44            });
45
46            await anotherPage.SetCookieAsync(new CookieParam
47            {
48                Name = "page2cookie",
49                Value = "page2value"
50            });
51
52            var cookies1 = await Page.GetCookiesAsync();
53            var cookies2 = await anotherPage.GetCookiesAsync();
54
55            Assert.Single(cookies1);
56            Assert.Single(cookies2);
57            Assert.Equal("page1cookie", cookies1[0].Name);
58            Assert.Equal("page1value", cookies1[0].Value);
59            Assert.Equal("page2cookie", cookies2[0].Name);
60            Assert.Equal("page2value", cookies2[0].Value);
61
62            await anotherContext.CloseAsync();
63        }
64
65        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set multiple cookies")]
66        [SkipBrowserFact(skipFirefox: true)]
67        public async Task ShouldSetMultipleCookies()
68        {
69            await Page.GoToAsync(TestConstants.EmptyPage);
70
71            await Page.SetCookieAsync(
72                new CookieParam
73                {
74                    Name = "password",
75                    Value = "123456"
76                },
77                new CookieParam
78                {
79                    Name = "foo",
80                    Value = "bar"
81                }
82            );
83
84            Assert.Equal(
85                new[]
86                {
87                    "foo=bar",
88                    "password=123456"
89                },
90                await Page.EvaluateFunctionAsync<string[]>(@"() => {
91                    const cookies = document.cookie.split(';');
92                    return cookies.map(cookie => cookie.trim()).sort();
93                }")
94            );
95        }
96
97        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should have |expires| set to |-1| for session cookies")]
98        [PuppeteerFact]
99        public async Task ShouldHaveExpiresSetToMinus1ForSessionCookies()
100        {
101            await Page.GoToAsync(TestConstants.EmptyPage);
102
103            await Page.SetCookieAsync(new CookieParam
104            {
105                Name = "password",
106                Value = "123456"
107            });
108
109            var cookies = await Page.GetCookiesAsync();
110
111            Assert.True(cookies[0].Session);
112            Assert.Equal(-1, cookies[0].Expires);
113        }
114
115        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set cookie with reasonable defaults")]
116        [PuppeteerFact]
117        public async Task ShouldSetCookieWithReasonableDefaults()
118        {
119            await Page.GoToAsync(TestConstants.EmptyPage);
120
121            await Page.SetCookieAsync(new CookieParam
122            {
123                Name = "password",
124                Value = "123456"
125            });
126
127            var cookie = Assert.Single(await Page.GetCookiesAsync());
128            Assert.Equal("password", cookie.Name);
129            Assert.Equal("123456", cookie.Value);
130            Assert.Equal("localhost", cookie.Domain);
131            Assert.Equal("/", cookie.Path);
132            Assert.Equal(-1, cookie.Expires);
133            Assert.Equal(14, cookie.Size);
134            Assert.False(cookie.HttpOnly);
135            Assert.False(cookie.Secure);
136            Assert.True(cookie.Session);
137        }
138
139        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set a cookie with a path")]
140        [SkipBrowserFact(skipFirefox: true)]
141        public async Task ShouldSetACookieWithAPath()
142        {
143            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
144            await Page.SetCookieAsync(new CookieParam
145            {
146                Name = "gridcookie",
147                Value = "GRID",
148                Path = "/grid.html"
149            });
150            var cookie = Assert.Single(await Page.GetCookiesAsync());
151            Assert.Equal("gridcookie", cookie.Name);
152            Assert.Equal("GRID", cookie.Value);
153            Assert.Equal("localhost", cookie.Domain);
154            Assert.Equal("/grid.html", cookie.Path);
155            Assert.Equal(cookie.Expires, -1);
156            Assert.Equal(14, cookie.Size);
157            Assert.False(cookie.HttpOnly);
158            Assert.False(cookie.Secure);
159            Assert.True(cookie.Session);
160        }
161
162        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should not set a cookie on a blank page")]
163        [SkipBrowserFact(skipFirefox: true)]
164        public async Task ShouldNotSetACookieOnABlankPage()
165        {
166            await Page.GoToAsync(TestConstants.AboutBlank);
167
168            var exception = await Assert.ThrowsAsync<MessageException>(async () => await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best" }));
169            Assert.Equal("Protocol error (Network.deleteCookies): At least one of the url and domain needs to be specified", exception.Message);
170        }
171
172        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should not set a cookie with blank page URL")]
173        [PuppeteerFact]
174        public async Task ShouldNotSetACookieWithBlankPageURL()
175        {
176            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
177
178            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.SetCookieAsync(new CookieParam
179            {
180                Name = "example-cookie",
181                Value = "best"
182            }, new CookieParam
183            {
184                Url = TestConstants.AboutBlank,
185                Name = "example-cookie-blank",
186                Value = "best"
187            }));
188            Assert.Equal("Blank page can not have cookie \"example-cookie-blank\"", exception.Message);
189        }
190
191        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should not set a cookie on a data URL page")]
192        [SkipBrowserFact(skipFirefox: true)]
193        public async Task ShouldNotSetACookieOnADataURLPage()
194        {
195            await Page.GoToAsync("data:,Hello%2C%20World!");
196            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best" }));
197
198            Assert.Equal("Protocol error (Network.deleteCookies): At least one of the url and domain needs to be specified", exception.Message);
199        }
200
201        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should default to setting secure cookie for HTTPS websites")]
202        [SkipBrowserFact(skipFirefox: true)]
203        public async Task ShouldDefaultToSettingSecureCookieForHttpsWebsites()
204        {
205            await Page.GoToAsync(TestConstants.EmptyPage);
206            var SecureUrl = "https://example.com";
207
208            await Page.SetCookieAsync(new CookieParam
209            {
210                Url = SecureUrl,
211                Name = "foo",
212                Value = "bar"
213            });
214            var cookie = Assert.Single(await Page.GetCookiesAsync(SecureUrl));
215            Assert.True(cookie.Secure);
216        }
217
218        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should be able to set unsecure cookie for HTTP website")]
219        [SkipBrowserFact(skipFirefox: true)]
220        public async Task ShouldBeAbleToSetUnsecureCookieForHttpWebSite()
221        {
222            await Page.GoToAsync(TestConstants.EmptyPage);
223            var SecureUrl = "http://example.com";
224
225            await Page.SetCookieAsync(new CookieParam
226            {
227                Url = SecureUrl,
228                Name = "foo",
229                Value = "bar"
230            });
231            var cookie = Assert.Single(await Page.GetCookiesAsync(SecureUrl));
232            Assert.False(cookie.Secure);
233        }
234
235        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set a cookie on a different domain")]
236        [SkipBrowserFact(skipFirefox: true)]
237        public async Task ShouldSetACookieOnADifferentDomain()
238        {
239            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
240            await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best", Url = "https://www.example.com" });
241            Assert.Equal(string.Empty, await Page.EvaluateExpressionAsync<string>("document.cookie"));
242            Assert.Empty(await Page.GetCookiesAsync());
243            var cookie = Assert.Single(await Page.GetCookiesAsync("https://www.example.com"));
244            Assert.Equal("example-cookie", cookie.Name);
245            Assert.Equal("best", cookie.Value);
246            Assert.Equal("www.example.com", cookie.Domain);
247            Assert.Equal("/", cookie.Path);
248            Assert.Equal(cookie.Expires, -1);
249            Assert.Equal(18, cookie.Size);
250            Assert.False(cookie.HttpOnly);
251            Assert.True(cookie.Secure);
252            Assert.True(cookie.Session);
253        }
254
255        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set cookies from a frame")]
256        [SkipBrowserFact(skipFirefox: true)]
257        public async Task ShouldSetCookiesFromAFrame()
258        {
259            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");
260            await Page.SetCookieAsync(new CookieParam { Name = "localhost-cookie", Value = "best" });
261            await Page.EvaluateFunctionAsync(@"src => {
262                    let fulfill;
263                    const promise = new Promise(x => fulfill = x);
264                    const iframe = document.createElement('iframe');
265                    document.body.appendChild(iframe);
266                    iframe.onload = fulfill;
267                    iframe.src = src;
268                    return promise;
269                }", TestConstants.CrossProcessHttpPrefix);
270            await Page.SetCookieAsync(new CookieParam { Name = "127-cookie", Value = "worst", Url = TestConstants.CrossProcessHttpPrefix });
271            Assert.Equal("localhost-cookie=best", await Page.EvaluateExpressionAsync<string>("document.cookie"));
272            Assert.Equal(string.Empty, await Page.FirstChildFrame().EvaluateExpressionAsync<string>("document.cookie"));
273            var cookie = Assert.Single(await Page.GetCookiesAsync());
274            Assert.Equal("localhost-cookie", cookie.Name);
275            Assert.Equal("best", cookie.Value);
276            Assert.Equal("localhost", cookie.Domain);
277            Assert.Equal("/", cookie.Path);
278            Assert.Equal(cookie.Expires, -1);
279            Assert.Equal(20, cookie.Size);
280            Assert.False(cookie.HttpOnly);
281            Assert.False(cookie.Secure);
282            Assert.True(cookie.Session);
283
284            cookie = Assert.Single(await Page.GetCookiesAsync(TestConstants.CrossProcessHttpPrefix));
285            Assert.Equal("127-cookie", cookie.Name);
286            Assert.Equal("worst", cookie.Value);
287            Assert.Equal("127.0.0.1", cookie.Domain);
288            Assert.Equal("/", cookie.Path);
289            Assert.Equal(cookie.Expires, -1);
290            Assert.Equal(15, cookie.Size);
291            Assert.False(cookie.HttpOnly);
292            Assert.False(cookie.Secure);
293            Assert.True(cookie.Session);
294        }
295    }
296}
297
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
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)