How to use port method in testcontainers-python

Best Python code snippet using testcontainers-python_python

port.in.jsx

Source:port.in.jsx Github

copy

Full Screen

1import AppConfig from 'AppConfig';2import {3 FORMAT_INTERNATIONAL_SWEDISH_MOBILE_REGEX,4 FORMAT_LOCAL_SWEDISH_MOBILE_REGEX5} from '@selfcare/core/constants/subscriber';6import { addBusinessDays, subtractBusinessDays, today } from '@selfcare/core/helpers/date.helper';7import { CODES } from '@selfcare/core/redux/metadata/codes/codes.constants';8import { OFFERING_STATUS } from '@selfcare/core/redux/subscriberOfferings/subscriber.offering.constants';9import { SUPPORT_REQUEST } from '@selfcare/core/redux/supportRequest/support.request.constants';10/* eslint-disable import/no-duplicates */11import format from 'date-fns/format';12import isBefore from 'date-fns/is_before';13import addDays from 'date-fns/add_days';14import differenceInDays from 'date-fns/difference_in_days';15/* eslint-enable import/no-duplicates */16import PropTypes from 'prop-types';17import compose from 'ramda/src/compose';18import isEmpty from 'ramda/src/isEmpty';19import path from 'ramda/src/path';20import pathOr from 'ramda/src/pathOr';21import React, { useEffect, useState } from 'react';22import { withI18n } from 'react-i18next';23import { withRouter } from 'react-router';24import FilledButton from 'selfcare-ui/src/components/button/filled.button';25import OutlineButton from 'selfcare-ui/src/components/button/outline.button';26import Heading from 'selfcare-ui/src/components/heading/heading';27import Input from 'selfcare-ui/src/components/input/input';28import InputField from 'selfcare-ui/src/components/inputField/input.field';29import Link from 'selfcare-ui/src/components/link/link';30import LoadingIndicator from 'selfcare-ui/src/components/loadingIndicator/loading.indicator';31import Notice from 'selfcare-ui/src/components/notice/notice';32import Paragraph from 'selfcare-ui/src/components/paragraph/paragraph';33import { DECISION_TYPE } from '../../../../constants/order.constants';34import LocaleKeys from '../../../../locales/keys';35import DatePicker from '../../../datePicker/date.picker';36import PageContent from '../../../pageContent/page.content';37import { SetupApiDataFromForm } from '../../../supportRequest/support.request.helpers';38import { getContextPageObject } from '../../../../helpers/inaccount.help.helpers';39import { navigateToProducts } from '../manage.product.helper';40import '../manage.product.scss';41import { PortInConstants, PORTIN_VALUES } from './port.in.constants';42const PortIn = ({ cancelPortInRequest, createSupportRequest, searchSupportRequest, history, isHandlingProductAction, isPortInNumberInvalid,43 portInNumberAdditionalPropertyValueId, portInCurrentMSISDNField, portInDateField, portInIsLoading, portInNumber, portInPortToMSISDNField, portInSsn, productIdentifier,44 recentlyClosedPortInRequest, recentlyNewOrOpenPortInRequest, retrieveCodes, retrieveProductMetadata, selectedProduct,45 subscriberSSN, t, updateAttributeValue, updateCustomPortInNumber, updatePortInRequest,46 validatedPortInDateField, offeringContextsByInstanceId, activeOfferInstanceId, validatePortInDate, setContextPageData }) => {47 const [currentPortInFlow, setCurrentPortInFlow] = useState(null);48 const [portInNumberValue, setPortInNumberValue] = useState(portInNumber.value || '');49 const [portInNumberClosed, setPortInNumberValueClosed] = useState('');50 const [portInDateFromCase, setPortInDateFromCase] = useState(addBusinessDays(today(), PORTIN_VALUES.DEFAULT));51 const [portInDate, setPortInDate] = useState(addBusinessDays(today(), PORTIN_VALUES.DEFAULT));52 const [initialPortInUpdateDate, setInitialPortInUpdateDate] = useState(addBusinessDays(today(), PORTIN_VALUES.DEFAULT));53 const [portInWasUpdated, setPortInWasUpdated] = useState(false);54 const [isPortInDisabled, setIsPortInDisabled] = useState(false);55 const hasOpenPortInRequest = recentlyNewOrOpenPortInRequest && !recentlyClosedPortInRequest;56 const mobileNumberPortType = AppConfig.MOBILE_NUMBER_PORT;57 useEffect(() => {58 if (productIdentifier && !isEmpty(offeringContextsByInstanceId) && !isEmpty(offeringContextsByInstanceId[activeOfferInstanceId])) {59 retrieveProductMetadata(productIdentifier);60 }61 }, [productIdentifier, retrieveProductMetadata, offeringContextsByInstanceId, activeOfferInstanceId]);62 useEffect(() => {63 setContextPageData(getContextPageObject(3, 'portin'));64 }, [setContextPageData]);65 useEffect(() => {66 retrieveCodes(CODES.Regex);67 retrieveCodes(CODES.FormControlType);68 }, [retrieveCodes]);69 useEffect(() => {70 const isPortInWithinOneBusinessDay = !isBefore(addBusinessDays(today(), 1), portInDate);71 const portInDisabled = selectedProduct.status === OFFERING_STATUS.PENDING_ACTIVE || isPortInWithinOneBusinessDay;72 setIsPortInDisabled(portInDisabled);73 }, [portInDate, selectedProduct.status]);74 useEffect(() => {75 const foundValidatedPortInDateField = pathOr([], ['AdditionalPropertyValues'], recentlyNewOrOpenPortInRequest).filter((obj) => (76 obj.Id === validatedPortInDateField.id));77 const foundValidatedPortInDate = foundValidatedPortInDateField[0] ? foundValidatedPortInDateField[0].Value : '';78 const portInNumberFieldClosed = pathOr([], ['AdditionalPropertyValues'], recentlyClosedPortInRequest).filter((obj) => (79 obj.Id === portInNumberAdditionalPropertyValueId));80 const portInNumberClosed = portInNumberFieldClosed[0] ? portInNumberFieldClosed[0].Value : '';81 portInNumberClosed && setPortInNumberValue('');82 setPortInNumberValueClosed(portInNumberClosed);83 if (hasOpenPortInRequest && foundValidatedPortInDate === '12/30/9999') {84 setCurrentPortInFlow(PortInConstants.PORT_IN_CANCEL_PENDING);85 } else if (hasOpenPortInRequest) {86 setCurrentPortInFlow(PortInConstants.PORT_IN_RESPONSE);87 const foundPortInNumberField = recentlyNewOrOpenPortInRequest.AdditionalPropertyValues.filter((obj) => (88 obj.Id === portInPortToMSISDNField.id));89 const foundPortInDateField = recentlyNewOrOpenPortInRequest.AdditionalPropertyValues.filter((obj) => (90 obj.Id === portInDateField.id));91 const foundPortInDateFieldUpdate = recentlyNewOrOpenPortInRequest.AdditionalPropertyValues.filter((obj) => (92 obj.Id === AppConfig.PORT_IN_DATE_ATTRIBUTE_ID.toString()));93 const foundPortInNumberValue = foundPortInNumberField[0] ? foundPortInNumberField[0].Value : '';94 const foundPortInDateValue = foundPortInDateField[0] ? foundPortInDateField[0].Value : '';95 const foundPortInDateValueUpdate = foundPortInDateFieldUpdate[0] ? foundPortInDateFieldUpdate[0].Value : '';96 setPortInNumberValue(foundPortInNumberValue.replace(FORMAT_LOCAL_SWEDISH_MOBILE_REGEX.pattern, FORMAT_LOCAL_SWEDISH_MOBILE_REGEX.replace),);97 setPortInDateFromCase(foundPortInDateValue);98 const endDatepickerDate = addDays(new Date(today()), PORTIN_VALUES.MAX + PORTIN_VALUES.MIN);99 const daysToAdd = differenceInDays(endDatepickerDate, addBusinessDays(foundPortInDateValueUpdate, 1)) > 0 ? 1 : -1;100 setInitialPortInUpdateDate(addBusinessDays(foundPortInDateValueUpdate, daysToAdd));101 setPortInDate(foundPortInDateValue);102 } else {103 setCurrentPortInFlow(PortInConstants.ENTER_NUMBER);104 }105 }, [hasOpenPortInRequest, portInDateField.id, portInPortToMSISDNField.id, recentlyNewOrOpenPortInRequest, recentlyClosedPortInRequest, validatedPortInDateField.id, portInNumberAdditionalPropertyValueId]);106 const handleUpdatePortInNumber = (event) => {107 const { target: { value } } = event;108 portInNumberClosed ?109 setPortInNumberValueClosed(value):110 setPortInNumberValue(value);111 updateCustomPortInNumber(value);112 };113 const handleValidatePortInNumber = (event) => {114 updateCustomPortInNumber(event.target.value);115 };116 const submitPortIn = async () => {117 const portinNumberToSend = portInNumberClosed || portInNumberValue;118 updateAttributeValue(DECISION_TYPE.QUANTITY, portInNumber.optionId, portInNumber.id, portInNumberValue, true, portInNumber.displayOrder);119 const values = {120 [SUPPORT_REQUEST.DESCRIPTION]: selectedProduct.offeringInstanceId,121 [portInCurrentMSISDNField.id]: selectedProduct.serviceIdentifier,122 [portInPortToMSISDNField.id]: portinNumberToSend.replace(FORMAT_INTERNATIONAL_SWEDISH_MOBILE_REGEX.pattern, FORMAT_INTERNATIONAL_SWEDISH_MOBILE_REGEX.replace),123 [portInSsn.id]: subscriberSSN,124 [portInDateField.id]: format(portInDate, 'YYYY-MM-DD')125 };126 const productInventoryItem = path(['inventoryItem', 'Id'], selectedProduct);127 if (productInventoryItem) {128 values[SUPPORT_REQUEST.INVENTORY_ITEM] = productInventoryItem;129 }130 const portInRequestData = SetupApiDataFromForm(values, mobileNumberPortType, mobileNumberPortType);131 await createSupportRequest(portInRequestData);132 setCurrentPortInFlow(PortInConstants.PORT_IN_RESPONSE);133 };134 const cancelPortIn = async () => {135 await cancelPortInRequest(recentlyNewOrOpenPortInRequest.Id.Value, selectedProduct.offeringInstanceId);136 setCurrentPortInFlow(PortInConstants.PORT_IN_CANCEL_PENDING);137 };138 const updatePortIn = async () => {139 await updateAttributeValue(DECISION_TYPE.QUANTITY, portInNumber.optionId, portInNumber.id, portInNumberValue, true, portInNumber.displayOrder);140 await updatePortInRequest(recentlyNewOrOpenPortInRequest.Id.Value, selectedProduct.offeringInstanceId, portInDate);141 setPortInDateFromCase(format(portInDate, 'YYYY-MM-DD'));142 setPortInWasUpdated(true);143 setCurrentPortInFlow(PortInConstants.PORT_IN_RESPONSE);144 };145 useEffect(() => {146 searchSupportRequest();147 }, [searchSupportRequest]);148 const setupViewFromFlow = () => {149 switch (currentPortInFlow) {150 case PortInConstants.ENTER_NUMBER:151 return {152 heading: t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER),153 content: (154 <>155 {(recentlyClosedPortInRequest && !recentlyClosedPortInRequest.successful) && (156 <Notice157 className="c-manage-product__notice"158 type="error"159 heading={160 t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_RESPONSE_HEADER, {161 portFrom: portInNumberClosed || portInNumberValue162 })163 }164 >165 <Paragraph>166 {t(`${LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_RESPONSE_PREFIX}${recentlyClosedPortInRequest.messageCode}`)}167 </Paragraph>168 </Notice>169 )}170 {(recentlyClosedPortInRequest && recentlyClosedPortInRequest.successful && (recentlyClosedPortInRequest.responseMessage !== 'CANCELLED')) ? (171 <Notice172 className="c-manage-product__notice"173 type="success"174 heading={175 t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_RESPONSE_HEADER, {176 portFrom: portInNumber.value177 })178 }179 >180 <Paragraph>181 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_SUCCESS_BODY)}182 </Paragraph>183 </Notice>184 ) : (185 <Paragraph className="c-manage-product__description">186 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_DESCRIPTION)}187 </Paragraph>188 )}189 <InputField190 error={isPortInNumberInvalid ? t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_ERROR) : null}191 labelText={t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_CHOOSE)}192 info={t(LocaleKeys.SHOP.ENTER_PORT_IN_HINT)}193 required194 input={(195 <Input196 id="port-in"197 type="tel"198 onChange={handleUpdatePortInNumber}199 onBlur={handleValidatePortInNumber}200 size="full"201 value={portInNumberClosed || portInNumberValue}202 />203 )}204 />205 <DatePicker206 id="portInDate"207 initialValue={new Date(portInDate)}208 labelText={t(LocaleKeys.PRODUCTS.SETTINGS.PORT_DATE_CHOOSE)}209 onDayChange={(day) => {210 setPortInDate(day);211 }}212 maxDays={PORTIN_VALUES.MAX}213 minDays={PORTIN_VALUES.MIN}214 size="large"215 />216 <div className="c-manage-product__button-actions">217 <OutlineButton218 className="c-manage-product__primary-action c-button-double"219 onClick={() => navigateToProducts(history)}220 >221 {t(LocaleKeys.CANCEL)}222 </OutlineButton>223 <FilledButton224 className="c-manage-product__primary-action c-button-double"225 disabled={isPortInNumberInvalid}226 onClick={submitPortIn}227 >228 {t(LocaleKeys.SUBMIT)}229 </FilledButton>230 </div>231 </>232 )233 };234 case PortInConstants.PORT_IN_UPDATE:235 return {236 heading: t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER),237 content: (238 <>239 <Paragraph className="c-manage-product__description">240 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_UPDATE_PROMPT, {241 portInDate: portInDateFromCase242 })}243 </Paragraph>244 <div className="c-manage-product__section-data">245 <div>246 <Heading className="c-manage-product__section-header" category="minor" tone="normal">{t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_PENDING_NUMBER_LABEL)}</Heading>247 <Heading category="minor" tone="normal">{portInNumberValue}</Heading>248 </div>249 </div>250 <div className="c-manage-product__date-input">251 <DatePicker252 id="portInDate"253 initialValue={new Date(initialPortInUpdateDate)}254 isPortInUpdateDate={subtractBusinessDays(initialPortInUpdateDate, 1)}255 labelText={t(LocaleKeys.PRODUCTS.SETTINGS.PORT_DATE_CHOOSE)}256 onDayChange={(day) => {257 setPortInDate(day);258 }}259 maxDays={PORTIN_VALUES.MAX}260 minDays={PORTIN_VALUES.MIN}261 size="large"262 />263 </div>264 <div className="c-manage-product__button-actions">265 <OutlineButton266 className="c-manage-product__secondary-action c-button-double"267 onClick={() => setCurrentPortInFlow(PortInConstants.PORT_IN_RESPONSE)}268 >269 {t(LocaleKeys.CANCEL)}270 </OutlineButton>271 <FilledButton272 className="c-manage-product__primary-action c-button-double"273 disabled={isPortInNumberInvalid}274 onClick={updatePortIn}275 >276 {t(LocaleKeys.SUBMIT)}277 </FilledButton>278 </div>279 <div className="c-manage-product__update-return">280 <Link281 className="c-manage-product__secondary-action"282 onClick={() => setCurrentPortInFlow(PortInConstants.PORT_IN_CANCEL)}283 >284 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_PENDING_CANCEL)}285 </Link>286 </div>287 </>288 )289 };290 case PortInConstants.PORT_IN_RESPONSE:291 return {292 heading: t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER),293 content: (294 <>295 {portInWasUpdated && (296 <Notice297 className="c-manage-product__port-in-disclaimer"298 type="success"299 heading={t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_UPDATE_SUCCESS_NOTIFICATION)}300 />301 )}302 <Paragraph className="c-manage-product__pending-description">303 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_PENDING)}304 </Paragraph>305 <div className="c-manage-product__section-data">306 <div className="c-manage-product__section-data-container">307 <Heading className="c-manage-product__section-header" category="minor" tone="normal">{t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_PENDING_NUMBER_LABEL)}</Heading>308 <Heading category="minor" tone="normal">{portInNumberValue}</Heading>309 </div>310 <div className="c-manage-product__section-data-container">311 <Heading className="c-manage-product__section-header" category="minor" tone="normal">{t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_PENDING_DATE_LABEL)}</Heading>312 <Heading category="minor" tone="normal">{format(portInDateFromCase, 'YYYY-MM-DD')}</Heading>313 </div>314 </div>315 {(!isPortInDisabled && validatePortInDate) && (316 <div className="c-manage-product__button-actions pending-port-in">317 <div className="action">318 <FilledButton319 className="c-manage-product__primary-action"320 onClick={() => setCurrentPortInFlow(PortInConstants.PORT_IN_UPDATE)}321 >322 {t(LocaleKeys.PRODUCTS.SETTINGS.CHANGE)}323 </FilledButton>324 </div>325 <div className="action">326 <Link327 onClick={() => setCurrentPortInFlow(PortInConstants.PORT_IN_CANCEL)}328 >329 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_PENDING_CANCEL)}330 </Link>331 </div>332 </div>333 )}334 </>335 )336 };337 case PortInConstants.PORT_IN_CANCEL:338 return {339 heading: t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER),340 content: (341 <>342 <Paragraph className="c-manage-product__pending-description">343 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_CANCEL_HEADER)}344 </Paragraph>345 <div className="c-manage-product__button-actions">346 <OutlineButton347 className="c-manage-product__primary-action c-button-double"348 onClick={() => setCurrentPortInFlow(PortInConstants.PORT_IN_RESPONSE)}349 >350 {t(LocaleKeys.CANCEL)}351 </OutlineButton>352 <FilledButton353 className="c-manage-product__primary-action c-button-double"354 disabled={isPortInDisabled}355 onClick={cancelPortIn}356 >357 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_CANCEL_CONFIRM_LABEL)}358 </FilledButton>359 </div>360 </>361 )362 };363 case PortInConstants.PORT_IN_CANCEL_PENDING:364 return {365 heading: t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER),366 content: (367 <>368 <Paragraph className="c-manage-product__pending-description">369 {t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER_CANCEL_PENDING)}370 </Paragraph>371 <div className="c-manage-product__button-actions">372 <FilledButton373 className="c-manage-product__primary-action c-button-double"374 onClick={() => navigateToProducts(history)}375 >376 {t(LocaleKeys.BACK)}377 </FilledButton>378 </div>379 </>380 )381 };382 default:383 return {384 heading: t(LocaleKeys.PRODUCTS.SETTINGS.PORT_NUMBER),385 content: (386 <div>387 <LoadingIndicator isLoading />388 </div>389 )390 };391 }392 };393 const view = setupViewFromFlow();394 return (395 <PageContent>396 <div className="c-manage-product c-loading-indicator-containment">397 <LoadingIndicator isLoading={isHandlingProductAction || portInIsLoading} />398 <Heading category="brand" tone="normal">399 {view.heading}400 </Heading>401 {view.content}402 </div>403 </PageContent>404 );405};406PortIn.displayName = 'PortIn';407PortIn.propTypes = {408 /** Action to cancel the port-in request. */409 cancelPortInRequest: PropTypes.func.isRequired,410 /** Function to be called on submission of the support request form to create the request */411 createSupportRequest: PropTypes.func,412 /** The action to trigger when populating the list for support requests */413 searchSupportRequest: PropTypes.func.isRequired,414 /** [[IgnoreDoc]] History instance provided by react-router */415 history: PropTypes.object.isRequired,416 /** Flag for when a product action is being utilized and the loading indicator should be triggered. */417 isHandlingProductAction: PropTypes.bool.isRequired,418 /** Whether the port in number is invalid or not. */419 isPortInNumberInvalid: PropTypes.bool,420 /** Current MSISDN Field information for creation of new port in case. */421 portInCurrentMSISDNField: PropTypes.shape({422 id: PropTypes.string423 }),424 /** Port in Date Field */425 portInDateField: PropTypes.object,426 /** Port in values after an port in support request is closed */427 portInNumberAdditionalPropertyValueId: PropTypes.string,428 /** Port in number */429 portInNumber: PropTypes.object,430 /** Whether the port in actions are loading or not. */431 portInIsLoading: PropTypes.bool.isRequired,432 /** New MSISDN Field information for creation of new port in case. */433 portInPortToMSISDNField: PropTypes.object,434 /** Port in SSN */435 portInSsn: PropTypes.object,436 /** Product Identifier */437 productIdentifier: PropTypes.number,438 /** Recent Closed Port In Request */439 recentlyClosedPortInRequest: PropTypes.shape({440 /** Response message for closed port in request */441 responseMessage: PropTypes.string,442 /** Message code for closed port in request */443 messageCode: PropTypes.string,444 /** successful flag for closed port in request */445 successful: PropTypes.bool446 }),447 /** Recent Port in Request */448 recentlyNewOrOpenPortInRequest: PropTypes.shape({449 Id: PropTypes.object,450 AdditionalPropertyValues: PropTypes.arrayOf(PropTypes.object)451 }),452 /** Action to fetch metadata */453 retrieveCodes: PropTypes.func.isRequired,454 /** Retrieve Product Metadata */455 retrieveProductMetadata: PropTypes.func.isRequired,456 /** Selected product to perform actions against. */457 selectedProduct: PropTypes.shape({458 /** Offering Id */459 offeringId: PropTypes.string,460 /** Offering Instance Id */461 offeringInstanceId: PropTypes.string,462 /** Display Name */463 displayName: PropTypes.string,464 /** Flag to determine if a use can opt out of the renewal at the end of the billing cycle. */465 canOptOutOnRenew: PropTypes.bool,466 /** Currency Code */467 currencyCode: PropTypes.string,468 /** Billing object on the offer */469 billing: PropTypes.shape({470 /** Next charge date for the offer */471 nextChargeDate: PropTypes.string472 }),473 /** Bool for product having first usage */474 hasFirstUsage: PropTypes.bool,475 /** The selected option Id on the primary decision. */476 hasPrimaryOption: PropTypes.string,477 /** Bool for product being broadband */478 isBroadband: PropTypes.bool,479 /** Bool for product being penny play */480 isPennyPlay: PropTypes.bool,481 /** Flag to tell us if the product is wireless */482 isWireless: PropTypes.bool,483 /** Marketing Template object to be used to render upgrade /downgrade */484 marketingTemplate: PropTypes.shape({}),485 /** Options */486 options: PropTypes.array,487 /** Right to Return */488 rightToReturn: PropTypes.bool,489 /** Service Identifier for the product. Also called the phone number. */490 serviceIdentifier: PropTypes.string,491 /** Status of the product */492 status: PropTypes.number,493 intentToPort: PropTypes.bool494 }),495 /** SSN of subscriber */496 subscriberSSN: PropTypes.string.isRequired,497 /** [[IgnoreDoc]] Translate function provided by react-i18next */498 t: PropTypes.func.isRequired,499 /** Function to update the attribute value */500 updateAttributeValue: PropTypes.func.isRequired,501 /** Function to update the custom port in number */502 updateCustomPortInNumber: PropTypes.func.isRequired,503 /** Function to update the port in request. */504 updatePortInRequest: PropTypes.func.isRequired,505 /** Field information for validated port in date. */506 validatedPortInDateField: PropTypes.object,507 /** Validate port in date attribute present inside open support requests */508 validatePortInDate: PropTypes.bool,509 offeringContextsByInstanceId: PropTypes.object,510 activeOfferInstanceId: PropTypes.string,511 /** Action to change ui context page data */512 setContextPageData: PropTypes.func.isRequired513};514export default compose(515 withI18n(),516 withRouter...

Full Screen

Full Screen

port_testcase.py

Source:port_testcase.py Github

copy

Full Screen

...70 os_name = None71 os_version = None72 port_maker = TestWebKitPort73 port_name = None74 def make_port(self, host=None, port_name=None, options=None, os_name=None, os_version=None, **kwargs):75 host = host or MockSystemHost(os_name=(os_name or self.os_name), os_version=(os_version or self.os_version))76 options = options or MockOptions(configuration='Release')77 port_name = port_name or self.port_name78 port_name = self.port_maker.determine_full_port_name(host, options, port_name)79 port = self.port_maker(host, port_name, options=options, **kwargs)80 port._config.build_directory = lambda configuration: '/mock-build'81 return port82 def make_wdiff_available(self, port):83 port._wdiff_available = True84 def test_check_build(self):85 port = self.make_port()86 port._check_file_exists = lambda path, desc: True87 if port._dump_reader:88 port._dump_reader.check_is_functional = lambda: True89 port._options.build = True90 port._check_driver_build_up_to_date = lambda config: True91 port.check_httpd = lambda: True92 oc = OutputCapture()93 try:94 oc.capture_output()95 self.assertEqual(port.check_build(needs_http=True, printer=FakePrinter()),96 test_run_results.OK_EXIT_STATUS)97 finally:98 out, err, logs = oc.restore_output()99 self.assertIn('pretty patches', logs) # We should get a warning about PrettyPatch being missing,100 self.assertNotIn('build requirements', logs) # but not the driver itself.101 port._check_file_exists = lambda path, desc: False102 port._check_driver_build_up_to_date = lambda config: False103 try:104 oc.capture_output()105 self.assertEqual(port.check_build(needs_http=True, printer=FakePrinter()),106 test_run_results.UNEXPECTED_ERROR_EXIT_STATUS)107 finally:108 out, err, logs = oc.restore_output()109 self.assertIn('pretty patches', logs) # And, hereere we should get warnings about both.110 self.assertIn('build requirements', logs)111 def test_default_max_locked_shards(self):112 port = self.make_port()113 port.default_child_processes = lambda: 16114 self.assertEqual(port.default_max_locked_shards(), 4)115 port.default_child_processes = lambda: 2116 self.assertEqual(port.default_max_locked_shards(), 1)117 def test_default_timeout_ms(self):118 self.assertEqual(self.make_port(options=MockOptions(configuration='Release')).default_timeout_ms(), 6000)119 self.assertEqual(self.make_port(options=MockOptions(configuration='Debug')).default_timeout_ms(), 18000)120 def test_default_pixel_tests(self):121 self.assertEqual(self.make_port().default_pixel_tests(), True)122 def test_driver_cmd_line(self):123 port = self.make_port()124 self.assertTrue(len(port.driver_cmd_line()))125 options = MockOptions(additional_drt_flag=['--foo=bar', '--foo=baz'])126 port = self.make_port(options=options)127 cmd_line = port.driver_cmd_line()128 self.assertTrue('--foo=bar' in cmd_line)129 self.assertTrue('--foo=baz' in cmd_line)130 def test_uses_apache(self):131 self.assertTrue(self.make_port().uses_apache())132 def assert_servers_are_down(self, host, ports):133 for port in ports:134 try:135 test_socket = socket.socket()136 test_socket.connect((host, port))137 self.fail()138 except IOError, e:139 self.assertTrue(e.errno in (errno.ECONNREFUSED, errno.ECONNRESET))140 finally:141 test_socket.close()142 def assert_servers_are_up(self, host, ports):143 for port in ports:144 try:145 test_socket = socket.socket()146 test_socket.connect((host, port))147 except IOError, e:148 self.fail('failed to connect to %s:%d' % (host, port))149 finally:150 test_socket.close()151 def test_diff_image__missing_both(self):152 port = self.make_port()153 self.assertEqual(port.diff_image(None, None), (None, None))154 self.assertEqual(port.diff_image(None, ''), (None, None))155 self.assertEqual(port.diff_image('', None), (None, None))156 self.assertEqual(port.diff_image('', ''), (None, None))157 def test_diff_image__missing_actual(self):158 port = self.make_port()159 self.assertEqual(port.diff_image(None, 'foo'), ('foo', None))160 self.assertEqual(port.diff_image('', 'foo'), ('foo', None))161 def test_diff_image__missing_expected(self):162 port = self.make_port()163 self.assertEqual(port.diff_image('foo', None), ('foo', None))164 self.assertEqual(port.diff_image('foo', ''), ('foo', None))165 def test_diff_image(self):166 def _path_to_image_diff():167 return "/path/to/image_diff"168 port = self.make_port()169 port._path_to_image_diff = _path_to_image_diff170 mock_image_diff = "MOCK Image Diff"171 def mock_run_command(args):172 port._filesystem.write_binary_file(args[4], mock_image_diff)173 return 1174 # Images are different.175 port._executive = MockExecutive2(run_command_fn=mock_run_command)176 self.assertEqual(mock_image_diff, port.diff_image("EXPECTED", "ACTUAL")[0])177 # Images are the same.178 port._executive = MockExecutive2(exit_code=0)179 self.assertEqual(None, port.diff_image("EXPECTED", "ACTUAL")[0])180 # There was some error running image_diff.181 port._executive = MockExecutive2(exit_code=2)182 exception_raised = False183 try:184 port.diff_image("EXPECTED", "ACTUAL")185 except ValueError, e:186 exception_raised = True187 self.assertFalse(exception_raised)188 def test_diff_image_crashed(self):189 port = self.make_port()190 port._executive = MockExecutive2(exit_code=2)191 self.assertEqual(port.diff_image("EXPECTED", "ACTUAL"), (None, 'Image diff returned an exit code of 2. See http://crbug.com/278596'))192 def test_check_wdiff(self):193 port = self.make_port()194 port.check_wdiff()195 def test_wdiff_text_fails(self):196 host = MockSystemHost(os_name=self.os_name, os_version=self.os_version)197 host.executive = MockExecutive(should_throw=True)198 port = self.make_port(host=host)199 port._executive = host.executive # AndroidPortTest.make_port sets its own executive, so reset that as well.200 # This should raise a ScriptError that gets caught and turned into the201 # error text, and also mark wdiff as not available.202 self.make_wdiff_available(port)203 self.assertTrue(port.wdiff_available())204 diff_txt = port.wdiff_text("/tmp/foo.html", "/tmp/bar.html")205 self.assertEqual(diff_txt, port._wdiff_error_html)206 self.assertFalse(port.wdiff_available())207 def test_missing_symbol_to_skipped_tests(self):208 # Test that we get the chromium skips and not the webkit default skips209 port = self.make_port()210 skip_dict = port._missing_symbol_to_skipped_tests()211 if port.PORT_HAS_AUDIO_CODECS_BUILT_IN:212 self.assertEqual(skip_dict, {})213 else:214 self.assertTrue('ff_mp3_decoder' in skip_dict)215 self.assertFalse('WebGLShader' in skip_dict)216 def test_test_configuration(self):217 port = self.make_port()218 self.assertTrue(port.test_configuration())219 def test_all_test_configurations(self):220 """Validate the complete set of configurations this port knows about."""221 port = self.make_port()222 self.assertEqual(set(port.all_test_configurations()), set([223 TestConfiguration('snowleopard', 'x86', 'debug'),224 TestConfiguration('snowleopard', 'x86', 'release'),225 TestConfiguration('lion', 'x86', 'debug'),226 TestConfiguration('lion', 'x86', 'release'),227 TestConfiguration('retina', 'x86', 'debug'),228 TestConfiguration('retina', 'x86', 'release'),229 TestConfiguration('mountainlion', 'x86', 'debug'),230 TestConfiguration('mountainlion', 'x86', 'release'),231 TestConfiguration('mavericks', 'x86', 'debug'),232 TestConfiguration('mavericks', 'x86', 'release'),233 TestConfiguration('xp', 'x86', 'debug'),234 TestConfiguration('xp', 'x86', 'release'),235 TestConfiguration('win7', 'x86', 'debug'),236 TestConfiguration('win7', 'x86', 'release'),237 TestConfiguration('lucid', 'x86', 'debug'),238 TestConfiguration('lucid', 'x86', 'release'),239 TestConfiguration('lucid', 'x86_64', 'debug'),240 TestConfiguration('lucid', 'x86_64', 'release'),241 TestConfiguration('icecreamsandwich', 'x86', 'debug'),242 TestConfiguration('icecreamsandwich', 'x86', 'release'),243 ]))244 def test_get_crash_log(self):245 port = self.make_port()246 self.assertEqual(port._get_crash_log(None, None, None, None, newer_than=None),247 (None,248 'crash log for <unknown process name> (pid <unknown>):\n'249 'STDOUT: <empty>\n'250 'STDERR: <empty>\n'))251 self.assertEqual(port._get_crash_log('foo', 1234, 'out bar\nout baz', 'err bar\nerr baz\n', newer_than=None),252 ('err bar\nerr baz\n',253 'crash log for foo (pid 1234):\n'254 'STDOUT: out bar\n'255 'STDOUT: out baz\n'256 'STDERR: err bar\n'257 'STDERR: err baz\n'))258 self.assertEqual(port._get_crash_log('foo', 1234, 'foo\xa6bar', 'foo\xa6bar', newer_than=None),259 ('foo\xa6bar',260 u'crash log for foo (pid 1234):\n'261 u'STDOUT: foo\ufffdbar\n'262 u'STDERR: foo\ufffdbar\n'))263 self.assertEqual(port._get_crash_log('foo', 1234, 'foo\xa6bar', 'foo\xa6bar', newer_than=1.0),264 ('foo\xa6bar',265 u'crash log for foo (pid 1234):\n'266 u'STDOUT: foo\ufffdbar\n'267 u'STDERR: foo\ufffdbar\n'))268 def assert_build_path(self, options, dirs, expected_path):269 port = self.make_port(options=options)270 for directory in dirs:271 port.host.filesystem.maybe_make_directory(directory)272 self.assertEqual(port._build_path(), expected_path)273 def test_expectations_files(self):274 port = self.make_port()275 generic_path = port.path_to_generic_test_expectations_file()276 chromium_overrides_path = port.path_from_chromium_base(277 'webkit', 'tools', 'layout_tests', 'test_expectations.txt')278 never_fix_tests_path = port._filesystem.join(port.layout_tests_dir(), 'NeverFixTests')279 stale_tests_path = port._filesystem.join(port.layout_tests_dir(), 'StaleTestExpectations')280 slow_tests_path = port._filesystem.join(port.layout_tests_dir(), 'SlowTests')281 flaky_tests_path = port._filesystem.join(port.layout_tests_dir(), 'FlakyTests')282 skia_overrides_path = port.path_from_chromium_base(283 'skia', 'skia_test_expectations.txt')284 port._filesystem.write_text_file(skia_overrides_path, 'dummy text')285 w3c_overrides_path = port.path_from_chromium_base(286 'webkit', 'tools', 'layout_tests', 'test_expectations_w3c.txt')287 port._filesystem.write_text_file(w3c_overrides_path, 'dummy text')288 port._options.builder_name = 'DUMMY_BUILDER_NAME'289 self.assertEqual(port.expectations_files(),290 [generic_path, skia_overrides_path, w3c_overrides_path,291 never_fix_tests_path, stale_tests_path, slow_tests_path,292 flaky_tests_path, chromium_overrides_path])293 port._options.builder_name = 'builder (deps)'294 self.assertEqual(port.expectations_files(),295 [generic_path, skia_overrides_path, w3c_overrides_path,296 never_fix_tests_path, stale_tests_path, slow_tests_path,297 flaky_tests_path, chromium_overrides_path])298 # A builder which does NOT observe the Chromium test_expectations,299 # but still observes the Skia test_expectations...300 port._options.builder_name = 'builder'301 self.assertEqual(port.expectations_files(),302 [generic_path, skia_overrides_path, w3c_overrides_path,303 never_fix_tests_path, stale_tests_path, slow_tests_path,304 flaky_tests_path])305 def test_check_sys_deps(self):306 port = self.make_port()307 port._executive = MockExecutive2(exit_code=0)308 self.assertEqual(port.check_sys_deps(needs_http=False), test_run_results.OK_EXIT_STATUS)309 port._executive = MockExecutive2(exit_code=1, output='testing output failure')310 self.assertEqual(port.check_sys_deps(needs_http=False), test_run_results.SYS_DEPS_EXIT_STATUS)311 def test_expectations_ordering(self):312 port = self.make_port()313 for path in port.expectations_files():314 port._filesystem.write_text_file(path, '')315 ordered_dict = port.expectations_dict()316 self.assertEqual(port.path_to_generic_test_expectations_file(), ordered_dict.keys()[0])317 options = MockOptions(additional_expectations=['/tmp/foo', '/tmp/bar'])318 port = self.make_port(options=options)319 for path in port.expectations_files():320 port._filesystem.write_text_file(path, '')321 port._filesystem.write_text_file('/tmp/foo', 'foo')322 port._filesystem.write_text_file('/tmp/bar', 'bar')323 ordered_dict = port.expectations_dict()324 self.assertEqual(ordered_dict.keys()[-2:], options.additional_expectations) # pylint: disable=E1101325 self.assertEqual(ordered_dict.values()[-2:], ['foo', 'bar'])326 def test_skipped_directories_for_symbols(self):327 # This first test confirms that the commonly found symbols result in the expected skipped directories.328 symbols_string = " ".join(["fooSymbol"])329 expected_directories = set([330 "webaudio/codec-tests/mp3",331 "webaudio/codec-tests/aac",332 ])333 result_directories = set(TestWebKitPort(symbols_string=symbols_string)._skipped_tests_for_unsupported_features(test_list=['webaudio/codec-tests/mp3/foo.html']))334 self.assertEqual(result_directories, expected_directories)335 # Test that the nm string parsing actually works:336 symbols_string = """337000000000124f498 s __ZZN7WebCore13ff_mp3_decoder12replaceChildEPS0_S1_E19__PRETTY_FUNCTION__338000000000124f500 s __ZZN7WebCore13ff_mp3_decoder13addChildAboveEPS0_S1_E19__PRETTY_FUNCTION__339000000000124f670 s __ZZN7WebCore13ff_mp3_decoder13addChildBelowEPS0_S1_E19__PRETTY_FUNCTION__340"""341 # Note 'compositing' is not in the list of skipped directories (hence the parsing of GraphicsLayer worked):342 expected_directories = set([343 "webaudio/codec-tests/aac",344 ])345 result_directories = set(TestWebKitPort(symbols_string=symbols_string)._skipped_tests_for_unsupported_features(test_list=['webaudio/codec-tests/mp3/foo.html']))346 self.assertEqual(result_directories, expected_directories)347 def _assert_config_file_for_platform(self, port, platform, config_file):348 self.assertEqual(port._apache_config_file_name_for_platform(platform), config_file)349 def test_linux_distro_detection(self):350 port = TestWebKitPort()351 self.assertFalse(port._is_redhat_based())352 self.assertFalse(port._is_debian_based())353 port._filesystem = MockFileSystem({'/etc/redhat-release': ''})354 self.assertTrue(port._is_redhat_based())355 self.assertFalse(port._is_debian_based())356 port._filesystem = MockFileSystem({'/etc/debian_version': ''})357 self.assertFalse(port._is_redhat_based())358 self.assertTrue(port._is_debian_based())359 def test_apache_config_file_name_for_platform(self):360 port = TestWebKitPort()361 self._assert_config_file_for_platform(port, 'cygwin', 'cygwin-httpd.conf')362 self._assert_config_file_for_platform(port, 'linux2', 'apache2-httpd.conf')363 self._assert_config_file_for_platform(port, 'linux3', 'apache2-httpd.conf')364 port._is_redhat_based = lambda: True365 port._apache_version = lambda: '2.2'366 self._assert_config_file_for_platform(port, 'linux2', 'fedora-httpd-2.2.conf')367 port = TestWebKitPort()368 port._is_debian_based = lambda: True369 port._apache_version = lambda: '2.2'370 self._assert_config_file_for_platform(port, 'linux2', 'debian-httpd-2.2.conf')371 self._assert_config_file_for_platform(port, 'mac', 'apache2-httpd.conf')372 self._assert_config_file_for_platform(port, 'win32', 'apache2-httpd.conf') # win32 isn't a supported sys.platform. AppleWin/WinCairo/WinCE ports all use cygwin.373 self._assert_config_file_for_platform(port, 'barf', 'apache2-httpd.conf')374 def test_path_to_apache_config_file(self):375 port = TestWebKitPort()376 saved_environ = os.environ.copy()377 try:378 os.environ['WEBKIT_HTTP_SERVER_CONF_PATH'] = '/path/to/httpd.conf'379 self.assertRaises(IOError, port.path_to_apache_config_file)380 port._filesystem.write_text_file('/existing/httpd.conf', 'Hello, world!')381 os.environ['WEBKIT_HTTP_SERVER_CONF_PATH'] = '/existing/httpd.conf'382 self.assertEqual(port.path_to_apache_config_file(), '/existing/httpd.conf')383 finally:384 os.environ = saved_environ.copy()385 # Mock out _apache_config_file_name_for_platform to ignore the passed sys.platform value.386 port._apache_config_file_name_for_platform = lambda platform: 'httpd.conf'387 self.assertEqual(port.path_to_apache_config_file(), '/mock-checkout/third_party/WebKit/LayoutTests/http/conf/httpd.conf')388 # Check that even if we mock out _apache_config_file_name, the environment variable takes precedence.389 saved_environ = os.environ.copy()390 try:391 os.environ['WEBKIT_HTTP_SERVER_CONF_PATH'] = '/existing/httpd.conf'392 self.assertEqual(port.path_to_apache_config_file(), '/existing/httpd.conf')393 finally:394 os.environ = saved_environ.copy()395 def test_additional_platform_directory(self):396 port = self.make_port(options=MockOptions(additional_platform_directory=['/tmp/foo']))...

Full Screen

Full Screen

miscellaneous_bindings.js

Source:miscellaneous_bindings.js Github

copy

Full Screen

1// Copyright (c) 2012 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4// This contains unprivileged javascript APIs for extensions and apps. It5// can be loaded by any extension-related context, such as content scripts or6// background pages. See user_script_slave.cc for script that is loaded by7// content scripts only.8 require('json_schema');9 require('event_bindings');10 var lastError = require('lastError');11 var miscNatives = requireNative('miscellaneous_bindings');12 var CloseChannel = miscNatives.CloseChannel;13 var PortAddRef = miscNatives.PortAddRef;14 var PortRelease = miscNatives.PortRelease;15 var PostMessage = miscNatives.PostMessage;16 var BindToGC = miscNatives.BindToGC;17 var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();18 var processNatives = requireNative('process');19 var manifestVersion = processNatives.GetManifestVersion();20 var extensionId = processNatives.GetExtensionId();21 // The reserved channel name for the sendRequest/sendMessage APIs.22 // Note: sendRequest is deprecated.23 chromeHidden.kRequestChannel = "chrome.extension.sendRequest";24 chromeHidden.kMessageChannel = "chrome.runtime.sendMessage";25 chromeHidden.kNativeMessageChannel = "chrome.runtime.sendNativeMessage";26 // Map of port IDs to port object.27 var ports = {};28 // Map of port IDs to chromeHidden.onUnload listeners. Keep track of these29 // to free the onUnload listeners when ports are closed.30 var portReleasers = {};31 // Change even to odd and vice versa, to get the other side of a given32 // channel.33 function getOppositePortId(portId) { return portId ^ 1; }34 // Port object. Represents a connection to another script context through35 // which messages can be passed.36 function PortImpl(portId, opt_name) {37 this.portId_ = portId;38 this.name = opt_name;39 this.onDisconnect = new chrome.Event();40 this.onMessage = new chrome.Event();41 }42 // Sends a message asynchronously to the context on the other end of this43 // port.44 PortImpl.prototype.postMessage = function(msg) {45 // JSON.stringify doesn't support a root object which is undefined.46 if (msg === undefined)47 msg = null;48 PostMessage(this.portId_, chromeHidden.JSON.stringify(msg));49 };50 // Disconnects the port from the other end.51 PortImpl.prototype.disconnect = function() {52 CloseChannel(this.portId_, true);53 this.destroy_();54 };55 PortImpl.prototype.destroy_ = function() {56 var portId = this.portId_;57 this.onDisconnect.destroy_();58 this.onMessage.destroy_();59 PortRelease(portId);60 chromeHidden.onUnload.removeListener(portReleasers[portId]);61 delete ports[portId];62 delete portReleasers[portId];63 };64 chromeHidden.Port = {};65 // Returns true if the specified port id is in this context. This is used by66 // the C++ to avoid creating the javascript message for all the contexts that67 // don't care about a particular message.68 chromeHidden.Port.hasPort = function(portId) {69 return portId in ports;70 };71 // Hidden port creation function. We don't want to expose an API that lets72 // people add arbitrary port IDs to the port list.73 chromeHidden.Port.createPort = function(portId, opt_name) {74 if (ports[portId]) {75 throw new Error("Port '" + portId + "' already exists.");76 }77 var port = new PortImpl(portId, opt_name);78 ports[portId] = port;79 portReleasers[portId] = PortRelease.bind(this, portId);80 chromeHidden.onUnload.addListener(portReleasers[portId]);81 PortAddRef(portId);82 return port;83 };84 // Helper function for dispatchOnRequest.85 function handleSendRequestError(isSendMessage, responseCallbackPreserved,86 sourceExtensionId, targetExtensionId) {87 var errorMsg;88 var eventName = (isSendMessage ?89 "chrome.runtime.onMessage" : "chrome.extension.onRequest");90 if (isSendMessage && !responseCallbackPreserved) {91 errorMsg =92 "The " + eventName + " listener must return true if you want to" +93 " send a response after the listener returns ";94 } else {95 errorMsg =96 "Cannot send a response more than once per " + eventName +97 " listener per document";98 }99 errorMsg += " (message was sent by extension " + sourceExtensionId;100 if (sourceExtensionId != targetExtensionId)101 errorMsg += " for extension " + targetExtensionId;102 errorMsg += ").";103 lastError.set(errorMsg);104 console.error("Could not send response: " + errorMsg);105 }106 // Helper function for dispatchOnConnect107 function dispatchOnRequest(portId, channelName, sender,108 sourceExtensionId, targetExtensionId,109 isExternal) {110 var isSendMessage = channelName == chromeHidden.kMessageChannel;111 var requestEvent = (isSendMessage ?112 (isExternal ?113 chrome.runtime.onMessageExternal : chrome.runtime.onMessage) :114 (isExternal ?115 chrome.extension.onRequestExternal : chrome.extension.onRequest));116 if (requestEvent.hasListeners()) {117 var port = chromeHidden.Port.createPort(portId, channelName);118 port.onMessage.addListener(function(request) {119 var responseCallbackPreserved = false;120 var responseCallback = function(response) {121 if (port) {122 port.postMessage(response);123 port.destroy_();124 port = null;125 } else {126 // We nulled out port when sending the response, and now the page127 // is trying to send another response for the same request.128 handleSendRequestError(isSendMessage, responseCallbackPreserved,129 sourceExtensionId, targetExtensionId);130 }131 };132 // In case the extension never invokes the responseCallback, and also133 // doesn't keep a reference to it, we need to clean up the port. Do134 // so by attaching to the garbage collection of the responseCallback135 // using some native hackery.136 BindToGC(responseCallback, function() {137 if (port) {138 port.destroy_();139 port = null;140 }141 });142 if (!isSendMessage) {143 requestEvent.dispatch(request, sender, responseCallback);144 } else {145 var rv = requestEvent.dispatch(request, sender, responseCallback);146 responseCallbackPreserved =147 rv && rv.results && rv.results.indexOf(true) > -1;148 if (!responseCallbackPreserved && port) {149 // If they didn't access the response callback, they're not150 // going to send a response, so clean up the port immediately.151 port.destroy_();152 port = null;153 }154 }155 });156 return true;157 }158 return false;159 }160 // Called by native code when a channel has been opened to this context.161 chromeHidden.Port.dispatchOnConnect = function(portId, channelName, tab,162 sourceExtensionId,163 targetExtensionId) {164 // Only create a new Port if someone is actually listening for a connection.165 // In addition to being an optimization, this also fixes a bug where if 2166 // channels were opened to and from the same process, closing one would167 // close both.168 if (targetExtensionId != extensionId)169 return false; // not for us170 if (ports[getOppositePortId(portId)])171 return false; // this channel was opened by us, so ignore it172 // Determine whether this is coming from another extension, so we can use173 // the right event.174 var isExternal = sourceExtensionId != extensionId;175 if (tab)176 tab = chromeHidden.JSON.parse(tab);177 var sender = {tab: tab, id: sourceExtensionId};178 // Special case for sendRequest/onRequest and sendMessage/onMessage.179 if (channelName == chromeHidden.kRequestChannel ||180 channelName == chromeHidden.kMessageChannel) {181 return dispatchOnRequest(portId, channelName, sender,182 sourceExtensionId, targetExtensionId,183 isExternal);184 }185 var connectEvent = (isExternal ?186 chrome.runtime.onConnectExternal : chrome.runtime.onConnect);187 if (connectEvent.hasListeners()) {188 var port = chromeHidden.Port.createPort(portId, channelName);189 port.sender = sender;190 if (manifestVersion < 2)191 port.tab = port.sender.tab;192 connectEvent.dispatch(port);193 return true;194 }195 return false;196 };197 // Called by native code when a channel has been closed.198 chromeHidden.Port.dispatchOnDisconnect = function(199 portId, connectionInvalid) {200 var port = ports[portId];201 if (port) {202 // Update the renderer's port bookkeeping, without notifying the browser.203 CloseChannel(portId, false);204 if (connectionInvalid) {205 var errorMsg =206 "Could not establish connection. Receiving end does not exist.";207 lastError.set(errorMsg);208 console.error("Port error: " + errorMsg);209 }210 try {211 port.onDisconnect.dispatch(port);212 } finally {213 port.destroy_();214 lastError.clear();215 }216 }217 };218 // Called by native code when a message has been sent to the given port.219 chromeHidden.Port.dispatchOnMessage = function(msg, portId) {220 var port = ports[portId];221 if (port) {222 if (msg) {223 msg = chromeHidden.JSON.parse(msg);224 }225 port.onMessage.dispatch(msg, port);226 }227 };228 // Shared implementation used by tabs.sendMessage and runtime.sendMessage.229 chromeHidden.Port.sendMessageImpl = function(port, request,230 responseCallback) {231 if (port.name != chromeHidden.kNativeMessageChannel)232 port.postMessage(request);233 if (port.name == chromeHidden.kMessageChannel && !responseCallback) {234 // TODO(mpcomplete): Do this for the old sendRequest API too, after235 // verifying it doesn't break anything.236 // Go ahead and disconnect immediately if the sender is not expecting237 // a response.238 port.disconnect();239 return;240 }241 // Ensure the callback exists for the older sendRequest API.242 if (!responseCallback)243 responseCallback = function() {};244 port.onDisconnect.addListener(function() {245 // For onDisconnects, we only notify the callback if there was an error246 try {247 if (chrome.runtime.lastError)248 responseCallback();249 } finally {250 port = null;251 }252 });253 port.onMessage.addListener(function(response) {254 try {255 responseCallback(response);256 } finally {257 port.disconnect();258 port = null;259 }260 });261 };262 function sendMessageUpdateArguments(functionName) {263 // Align missing (optional) function arguments with the arguments that264 // schema validation is expecting, e.g.265 // extension.sendRequest(req) -> extension.sendRequest(null, req)266 // extension.sendRequest(req, cb) -> extension.sendRequest(null, req, cb)267 var args = Array.prototype.splice.call(arguments, 1); // skip functionName268 var lastArg = args.length - 1;269 // responseCallback (last argument) is optional.270 var responseCallback = null;271 if (typeof(args[lastArg]) == 'function')272 responseCallback = args[lastArg--];273 // request (second argument) is required.274 var request = args[lastArg--];275 // targetId (first argument, extensionId in the manfiest) is optional.276 var targetId = null;277 if (lastArg >= 0)278 targetId = args[lastArg--];279 if (lastArg != -1)280 throw new Error('Invalid arguments to ' + functionName + '.');281 return [targetId, request, responseCallback];282 }...

Full Screen

Full Screen

QtSerialPort.pyi

Source:QtSerialPort.pyi Github

copy

Full Screen

1# The PEP 484 type hints stub file for the QtSerialPort module.2#3# Generated by SIP 4.18.14#5# Copyright (c) 2016 Riverbank Computing Limited <info@riverbankcomputing.com>6# 7# This file is part of PyQt5.8# 9# This file may be used under the terms of the GNU General Public License10# version 3.0 as published by the Free Software Foundation and appearing in11# the file LICENSE included in the packaging of this file. Please review the12# following information to ensure the GNU General Public License version 3.013# requirements will be met: http://www.gnu.org/copyleft/gpl.html.14# 15# If you do not wish to use this file under the terms of the GPL version 3.016# then you may purchase a commercial license. For more information contact17# info@riverbankcomputing.com.18# 19# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE20# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.21import typing22import sip23from PyQt5 import QtCore24# Support for QDate, QDateTime and QTime.25import datetime26# Convenient type aliases.27PYQT_SIGNAL = typing.Union[QtCore.pyqtSignal, QtCore.pyqtBoundSignal]28PYQT_SLOT = typing.Union[typing.Callable[..., None], QtCore.pyqtBoundSignal]29class QSerialPort(QtCore.QIODevice):30 class SerialPortError(int): ...31 NoError = ... # type: 'QSerialPort.SerialPortError'32 DeviceNotFoundError = ... # type: 'QSerialPort.SerialPortError'33 PermissionError = ... # type: 'QSerialPort.SerialPortError'34 OpenError = ... # type: 'QSerialPort.SerialPortError'35 ParityError = ... # type: 'QSerialPort.SerialPortError'36 FramingError = ... # type: 'QSerialPort.SerialPortError'37 BreakConditionError = ... # type: 'QSerialPort.SerialPortError'38 WriteError = ... # type: 'QSerialPort.SerialPortError'39 ReadError = ... # type: 'QSerialPort.SerialPortError'40 ResourceError = ... # type: 'QSerialPort.SerialPortError'41 UnsupportedOperationError = ... # type: 'QSerialPort.SerialPortError'42 TimeoutError = ... # type: 'QSerialPort.SerialPortError'43 NotOpenError = ... # type: 'QSerialPort.SerialPortError'44 UnknownError = ... # type: 'QSerialPort.SerialPortError'45 class DataErrorPolicy(int): ...46 SkipPolicy = ... # type: 'QSerialPort.DataErrorPolicy'47 PassZeroPolicy = ... # type: 'QSerialPort.DataErrorPolicy'48 IgnorePolicy = ... # type: 'QSerialPort.DataErrorPolicy'49 StopReceivingPolicy = ... # type: 'QSerialPort.DataErrorPolicy'50 UnknownPolicy = ... # type: 'QSerialPort.DataErrorPolicy'51 class PinoutSignal(int): ...52 NoSignal = ... # type: 'QSerialPort.PinoutSignal'53 TransmittedDataSignal = ... # type: 'QSerialPort.PinoutSignal'54 ReceivedDataSignal = ... # type: 'QSerialPort.PinoutSignal'55 DataTerminalReadySignal = ... # type: 'QSerialPort.PinoutSignal'56 DataCarrierDetectSignal = ... # type: 'QSerialPort.PinoutSignal'57 DataSetReadySignal = ... # type: 'QSerialPort.PinoutSignal'58 RingIndicatorSignal = ... # type: 'QSerialPort.PinoutSignal'59 RequestToSendSignal = ... # type: 'QSerialPort.PinoutSignal'60 ClearToSendSignal = ... # type: 'QSerialPort.PinoutSignal'61 SecondaryTransmittedDataSignal = ... # type: 'QSerialPort.PinoutSignal'62 SecondaryReceivedDataSignal = ... # type: 'QSerialPort.PinoutSignal'63 class FlowControl(int): ...64 NoFlowControl = ... # type: 'QSerialPort.FlowControl'65 HardwareControl = ... # type: 'QSerialPort.FlowControl'66 SoftwareControl = ... # type: 'QSerialPort.FlowControl'67 UnknownFlowControl = ... # type: 'QSerialPort.FlowControl'68 class StopBits(int): ...69 OneStop = ... # type: 'QSerialPort.StopBits'70 OneAndHalfStop = ... # type: 'QSerialPort.StopBits'71 TwoStop = ... # type: 'QSerialPort.StopBits'72 UnknownStopBits = ... # type: 'QSerialPort.StopBits'73 class Parity(int): ...74 NoParity = ... # type: 'QSerialPort.Parity'75 EvenParity = ... # type: 'QSerialPort.Parity'76 OddParity = ... # type: 'QSerialPort.Parity'77 SpaceParity = ... # type: 'QSerialPort.Parity'78 MarkParity = ... # type: 'QSerialPort.Parity'79 UnknownParity = ... # type: 'QSerialPort.Parity'80 class DataBits(int): ...81 Data5 = ... # type: 'QSerialPort.DataBits'82 Data6 = ... # type: 'QSerialPort.DataBits'83 Data7 = ... # type: 'QSerialPort.DataBits'84 Data8 = ... # type: 'QSerialPort.DataBits'85 UnknownDataBits = ... # type: 'QSerialPort.DataBits'86 class BaudRate(int): ...87 Baud1200 = ... # type: 'QSerialPort.BaudRate'88 Baud2400 = ... # type: 'QSerialPort.BaudRate'89 Baud4800 = ... # type: 'QSerialPort.BaudRate'90 Baud9600 = ... # type: 'QSerialPort.BaudRate'91 Baud19200 = ... # type: 'QSerialPort.BaudRate'92 Baud38400 = ... # type: 'QSerialPort.BaudRate'93 Baud57600 = ... # type: 'QSerialPort.BaudRate'94 Baud115200 = ... # type: 'QSerialPort.BaudRate'95 UnknownBaud = ... # type: 'QSerialPort.BaudRate'96 class Direction(int): ...97 Input = ... # type: 'QSerialPort.Direction'98 Output = ... # type: 'QSerialPort.Direction'99 AllDirections = ... # type: 'QSerialPort.Direction'100 class Directions(sip.simplewrapper):101 @typing.overload102 def __init__(self) -> None: ...103 @typing.overload104 def __init__(self, f: typing.Union['QSerialPort.Directions', 'QSerialPort.Direction']) -> None: ...105 @typing.overload106 def __init__(self, a0: 'QSerialPort.Directions') -> None: ...107 def __bool__(self) -> int: ...108 def __invert__(self) -> 'QSerialPort.Directions': ...109 def __int__(self) -> int: ...110 class PinoutSignals(sip.simplewrapper):111 @typing.overload112 def __init__(self) -> None: ...113 @typing.overload114 def __init__(self, f: typing.Union['QSerialPort.PinoutSignals', 'QSerialPort.PinoutSignal']) -> None: ...115 @typing.overload116 def __init__(self, a0: 'QSerialPort.PinoutSignals') -> None: ...117 def __bool__(self) -> int: ...118 def __invert__(self) -> 'QSerialPort.PinoutSignals': ...119 def __int__(self) -> int: ...120 @typing.overload121 def __init__(self, parent: typing.Optional[QtCore.QObject] = ...) -> None: ...122 @typing.overload123 def __init__(self, name: str, parent: typing.Optional[QtCore.QObject] = ...) -> None: ...124 @typing.overload125 def __init__(self, info: 'QSerialPortInfo', parent: typing.Optional[QtCore.QObject] = ...) -> None: ...126 def breakEnabledChanged(self, set: bool) -> None: ...127 def isBreakEnabled(self) -> bool: ...128 def handle(self) -> sip.voidptr: ...129 def writeData(self, data: bytes) -> int: ...130 def readLineData(self, maxlen: int) -> bytes: ...131 def readData(self, maxlen: int) -> bytes: ...132 def settingsRestoredOnCloseChanged(self, restore: bool) -> None: ...133 def requestToSendChanged(self, set: bool) -> None: ...134 def dataTerminalReadyChanged(self, set: bool) -> None: ...135 def dataErrorPolicyChanged(self, policy: 'QSerialPort.DataErrorPolicy') -> None: ...136 def flowControlChanged(self, flow: 'QSerialPort.FlowControl') -> None: ...137 def stopBitsChanged(self, stopBits: 'QSerialPort.StopBits') -> None: ...138 def parityChanged(self, parity: 'QSerialPort.Parity') -> None: ...139 def dataBitsChanged(self, dataBits: 'QSerialPort.DataBits') -> None: ...140 def baudRateChanged(self, baudRate: int, directions: typing.Union['QSerialPort.Directions', 'QSerialPort.Direction']) -> None: ...141 def setBreakEnabled(self, enabled: bool = ...) -> bool: ...142 def sendBreak(self, duration: int = ...) -> bool: ...143 def waitForBytesWritten(self, msecs: int) -> bool: ...144 def waitForReadyRead(self, msecs: int) -> bool: ...145 def canReadLine(self) -> bool: ...146 def bytesToWrite(self) -> int: ...147 def bytesAvailable(self) -> int: ...148 def isSequential(self) -> bool: ...149 def setReadBufferSize(self, size: int) -> None: ...150 def readBufferSize(self) -> int: ...151 def clearError(self) -> None: ...152 @typing.overload153 def error(self) -> 'QSerialPort.SerialPortError': ...154 @typing.overload155 def error(self, serialPortError: 'QSerialPort.SerialPortError') -> None: ...156 def dataErrorPolicy(self) -> 'QSerialPort.DataErrorPolicy': ...157 def setDataErrorPolicy(self, policy: 'QSerialPort.DataErrorPolicy' = ...) -> bool: ...158 def atEnd(self) -> bool: ...159 def clear(self, dir: typing.Union['QSerialPort.Directions', 'QSerialPort.Direction'] = ...) -> bool: ...160 def flush(self) -> bool: ...161 def pinoutSignals(self) -> 'QSerialPort.PinoutSignals': ...162 def isRequestToSend(self) -> bool: ...163 def setRequestToSend(self, set: bool) -> bool: ...164 def isDataTerminalReady(self) -> bool: ...165 def setDataTerminalReady(self, set: bool) -> bool: ...166 def flowControl(self) -> 'QSerialPort.FlowControl': ...167 def setFlowControl(self, flow: 'QSerialPort.FlowControl') -> bool: ...168 def stopBits(self) -> 'QSerialPort.StopBits': ...169 def setStopBits(self, stopBits: 'QSerialPort.StopBits') -> bool: ...170 def parity(self) -> 'QSerialPort.Parity': ...171 def setParity(self, parity: 'QSerialPort.Parity') -> bool: ...172 def dataBits(self) -> 'QSerialPort.DataBits': ...173 def setDataBits(self, dataBits: 'QSerialPort.DataBits') -> bool: ...174 def baudRate(self, dir: typing.Union['QSerialPort.Directions', 'QSerialPort.Direction'] = ...) -> int: ...175 def setBaudRate(self, baudRate: int, dir: typing.Union['QSerialPort.Directions', 'QSerialPort.Direction'] = ...) -> bool: ...176 def settingsRestoredOnClose(self) -> bool: ...177 def setSettingsRestoredOnClose(self, restore: bool) -> None: ...178 def close(self) -> None: ...179 def open(self, mode: typing.Union[QtCore.QIODevice.OpenMode, QtCore.QIODevice.OpenModeFlag]) -> bool: ...180 def setPort(self, info: 'QSerialPortInfo') -> None: ...181 def portName(self) -> str: ...182 def setPortName(self, name: str) -> None: ...183class QSerialPortInfo(sip.simplewrapper):184 @typing.overload185 def __init__(self) -> None: ...186 @typing.overload187 def __init__(self, port: QSerialPort) -> None: ...188 @typing.overload189 def __init__(self, name: str) -> None: ...190 @typing.overload191 def __init__(self, other: 'QSerialPortInfo') -> None: ...192 def serialNumber(self) -> str: ...193 def isNull(self) -> bool: ...194 @staticmethod195 def availablePorts() -> typing.Any: ...196 @staticmethod197 def standardBaudRates() -> typing.List[int]: ...198 def isValid(self) -> bool: ...199 def isBusy(self) -> bool: ...200 def hasProductIdentifier(self) -> bool: ...201 def hasVendorIdentifier(self) -> bool: ...202 def productIdentifier(self) -> int: ...203 def vendorIdentifier(self) -> int: ...204 def manufacturer(self) -> str: ...205 def description(self) -> str: ...206 def systemLocation(self) -> str: ...207 def portName(self) -> str: ......

Full Screen

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 testcontainers-python 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