How to use test_url method in wpt

Best JavaScript code snippet using wpt

backstop.js

Source:backstop.js Github

copy

Full Screen

1const TEST_HOST = process.env.HOSTNAME === 'docker-desktop' ? 'host.docker.internal' : '0.0.0.0';2const TEST_URL = `http://${TEST_HOST}:3000/components`;3module.exports = {4 dockerCommandTemplate: 'docker run --rm --network=host --mount type=bind,source="{cwd}",target=/src backstopjs/backstopjs:{version} {backstopCommand} {args}',5 id: 'nhsuk-frontend',6 viewports: [7 {8 label: 'iPhone 5/SE',9 width: 320,10 height: 568,11 },12 {13 label: 'iPhone 6-8',14 width: 375,15 height: 667,16 },17 {18 label: 'iPad',19 width: 768,20 height: 1024,21 },22 {23 label: 'Surface, iPad Pro',24 width: 1366,25 height: 768,26 },27 ],28 onBeforeScript: 'puppet/onBefore.js',29 onReadyScript: 'puppet/onReady.js',30 scenarios: [31 {32 label: 'A-Z navigation',33 url: `${TEST_URL}/nav-a-z/index.html`,34 },35 {36 label: 'Action link',37 url: `${TEST_URL}/action-link/index.html`,38 },39 {40 label: 'Back link',41 url: `${TEST_URL}/back-link/index.html`,42 },43 {44 label: 'Breadcrumb',45 url: `${TEST_URL}/breadcrumb/index.html`,46 },47 {48 label: 'Button',49 url: `${TEST_URL}/button/index.html`,50 },51 {52 label: 'Button click',53 url: `${TEST_URL}/button/index.html`,54 clickSelector: '.nhsuk-button',55 viewports: [56 {57 label: 'Surface, iPad Pro',58 width: 1366,59 height: 768,60 },61 ],62 },63 {64 label: 'Button as a link',65 url: `${TEST_URL}/button/link.html`,66 },67 {68 label: 'Button disabled',69 url: `${TEST_URL}/button/disabled.html`,70 },71 {72 label: 'Button secondary',73 url: `${TEST_URL}/button/secondary.html`,74 },75 {76 label: 'Button reverse',77 url: `${TEST_URL}/button/reverse.html`,78 },79 {80 label: 'Card - Basic card',81 url: `${TEST_URL}/card/basic-card.html`,82 },83 {84 label: 'Card - Clickable card',85 url: `${TEST_URL}/card/clickable-card.html`,86 },87 {88 label: 'Card - Card with image',89 url: `${TEST_URL}/card/card-with-image.html`,90 },91 {92 label: 'Card - Card group',93 url: `${TEST_URL}/card/card-group.html`,94 },95 {96 label: 'Card - Card group',97 url: `${TEST_URL}/card/feature-card.html`,98 },99 {100 label: 'Care card - Non urgent',101 url: `${TEST_URL}/care-card/care-card-non-urgent.html`,102 },103 {104 label: 'Care card - Urgent',105 url: `${TEST_URL}/care-card/care-card-urgent.html`,106 },107 {108 label: 'Care card - Immediate',109 url: `${TEST_URL}/care-card/care-card-immediate.html`,110 },111 {112 label: 'Checkboxes',113 url: `${TEST_URL}/checkboxes/index.html`,114 },115 {116 label: 'Checkboxes with hint text',117 url: `${TEST_URL}/checkboxes/hint.html`,118 },119 {120 label: 'Checkboxes with disabled item',121 url: `${TEST_URL}/checkboxes/disabled.html`,122 },123 {124 label: 'Checkboxes with legend as page heading',125 url: `${TEST_URL}/checkboxes/page-heading.html`,126 },127 {128 label: 'Checkboxes with error message',129 url: `${TEST_URL}/checkboxes/error.html`,130 },131 {132 label: 'Checkboxes with conditional content',133 url: `${TEST_URL}/checkboxes/conditional.html`,134 clickSelector: '#contact-1',135 },136 {137 label: 'Contents list',138 url: `${TEST_URL}/contents-list/index.html`,139 },140 {141 label: 'Date input',142 url: `${TEST_URL}/date-input/index.html`,143 },144 {145 label: 'Date input with multiple errors',146 url: `${TEST_URL}/date-input/multiple-errors.html`,147 },148 {149 label: 'Details',150 url: `${TEST_URL}/details/index.html`,151 clickSelector: '.nhsuk-details__summary',152 },153 {154 label: "Do & Don't list",155 url: `${TEST_URL}/do-dont-list/index.html`,156 },157 {158 label: 'Error message',159 url: `${TEST_URL}/error-message/index.html`,160 },161 {162 label: 'Error summary',163 url: `${TEST_URL}/error-summary/index.html`,164 },165 {166 label: 'Error summary with link to an input field',167 url: `${TEST_URL}/error-summary/linking-to-input.html`,168 },169 {170 label: 'Error summary with link to a radio field',171 url: `${TEST_URL}/error-summary/linking-to-radios.html`,172 },173 {174 label: 'Expander',175 url: `${TEST_URL}/details/expander.html`,176 clickSelector: '.nhsuk-details__summary',177 },178 {179 label: 'Expander group',180 url: `${TEST_URL}/details/expander-group.html`,181 clickSelector: '.nhsuk-details__summary',182 },183 {184 label: 'Footer',185 url: `${TEST_URL}/footer/index.html`,186 },187 {188 label: 'Fieldset',189 url: `${TEST_URL}/fieldset/index.html`,190 },191 {192 label: 'Fieldset as page heading',193 url: `${TEST_URL}/fieldset/page-heading.html`,194 },195 {196 label: 'Fieldset with inputs',197 url: `${TEST_URL}/fieldset/with-inputs.html`,198 },199 {200 label: 'Header',201 url: `${TEST_URL}/header/index.html`,202 },203 {204 label: 'Header with logo only',205 url: `${TEST_URL}/header/header-logo.html`,206 },207 {208 label: 'Header with a service name',209 url: `${TEST_URL}/header/header-service-name.html`,210 },211 {212 label: 'Header with a service name, search and navigation',213 url: `${TEST_URL}/header/header-service-name-with-nav.html`,214 },215 {216 label: 'Header transactional',217 url: `${TEST_URL}/header/header-transactional.html`,218 },219 {220 label: 'Header transactional with service name',221 url: `${TEST_URL}/header/header-transactional-service-name.html`,222 },223 {224 label: 'Header transactional with a long service name',225 url: `${TEST_URL}/header/header-transactional-long-service-name.html`,226 },227 {228 label: 'Header with navigation',229 url: `${TEST_URL}/header/header-navigation.html`,230 },231 {232 label: 'Header with navigation open',233 url: `${TEST_URL}/header/header-navigation.html`,234 clickSelector: '#toggle-menu',235 viewports: [236 {237 label: 'iPhone 5/SE',238 width: 320,239 height: 568,240 },241 {242 label: 'iPhone 6-8',243 width: 375,244 height: 667,245 },246 {247 label: 'iPad',248 width: 768,249 height: 1024,250 },251 ],252 },253 {254 label: 'Header with search',255 url: `${TEST_URL}/header/header-search.html`,256 },257 {258 label: 'Header with search open',259 url: `${TEST_URL}/header/header-search.html`,260 clickSelector: '#toggle-search',261 viewports: [262 {263 label: 'iPhone 5/SE',264 width: 320,265 height: 568,266 },267 {268 label: 'iPhone 6-8',269 width: 375,270 height: 667,271 },272 ],273 },274 {275 label: 'Header organisational',276 url: `${TEST_URL}/header/header-org.html`,277 },278 {279 label: 'Header organisational with white header',280 url: `${TEST_URL}/header/header-org-white.html`,281 },282 {283 label: 'Header organisational with white header and navigation',284 url: `${TEST_URL}/header/header-org-white-nav.html`,285 },286 {287 label: 'Hero',288 url: `${TEST_URL}/hero/index.html`,289 },290 {291 label: 'Hero with image',292 url: `${TEST_URL}/hero/hero-image.html`,293 },294 {295 label: 'Hero with image and content',296 url: `${TEST_URL}/hero/hero-image-content.html`,297 },298 {299 label: 'Hint',300 url: `${TEST_URL}/hint/index.html`,301 },302 {303 label: 'Images',304 url: `${TEST_URL}/images/index.html`,305 },306 {307 label: 'Input',308 url: `${TEST_URL}/input/index.html`,309 },310 {311 label: 'Input with hint text',312 url: `${TEST_URL}/input/hint.html`,313 },314 {315 label: 'Input with error message',316 url: `${TEST_URL}/input/error.html`,317 },318 {319 label: 'Input with width modifier',320 url: `${TEST_URL}/input/custom-width.html`,321 },322 {323 label: 'Inset text',324 url: `${TEST_URL}/inset-text/index.html`,325 },326 {327 label: 'Label',328 url: `${TEST_URL}/label/index.html`,329 },330 {331 label: 'Label with bold text',332 url: `${TEST_URL}/label/bold.html`,333 },334 {335 label: 'Label as page heading',336 url: `${TEST_URL}/label/page-heading.html`,337 },338 {339 label: 'List panel',340 url: `${TEST_URL}/list-panel/index.html`,341 },342 {343 label: 'Pagination',344 url: `${TEST_URL}/pagination/index.html`,345 },346 {347 label: 'Radios',348 url: `${TEST_URL}/radios/index.html`,349 },350 {351 label: 'Radios inline',352 url: `${TEST_URL}/radios/inline.html`,353 },354 {355 label: 'Radios disabled',356 url: `${TEST_URL}/radios/disabled.html`,357 },358 {359 label: 'Radios with a divider',360 url: `${TEST_URL}/radios/divider.html`,361 },362 {363 label: 'Radios with hint text',364 url: `${TEST_URL}/radios/hint.html`,365 },366 {367 label: 'Radios without fieldset',368 url: `${TEST_URL}/radios/without-fieldset.html`,369 },370 {371 label: 'Radios with hint text and error message',372 url: `${TEST_URL}/radios/hint-error.html`,373 },374 {375 label: 'Radios with conditional content',376 url: `${TEST_URL}/radios/conditional.html`,377 clickSelector: '#contact-1',378 },379 {380 label: 'Select',381 url: `${TEST_URL}/select/index.html`,382 },383 {384 label: 'Select with hint text and error message',385 url: `${TEST_URL}/select/hint-error.html`,386 },387 {388 label: 'Summary list',389 url: `${TEST_URL}/summary-list/index.html`,390 },391 {392 label: 'Summary list without actions',393 url: `${TEST_URL}/summary-list/without-actions.html`,394 },395 {396 label: 'Summary list without border',397 url: `${TEST_URL}/summary-list/without-border.html`,398 },399 {400 label: 'Table',401 url: `${TEST_URL}/tables/index.html`,402 },403 {404 label: 'Responsive table',405 url: `${TEST_URL}/tables/responsive-table.html`,406 },407 {408 label: 'Table as panel',409 url: `${TEST_URL}/tables/tables-panel.html`,410 },411 {412 label: 'Tag',413 url: `${TEST_URL}/tag/index.html`,414 },415 {416 label: 'Textarea',417 url: `${TEST_URL}/textarea/index.html`,418 },419 {420 label: 'Textarea with error message',421 url: `${TEST_URL}/textarea/error.html`,422 },423 {424 label: 'Warning callout',425 url: `${TEST_URL}/warning-callout/index.html`,426 },427 {428 label: 'Warning callout with custom heading',429 url: `${TEST_URL}/warning-callout/custom-heading.html`,430 },431 ],432 paths: {433 bitmaps_reference: 'tests/backstop/bitmaps_reference',434 bitmaps_test: 'tests/backstop/bitmaps_test',435 engine_scripts: 'tests/backstop/engine_scripts',436 html_report: 'tests/backstop/html_report',437 ci_report: 'tests/backstop/ci_report',438 },439 report: ['browser'],440 engine: 'puppeteer',441 engineOptions: {442 args: ['--no-sandbox'],443 },444 asyncCaptureLimit: 5,445 asyncCompareLimit: 50,446 debug: false,447 debugWindow: false,...

Full Screen

Full Screen

test_connector.py

Source:test_connector.py Github

copy

Full Screen

...9from haystack.nodes.connector import Crawler10from haystack.schema import Document11from ..conftest import SAMPLES_PATH12@pytest.fixture(scope="session")13def test_url():14 return f"file://{SAMPLES_PATH.absolute()}/crawler"15def content_match(crawler: Crawler, url: str, crawled_page: Path):16 """17 :param crawler: the tested Crawler object18 :param url: the URL of the expected page19 :param crawled_page: the output of Crawler (one element of the paths list)20 """21 crawler.driver.get(url)22 body = crawler.driver.find_element(by=By.TAG_NAME, value="body")23 if crawler.extract_hidden_text:24 expected_crawled_content = body.get_attribute("textContent")25 else:26 expected_crawled_content = body.text27 with open(crawled_page, "r") as crawled_file:...

Full Screen

Full Screen

utils.spec.ts

Source:utils.spec.ts Github

copy

Full Screen

1import mockKnex from 'mock-knex';2import mockdate from 'mockdate';3import { getTrailUrl, getNonExistedTrailId, createTrail } from '../utils';4import knex from '../knex';5import redis from '../redis';6import {7 TEST_ID,8 TEST_URL,9 TEST_EXPIRE_AT,10 GENERATED_TRAIL_ID_1,11 GENERATED_TRAIL_ID_2,12} from '../../test/constants';13mockdate.set('2022-01-13');14jest.mock('../redis');15const mockedRedis = jest.mocked(redis, true);16let tracker: mockKnex.Tracker;17beforeAll(() => {18 mockKnex.mock(knex);19 tracker = mockKnex.getTracker();20});21beforeEach(() => {22 jest.clearAllMocks();23 tracker.install();24});25afterEach(() => {26 tracker.uninstall();27});28describe('#getTrailUrl', () => {29 it('should get cached url from redis if existed.', async () => {30 mockedRedis.get.mockResolvedValue(TEST_URL);31 const trailUrl = await getTrailUrl(TEST_ID);32 expect(trailUrl).toEqual(TEST_URL);33 expect(mockedRedis.get).toBeCalledWith(TEST_ID);34 });35 it('should get cached url from database if existed, and cache it with url and expired time.', async () => {36 mockedRedis.get.mockResolvedValue(null);37 tracker.on('query', (query, step) => {38 [39 () => {40 expect(query).toMatchObject({41 sql: 'select "url", "expire_at" from "trails" where "id" = $1 and ("expire_at" > CURRENT_TIMESTAMP or "expire_at" is null)',42 bindings: [TEST_ID],43 });44 query.response([45 {46 url: TEST_URL,47 expire_at: TEST_EXPIRE_AT,48 },49 ]);50 },51 ][step - 1]();52 });53 const trailUrl = await getTrailUrl(TEST_ID);54 const expireTime = Math.round(55 (TEST_EXPIRE_AT.getTime() - new Date().getTime()) / 100056 );57 expect(trailUrl).toEqual(TEST_URL);58 expect(mockedRedis.get).toBeCalledWith(TEST_ID);59 expect(mockedRedis.setex).toHaveBeenCalledWith(60 TEST_ID,61 expireTime,62 TEST_URL63 );64 });65 it('should return null if none url found by querying given id.', async () => {66 mockedRedis.get.mockResolvedValue(null);67 tracker.on('query', (query, step) => {68 [69 () => {70 expect(query).toMatchObject({71 sql: 'select "url", "expire_at" from "trails" where "id" = $1 and ("expire_at" > CURRENT_TIMESTAMP or "expire_at" is null)',72 bindings: [TEST_ID],73 });74 query.response([]);75 },76 ][step - 1]();77 });78 const trailUrl = await getTrailUrl(TEST_ID);79 expect(trailUrl).toEqual(null);80 expect(mockedRedis.get).toBeCalledWith(TEST_ID);81 expect(mockedRedis.setex).not.toHaveBeenCalled();82 });83});84describe('#getNonExistedTrailId', () => {85 it('should retry when generated id existed in cache.', async () => {86 mockedRedis.get.mockImplementation(async (id) => {87 if (id === GENERATED_TRAIL_ID_1) return TEST_URL;88 return null;89 });90 tracker.on('query', (query) => {91 query.response([]);92 });93 const trailIdGenerator = jest94 .fn()95 .mockReturnValueOnce(GENERATED_TRAIL_ID_1)96 .mockReturnValueOnce(GENERATED_TRAIL_ID_2);97 expect(await getNonExistedTrailId(trailIdGenerator)).toEqual(98 GENERATED_TRAIL_ID_299 );100 expect(trailIdGenerator).toHaveBeenCalledTimes(2);101 expect(mockedRedis.get.mock.calls[0][0]).toBe(GENERATED_TRAIL_ID_1);102 expect(mockedRedis.get.mock.calls[1][0]).toBe(GENERATED_TRAIL_ID_2);103 });104 it('should retry when generated id existed in database.', async () => {105 mockedRedis.get.mockResolvedValue(null);106 tracker.on('query', (query, step) => {107 [108 () => {109 expect(query).toMatchObject({110 sql: 'select "url", "expire_at" from "trails" where "id" = $1 and ("expire_at" > CURRENT_TIMESTAMP or "expire_at" is null)',111 bindings: [GENERATED_TRAIL_ID_1],112 });113 query.response([114 {115 url: TEST_URL,116 expire_at: TEST_EXPIRE_AT,117 },118 ]);119 },120 () => {121 expect(query).toMatchObject({122 sql: 'select "url", "expire_at" from "trails" where "id" = $1 and ("expire_at" > CURRENT_TIMESTAMP or "expire_at" is null)',123 bindings: [GENERATED_TRAIL_ID_2],124 });125 query.response([]);126 },127 ][step - 1]();128 });129 const trailIdGenerator = jest130 .fn()131 .mockReturnValueOnce(GENERATED_TRAIL_ID_1)132 .mockReturnValueOnce(GENERATED_TRAIL_ID_2);133 expect(await getNonExistedTrailId(trailIdGenerator)).toEqual(134 GENERATED_TRAIL_ID_2135 );136 expect(trailIdGenerator).toHaveBeenCalledTimes(2);137 expect(mockedRedis.get.mock.calls[0][0]).toBe(GENERATED_TRAIL_ID_1);138 expect(mockedRedis.get.mock.calls[1][0]).toBe(GENERATED_TRAIL_ID_2);139 });140 it('should not retry when generated id not existed in cache or database.', async () => {141 mockedRedis.get.mockResolvedValue(null);142 tracker.on('query', (query, step) => {143 [144 () => {145 expect(query).toMatchObject({146 sql: 'select "url", "expire_at" from "trails" where "id" = $1 and ("expire_at" > CURRENT_TIMESTAMP or "expire_at" is null)',147 bindings: [GENERATED_TRAIL_ID_1],148 });149 query.response([]);150 },151 () => {152 expect(query).toMatchObject({153 sql: 'select "url", "expire_at" from "trails" where "id" = $1 and ("expire_at" > CURRENT_TIMESTAMP or "expire_at" is null)',154 bindings: [GENERATED_TRAIL_ID_2],155 });156 query.response([]);157 },158 ][step - 1]();159 });160 const trailIdGenerator = jest161 .fn()162 .mockReturnValueOnce(GENERATED_TRAIL_ID_1)163 .mockReturnValueOnce(GENERATED_TRAIL_ID_2);164 expect(await getNonExistedTrailId(trailIdGenerator)).toEqual(165 GENERATED_TRAIL_ID_1166 );167 expect(trailIdGenerator).toHaveBeenCalledTimes(1);168 expect(mockedRedis.get).toBeCalledWith(GENERATED_TRAIL_ID_1);169 });170});171describe('#createTrail', () => {172 it('should create both db and redis record without expireAt.', async () => {173 tracker.on('query', (query, step) => {174 [175 () => {176 expect(query).toMatchObject({177 sql: 'insert into "trails" ("expire_at", "id", "url") values (DEFAULT, $1, $2) on conflict ("id") do nothing returning "id", "expire_at"',178 bindings: [TEST_ID, TEST_URL],179 });180 query.response([181 {182 id: TEST_ID,183 url: TEST_URL,184 },185 ]);186 },187 ][step - 1]();188 });189 const trail = await createTrail({190 id: TEST_ID,191 url: TEST_URL,192 });193 const expireTime = Number(process.env.DEFAULT_CACHE_EXPIRE_IN_SEC);194 expect(trail).toEqual({195 id: TEST_ID,196 url: TEST_URL,197 });198 expect(mockedRedis.setex).toHaveBeenCalledWith(199 TEST_ID,200 expireTime,201 TEST_URL202 );203 });204 it('should create both db and redis record with expireAt.', async () => {205 tracker.on('query', (query, step) => {206 [207 () => {208 expect(query).toMatchObject({209 sql: 'insert into "trails" ("expire_at", "id", "url") values ($1, $2, $3) on conflict ("id") do nothing returning "id", "expire_at"',210 bindings: [TEST_EXPIRE_AT, TEST_ID, TEST_URL],211 });212 query.response([213 {214 id: TEST_ID,215 url: TEST_URL,216 expire_at: TEST_EXPIRE_AT,217 },218 ]);219 },220 ][step - 1]();221 });222 const trail = await createTrail({223 id: TEST_ID,224 url: TEST_URL,225 expireAt: TEST_EXPIRE_AT,226 });227 const expireTime = Math.round(228 (TEST_EXPIRE_AT.getTime() - new Date().getTime()) / 1000229 );230 expect(trail).toEqual({231 id: TEST_ID,232 url: TEST_URL,233 expireAt: TEST_EXPIRE_AT,234 });235 expect(mockedRedis.setex).toHaveBeenCalledWith(236 TEST_ID,237 expireTime,238 TEST_URL239 );240 });...

Full Screen

Full Screen

utils.test.ts

Source:utils.test.ts Github

copy

Full Screen

1import CookieUtils from '../../src/cookie-filtering/utils';2import ParsedCookie from '../../src/cookie-filtering/parsed-cookie';3const TEST_URL = 'https://test.com/url';4describe('Cookie utils - Set-Cookie headers parsing', () => {5 it('checks parse simple', () => {6 let cookies = CookieUtils.parseSetCookieHeaders([], TEST_URL);7 expect(cookies).toHaveLength(0);8 cookies = CookieUtils.parseSetCookieHeaders([9 {10 name: 'set-cookie',11 value: 'ok',12 },13 ], TEST_URL);14 expect(cookies).toHaveLength(1);15 cookies = CookieUtils.parseSetCookieHeaders([16 {17 name: 'invalid',18 value: 'invalid',19 },20 ], TEST_URL);21 expect(cookies).toHaveLength(0);22 cookies = CookieUtils.parseSetCookieHeaders([23 {24 name: 'set-cookie',25 value: undefined,26 },27 ], TEST_URL);28 expect(cookies).toHaveLength(0);29 cookies = CookieUtils.parseSetCookieHeaders([30 {31 name: 'set-cookie',32 value: '',33 },34 ], TEST_URL);35 expect(cookies).toHaveLength(0);36 });37});38describe('Cookie utils - Set-Cookie parsing', () => {39 it('checks parse simple', () => {40 const cookie = CookieUtils.parseSetCookie('value=123', TEST_URL);41 expect(cookie).not.toBeNull();42 expect(cookie!.name).toBe('value');43 expect(cookie!.value).toBe('123');44 expect(cookie!.url).toBe(TEST_URL);45 expect(cookie!.domain).toBe('test.com');46 });47 it('checks parse complicated', () => {48 // eslint-disable-next-line max-len49 const cookie = CookieUtils.parseSetCookie('user_session=wBDJ5-apskjfjkas124192--e5; path=/; expires=Tue, 06 Nov 2018 12:57:11 -0000; secure; HttpOnly; SameSite=Lax; Max-Age=100', TEST_URL);50 expect(cookie).not.toBeNull();51 expect(cookie!.name).toBe('user_session');52 expect(cookie!.value).toBe('wBDJ5-apskjfjkas124192--e5');53 expect(cookie!.url).toBe(TEST_URL);54 expect(cookie!.domain).toBe('test.com');55 });56 it('parses cookie with path', () => {57 const cookie = CookieUtils.parseSetCookie(58 'sample-key=sample-value; path=/',59 TEST_URL,60 );61 expect(cookie!.name).toBe('sample-key');62 expect(cookie!.value).toBe('sample-value');63 expect(cookie!.path).toBe('/');64 const cookie2 = CookieUtils.parseSetCookie(65 'sample-key=sample-value; path=/login',66 TEST_URL,67 );68 expect(cookie2!.name).toBe('sample-key');69 expect(cookie2!.value).toBe('sample-value');70 expect(cookie2!.path).toBe('/login');71 });72 it('checks parse invalid', () => {73 let cookie = CookieUtils.parseSetCookie('', TEST_URL);74 expect(cookie).toBeNull();75 cookie = CookieUtils.parseSetCookie('empty', TEST_URL);76 expect(cookie).not.toBeNull();77 expect(cookie!.name).toBe('empty');78 expect(cookie!.value).toBe('');79 });80});81describe('Cookie utils - parsing cookies', () => {82 it('checks parse simple', () => {83 const cookies = CookieUtils.parseCookies('first_name=first_value;skip;second_name=second_value;', TEST_URL);84 expect(cookies).toHaveLength(2);85 expect(cookies[0].name).toBe('first_name');86 expect(cookies[0]!.value).toBe('first_value');87 expect(cookies[0].url).toBe(TEST_URL);88 expect(cookies[0].domain).toBe('test.com');89 });90 it('checks parse secure', () => {91 // eslint-disable-next-line max-len92 const cookies = CookieUtils.parseCookies('__Secure-first_name=first_value;skip;__Host-second_name=second_value;', TEST_URL);93 expect(cookies).toHaveLength(2);94 expect(cookies[0].name).toBe('__Secure-first_name');95 expect(cookies[0]!.value).toBe('first_value');96 expect(cookies[1]!.secure).toBe(true);97 expect(cookies[0].url).toBe(TEST_URL);98 expect(cookies[0].domain).toBe('test.com');99 });100 it('checks parse invalid', () => {101 const cookies = CookieUtils.parseCookies('', TEST_URL);102 expect(cookies).toHaveLength(0);103 });104});105describe('Cookie utils - update max age', () => {106 let cookie: ParsedCookie;107 beforeEach(() => {108 cookie = new ParsedCookie('test', 'test', TEST_URL);109 });110 it('checks update - max age', () => {111 cookie.maxAge = undefined;112 cookie.expires = undefined;113 expect(CookieUtils.updateCookieMaxAge(cookie, 1)).toBeTruthy();114 expect(cookie.maxAge).toBe(1);115 expect(cookie.expires).toBeDefined();116 });117 it('checks add - max age', () => {118 cookie.maxAge = 2;119 cookie.expires = undefined;120 expect(CookieUtils.updateCookieMaxAge(cookie, 1)).toBeTruthy();121 expect(cookie.maxAge).toBe(1);122 expect(cookie.expires).toBeDefined();123 });124 it('checks no update - max age', () => {125 cookie.maxAge = 1;126 cookie.expires = undefined;127 expect(CookieUtils.updateCookieMaxAge(cookie, 2)).toBeFalsy();128 expect(cookie.maxAge).toBe(1);129 expect(cookie.expires).not.toBeDefined();130 });131 it('checks add - expires', () => {132 cookie.maxAge = undefined;133 const date = new Date(new Date().getTime() + 5 * 1000);134 cookie.expires = date;135 expect(CookieUtils.updateCookieMaxAge(cookie, 2)).toBeTruthy();136 expect(cookie.maxAge).toBe(2);137 expect(cookie.expires).toBeDefined();138 expect(cookie.expires).not.toBe(date);139 });140 it('checks no update - expires', () => {141 cookie.maxAge = undefined;142 const date = new Date();143 cookie.expires = date;144 expect(CookieUtils.updateCookieMaxAge(cookie, 2)).toBeFalsy();145 expect(cookie.maxAge).not.toBeDefined();146 expect(cookie.expires).toBeDefined();147 expect(cookie.expires).toBe(date);148 });149});150describe('Cookie utils - serialize cookie', () => {151 it('throws error on invalid cookie', () => {152 const cookie = {153 name: 'привет',154 value: 'я_кука',155 };156 expect(() => {157 CookieUtils.serializeCookie(cookie as ParsedCookie);158 }).toThrow(TypeError);159 });160 it('serializes simple cookie', () => {161 const cookie = {162 name: '_octo',163 value: 'GH1.1.635223982.1507661197',164 };165 const setCookieValue = CookieUtils.serializeCookie(cookie as ParsedCookie);166 expect(setCookieValue).toBe('_octo=GH1.1.635223982.1507661197');167 });168 it('serializes complicated cookie', () => {169 const cookie = {170 name: '_octo',171 value: 'GH1.1.635223982.1507661197',172 path: '/',173 expires: new Date('Tue, 23 Oct 2018 13:40:11 -0000'),174 secure: true,175 httpOnly: true,176 };177 const setCookieValue = CookieUtils.serializeCookie(cookie as ParsedCookie);178 expect(setCookieValue)179 .toBe('_octo=GH1.1.635223982.1507661197; Path=/; Expires=Tue, 23 Oct 2018 13:40:11 GMT; HttpOnly; Secure');180 });...

Full Screen

Full Screen

test_utils__mock_requests.py

Source:test_utils__mock_requests.py Github

copy

Full Screen

1# coding=utf-82from __future__ import unicode_literals3import requests4from requests.exceptions import HTTPError5from django_app.test import PyW4CTestCase6from utils.mock_requests import patch_requests, patch_requests_decorator7class UtilsMockRequestsTest(PyW4CTestCase):8 requests_mock_dec_test_url = "http://testing.work4labs.com"9 def test_base_case(self):10 # Check that the mock behaves when used properly11 test_url = "http://test.work4labs.com"12 fail_test_url = "http://kaboom.work4labs.com"13 mapping = {14 test_url: {15 'response': 'Nothingness',16 'http_code': 20017 },18 fail_test_url: {19 'response': 'Nope',20 'http_code': 50021 }22 }23 with patch_requests(mapping) as m_requests:24 # All good, take 125 resp = requests.post(test_url)26 self.assertEqual(m_requests['post'].call_count, 1)27 self.assertEqual(m_requests['post'].call_args[0][0], test_url)28 self.assertEqual(resp.url, test_url)29 self.assertEqual(resp.status_code, 200)30 self.assertIn('Nothingness', resp.text)31 # All good, take 232 resp = requests.get(test_url)33 self.assertEqual(m_requests['get'].call_count, 1)34 self.assertEqual(m_requests['get'].call_args[0][0], test_url)35 self.assertEqual(resp.url, test_url)36 self.assertEqual(resp.status_code, 200)37 self.assertIn('Nothingness', resp.text)38 # Uh oh39 resp = requests.get(fail_test_url)40 self.assertEqual(m_requests['get'].call_count, 2)41 self.assertEqual(m_requests['get'].call_args[0][0], fail_test_url)42 self.assertEqual(resp.url, fail_test_url)43 self.assertEqual(resp.status_code, 500)44 self.assertIn('Nope', resp.text)45 with self.assertRaises(HTTPError):46 resp.raise_for_status() # The mock behaves like a proper requests' Response47 @patch_requests_decorator({requests_mock_dec_test_url: {'response': 'Bah, humbug'}})48 def test_as_decorator(self):49 # Check that the mock behaves too when used properly as a decorator50 resp = requests.post(self.requests_mock_dec_test_url)51 self.assertEqual(resp.url, self.requests_mock_dec_test_url)52 self.assertEqual(resp.status_code, 200)53 self.assertIn('Bah', resp.text)54 def test_empty_mapping(self):55 # An empty mapping does not crash − but using it will fail56 mapping = {}57 with patch_requests(mapping):58 with self.assertRaises(Exception): # "called with unexpected URL…"59 requests.get("https://whatever.work4labs.com")60 def test_no_mapping_no_domains(self):61 with self.assertRaises(ValueError):62 with patch_requests():63 pass64 def test_specific_domain(self):65 with patch_requests(allowed_domains=["work4labs.com"], allowed_methods=["get"]):66 resp = requests.get("https://app.work4labs.com")67 self.assertEqual(resp.status_code, 200)68 def test_custom_headers_and_json(self):69 # B. Custom headers and json70 test_url = "https://whatever.work4labs.com"71 headers = {"x-api-key": 'Blablabla'}72 mapping = {73 test_url: {74 'headers': headers,75 'json': True,76 'response': ['Nothingness']77 }78 }79 with patch_requests(mapping) as m_requests:80 resp = requests.post(test_url)81 self.assertEqual(m_requests['post'].call_count, 1)82 self.assertEqual(m_requests['post'].call_args[0][0], test_url)83 self.assertEqual(resp.url, test_url)84 self.assertEqual(resp.headers, headers)85 self.assertEqual(resp.status_code, 200)86 self.assertEqual('["Nothingness"]', resp.text)87 def test_request_method(self):88 # Using requests.request directly also work (kind of an edge case for coverage)89 test_url = "http://test.work4labs.com"90 mapping = {91 test_url: {92 'response': 'Nothingness',93 'json': False,94 'http_code': 200,95 }96 }97 with patch_requests(mapping) as m_requests:98 resp = requests.request('GET', test_url)99 self.assertEqual(m_requests['request'].call_count, 1)100 self.assertEqual(m_requests['request'].call_args[0][0], 'GET')101 self.assertEqual(m_requests['request'].call_args[0][1], test_url)102 self.assertEqual(resp.url, test_url)103 self.assertEqual(resp.status_code, 200)104 self.assertIn('Nothingness', resp.text)105 def test_stream_response(self):106 # Using requests.request directly also work (kind of an edge case for coverage)107 test_url = "http://test.work4labs.com"108 mapping = {109 test_url: {110 'response': 'Nothingness',111 'json': False,112 'stream': True,113 'http_code': 200,114 }115 }116 with patch_requests(mapping) as m_requests:117 resp = requests.request('GET', test_url, stream=True)118 self.assertEqual(m_requests['request'].call_count, 1)119 self.assertEqual(m_requests['request'].call_args[0][0], 'GET')120 self.assertEqual(m_requests['request'].call_args[0][1], test_url)121 self.assertEqual(resp.url, test_url)122 self.assertEqual(resp.status_code, 200)...

Full Screen

Full Screen

testNyComments.py

Source:testNyComments.py Github

copy

Full Screen

1import transaction23from Products.Naaya.tests.NaayaFunctionalTestCase import NaayaFunctionalTestCase4from Products.Naaya.NyFolder import addNyFolder5from naaya.content.url.url_item import addNyURL6from Products.NaayaBase.NyComments import NyComment78def physical_path(obj):9 return '/'.join(obj.getPhysicalPath())1011class NyCommentsTestCase(NaayaFunctionalTestCase):12 def afterSetUp(self):13 addNyFolder(self.portal, 'folder', contributor='admin', submission=1)14 addNyURL(self.portal.folder, id='test_url', title='test url')15 transaction.commit()1617 def catalog_search(self, meta_type, **kwargs):18 catalog = self.portal.getCatalogTool()19 brains = catalog(meta_type=meta_type, **kwargs)20 return [b.getObject() for b in brains]2122 def test_comments_container(self):23 self.assertFalse(hasattr(self.portal.folder.test_url, '.comments'))2425 def test_add_comment(self):26 self.portal.folder.test_url._comment_add(body='test comment')27 container = self.portal.folder.test_url._get_comments_container()28 self.assertEqual(len(container.objectValues()), 1)29 self.assertEqual(container.objectValues()[0].body, 'test comment')3031 def test_del_comment(self):32 comment = self.portal.folder.test_url._comment_add(body='test comment')33 self.portal.folder.test_url._comment_del(comment.id)34 container = self.portal.folder.test_url._get_comments_container()35 self.assertEqual(len(container.objectValues()), 0)3637 def test_catalog_comment(self):38 self.assertEqual(len(self.catalog_search(NyComment.meta_type)), 0)3940 comment = self.portal.folder.test_url._comment_add(body='test comment')41 self.assertEqual(len(self.catalog_search(NyComment.meta_type)), 1)4243 self.portal.folder.test_url._comment_del(comment.id)44 self.assertEqual(len(self.catalog_search(NyComment.meta_type)), 0)4546 def test_catalog_delete_commented_object(self):47 self.assertEqual(len(self.catalog_search(NyComment.meta_type)), 0)4849 comment = self.portal.folder.test_url._comment_add(body='test comment')50 self.assertEqual(len(self.catalog_search(NyComment.meta_type)), 1)5152 self.portal.folder.manage_delObjects(['test_url'])53 self.assertEqual(len(self.catalog_search(NyComment.meta_type)), 0)5455 def test_catalog_copy_commented_object(self):56 self.login()57 self.assertEqual(len(self.catalog_search(NyComment.meta_type)), 0)5859 comment = self.portal.folder.test_url._comment_add(body='test comment')60 self.assertEqual(len(self.catalog_search(NyComment.meta_type,61 path = physical_path(self.portal.folder))), 1)6263 addNyFolder(self.portal, 'other_folder', contributor='admin', submission=1)64 clipboard = self.portal.folder.manage_copyObjects(['test_url'])65 self.portal.other_folder.manage_pasteObjects(clipboard)6667 self.assertEqual(len(self.catalog_search(NyComment.meta_type,68 path = physical_path(self.portal.other_folder))), 1)6970 self.logout()7172 def test_catalog_cut_commented_object(self):73 self.login()74 addNyFolder(self.portal, 'other_folder', contributor='admin', submission=1)7576 self.assertEqual(len(self.catalog_search(NyComment.meta_type)), 0)7778 comment = self.portal.folder.test_url._comment_add(body='test comment')79 self.assertEqual(len(self.catalog_search(NyComment.meta_type,80 path = physical_path(self.portal.folder))), 1)8182 clipboard = self.portal.folder.manage_cutObjects(['test_url'])83 self.portal.other_folder.manage_pasteObjects(clipboard)8485 self.assertEqual(len(self.catalog_search(NyComment.meta_type,86 path = physical_path(self.portal.folder))), 0)8788 self.assertEqual(len(self.catalog_search(NyComment.meta_type,89 path = physical_path(self.portal.other_folder))), 1)9091 self.logout()9293 def test_get_comments(self):94 first_comment = self.portal.folder.test_url._comment_add(body='test comment', 95 releasedate='2/10/2010')96 second_comment = self.portal.folder.test_url._comment_add(body='test comment',97 releasedate='1/10/2010')98 self.assertEqual(self.portal.folder.test_url.count_comments(), 2)99 self.assertEqual(self.portal.folder.test_url.get_comments_list()[0].releasedate, ...

Full Screen

Full Screen

test_cloaker.py

Source:test_cloaker.py Github

copy

Full Screen

1# SPDX-License-Identifier: GPL-3.0-or-later2import unittest3import os4from collections import namedtuple5from resources.lib.cloaker import Cloaker6from resources.lib.settings import localsettings7from resources.lib.logger import Logger8# Dummy Channel Info object9ChannelInfo = namedtuple("ChannelInfo", ["guid", "id"])10class TestCloaker(unittest.TestCase):11 @classmethod12 def setUpClass(cls):13 Logger.create_logger(None, str(cls), min_log_level=0)14 def setUp(self):15 self.cloakSettings = "settings.json"16 self.channel = ChannelInfo(guid="channel.id", id="channel.id.code")17 self.logger = Logger.instance()18 if os.path.isfile(self.cloakSettings):19 os.remove(self.cloakSettings)20 self.store = localsettings.LocalSettings(".", logger=self.logger)21 self.cloaker = Cloaker(channel=self.channel, settings_store=self.store, logger=self.logger)22 def tearDown(self):23 # we need to actively delete the cloaker and store to prevent any issues with reuse24 del self.cloaker25 del self.store26 if os.path.isfile(self.cloakSettings):27 os.remove(self.cloakSettings)28 def test_setting_first_time_cloak(self):29 self.assertTrue(self.cloaker.cloak("test-url"))30 self.assertFalse(self.cloaker.cloak("test-url2"))31 def test_is_cloaked(self):32 test_url = "test_url"33 self.assertFalse(self.cloaker.is_cloaked(test_url))34 self.cloaker.cloak(test_url)35 self.assertTrue(self.cloaker.is_cloaked(test_url))36 def test_is_already_cloaked(self):37 test_url = "test_url"38 self.assertTrue(self.cloaker.cloak(test_url))39 self.assertFalse(self.cloaker.cloak(test_url))40 def test_uncloak(self):41 test_url = "test_url"42 self.assertTrue(self.cloaker.cloak(test_url))43 self.assertTrue(self.cloaker.is_cloaked(test_url))44 self.cloaker.un_cloak(test_url)45 self.cloaker.un_cloak("not in there")...

Full Screen

Full Screen

test_helper_functions.py

Source:test_helper_functions.py Github

copy

Full Screen

1from tethys_sdk.testing import TethysTestCase2import tethys_services.models as service_model3from django.core.exceptions import ValidationError4class HelperFunctionTests(TethysTestCase):5 def set_up(self):6 pass7 def tear_down(self):8 pass9 def test_validate_url_valid(self):10 test_url = 'http://'11 raised = False12 try:13 service_model.validate_url(test_url)14 except ValidationError:15 raised = True16 self.assertFalse(raised)17 def test_validate_url(self):18 test_url = 'test_url'19 self.assertRaises(ValidationError, service_model.validate_url, test_url)20 def test_validate_dataset_service_endpoint(self):21 test_url = 'http://test_url'22 self.assertRaises(ValidationError, service_model.validate_dataset_service_endpoint, test_url)23 def test_validate_spatial_dataset_service_endpoint(self):24 test_url = 'test_url' # Not HTTP25 self.assertRaises(ValidationError, service_model.validate_spatial_dataset_service_endpoint, test_url)26 def test_validate_wps_service_endpoint(self):27 test_url = 'http://test_url'28 self.assertRaises(ValidationError, service_model.validate_wps_service_endpoint, test_url)29 def test_validate_persistent_store_port(self):30 test_url = '800'...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1 if(err) {2 console.log('Error: ' + err);3 } else {4 console.log('Test ID: ' + data.data.testId);5 }6});7 if(err) {8 console.log('Error: ' + err);9 } else {10 console.log('Test ID: ' + data.data.testId);11 }12});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2exports.test_url = function(url) {3 console.log('testing url: ' + url);4};5var wpt = require('./wpt.js');6module.exports = {7 test_url: function(url) {8 console.log('testing url: ' + url);9 }10};11var wpt = require('./wpt.js');12module.exports = {13 test_url: function(url) {14 console.log('testing url: ' + url);15 }16};

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful