How to use port method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

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

PortMappings-test.js

Source:PortMappings-test.js Github

copy

Full Screen

1const PortMappings = require("../PortMappings");2const { ADD_ITEM } = require("#SRC/js/constants/TransactionTypes");3const Transaction = require("#SRC/js/structs/Transaction");4const { type: { BRIDGE } } = require("#SRC/js/constants/Networking");5const { type: { DOCKER } } = require("../../../constants/ContainerConstants");6describe("#JSONParser", function() {7 describe("PortMappings", function() {8 it("should add portDefinition with details", function() {9 expect(10 PortMappings.JSONParser({11 type: DOCKER,12 container: {13 docker: {14 network: BRIDGE,15 portMappings: [16 {17 name: "foo",18 hostPort: 0,19 containerPort: 80,20 protocol: "tcp"21 }22 ]23 }24 }25 })26 ).toEqual([27 new Transaction(["portDefinitions"], null, ADD_ITEM),28 new Transaction(["portDefinitions", 0, "name"], "foo"),29 new Transaction(["portDefinitions", 0, "automaticPort"], true),30 new Transaction(["portDefinitions", 0, "portMapping"], true),31 new Transaction(["portDefinitions", 0, "containerPort"], 80),32 new Transaction(["portDefinitions", 0, "protocol", "udp"], false),33 new Transaction(["portDefinitions", 0, "protocol", "tcp"], true)34 ]);35 });36 it("shouldn't add existing, but update details", function() {37 expect(38 PortMappings.JSONParser({39 type: DOCKER,40 container: {41 docker: {42 network: BRIDGE,43 portMappings: [44 {45 name: "foo",46 hostPort: 0,47 containerPort: 80,48 protocol: "tcp"49 }50 ]51 }52 },53 portDefinitions: [54 {55 name: "foo",56 port: 0,57 protocol: "tcp"58 }59 ]60 })61 ).toEqual([62 new Transaction(["portDefinitions", 0, "name"], "foo"),63 new Transaction(["portDefinitions", 0, "automaticPort"], true),64 new Transaction(["portDefinitions", 0, "portMapping"], true),65 new Transaction(["portDefinitions", 0, "containerPort"], 80),66 new Transaction(["portDefinitions", 0, "protocol", "udp"], false),67 new Transaction(["portDefinitions", 0, "protocol", "tcp"], true)68 ]);69 });70 it("should add Transaction for automaticPort and hostPort", function() {71 expect(72 PortMappings.JSONParser({73 type: DOCKER,74 container: {75 docker: {76 network: BRIDGE,77 portMappings: [78 {79 hostPort: 1080 }81 ]82 }83 }84 })85 ).toEqual([86 new Transaction(["portDefinitions"], null, ADD_ITEM),87 new Transaction(["portDefinitions", 0, "automaticPort"], false),88 new Transaction(["portDefinitions", 0, "portMapping"], true),89 new Transaction(["portDefinitions", 0, "hostPort"], 10)90 ]);91 });92 it("should add Transaction for loadBalanced ports", function() {93 expect(94 PortMappings.JSONParser({95 type: DOCKER,96 container: {97 docker: {98 network: BRIDGE,99 portMappings: [100 {101 labels: {102 VIP_0: "/:0"103 }104 }105 ]106 }107 }108 })109 ).toEqual([110 new Transaction(["portDefinitions"], null, ADD_ITEM),111 new Transaction(["portDefinitions", 0, "portMapping"], false),112 new Transaction(["portDefinitions", 0, "loadBalanced"], true),113 new Transaction(["portDefinitions", 0, "vip"], "/:0"),114 new Transaction(["portDefinitions", 0, "vipPort"], "0"),115 new Transaction(["portDefinitions", 0, "labels"], { VIP_0: "/:0" })116 ]);117 });118 it("shouldn't add loadBalanced for wrong label", function() {119 expect(120 PortMappings.JSONParser({121 type: DOCKER,122 container: {123 docker: {124 network: BRIDGE,125 portMappings: [126 {127 labels: {128 VIP_1: "/:0"129 }130 }131 ]132 }133 }134 })135 ).toEqual([136 new Transaction(["portDefinitions"], null, ADD_ITEM),137 new Transaction(["portDefinitions", 0, "portMapping"], false),138 new Transaction(["portDefinitions", 0, "labels"], { VIP_1: "/:0" })139 ]);140 });141 it("should add Transaction for protocol", function() {142 expect(143 PortMappings.JSONParser({144 type: DOCKER,145 container: {146 docker: {147 network: BRIDGE,148 portMappings: [149 {150 protocol: "udp"151 }152 ]153 }154 }155 })156 ).toEqual([157 new Transaction(["portDefinitions"], null, ADD_ITEM),158 new Transaction(["portDefinitions", 0, "portMapping"], false),159 new Transaction(["portDefinitions", 0, "protocol", "udp"], true),160 new Transaction(["portDefinitions", 0, "protocol", "tcp"], false)161 ]);162 });163 it("should merge info from portMappings and portDefinitions", function() {164 expect(165 PortMappings.JSONParser({166 type: DOCKER,167 container: {168 docker: {169 network: BRIDGE,170 portMappings: [171 {172 name: "foo",173 hostPort: 0,174 containerPort: 80,175 protocol: "tcp"176 },177 {178 name: "bar",179 hostPort: 10,180 containerPort: 81,181 protocol: "tcp",182 labels: {183 VIP_1: "/:0"184 }185 }186 ]187 }188 },189 portDefinitions: [190 {191 name: "foo",192 port: 0,193 protocol: "tcp"194 }195 ]196 })197 ).toEqual([198 new Transaction(["portDefinitions"], null, ADD_ITEM),199 new Transaction(["portDefinitions", 0, "name"], "foo"),200 new Transaction(["portDefinitions", 0, "automaticPort"], true),201 new Transaction(["portDefinitions", 0, "portMapping"], true),202 new Transaction(["portDefinitions", 0, "containerPort"], 80),203 new Transaction(["portDefinitions", 0, "protocol", "udp"], false),204 new Transaction(["portDefinitions", 0, "protocol", "tcp"], true),205 new Transaction(["portDefinitions", 1, "name"], "bar"),206 new Transaction(["portDefinitions", 1, "automaticPort"], false),207 new Transaction(["portDefinitions", 1, "portMapping"], true),208 new Transaction(["portDefinitions", 1, "hostPort"], 10),209 new Transaction(["portDefinitions", 1, "containerPort"], 81),210 new Transaction(["portDefinitions", 1, "protocol", "udp"], false),211 new Transaction(["portDefinitions", 1, "protocol", "tcp"], true),212 new Transaction(["portDefinitions", 1, "loadBalanced"], true),213 new Transaction(["portDefinitions", 1, "vip"], "/:0"),214 new Transaction(["portDefinitions", 1, "vipPort"], "0"),215 new Transaction(["portDefinitions", 1, "labels"], { VIP_1: "/:0" })216 ]);217 });218 it("should not add more from portMappings when less than portDefinitions", function() {219 expect(220 PortMappings.JSONParser({221 type: DOCKER,222 container: {223 docker: {224 network: BRIDGE,225 portMappings: [226 {227 name: "foo",228 hostPort: 0,229 containerPort: 80,230 protocol: "tcp"231 }232 ]233 }234 },235 portDefinitions: [236 {237 name: "foo",238 port: 0,239 protocol: "tcp"240 },241 {242 name: "bar",243 port: 10,244 protocol: "tcp",245 labels: {246 VIP_1: "/:0"247 }248 }249 ]250 })251 ).toEqual([252 new Transaction(["portDefinitions", 0, "name"], "foo"),253 new Transaction(["portDefinitions", 0, "automaticPort"], true),254 new Transaction(["portDefinitions", 0, "portMapping"], true),255 new Transaction(["portDefinitions", 0, "containerPort"], 80),256 new Transaction(["portDefinitions", 0, "protocol", "udp"], false),257 new Transaction(["portDefinitions", 0, "protocol", "tcp"], true)258 ]);259 });260 });...

Full Screen

Full Screen

networks.js

Source:networks.js Github

copy

Full Screen

1/** @module networks */2module.exports = {3 /** @type {Network} */4 ark: {5 messagePrefix: '\x18Ark Signed Message:\n',6 bip32: {7 public: 0x2bf4968, // base58 will have a prefix 'apub'8 private: 0x2bf4530 // base58Priv will have a prefix 'apriv'9 },10 name: 'mainnet',11 nethash: '6e84d08bd299ed97c212c886c98a57e36545c8f5d645ca7eeae63a8bd62d8988',12 token: 'ARK',13 symbol: 'Ѧ',14 pubKeyHash: 0x17, // Addresses will begin with 'A'15 explorer: 'https://explorer.ark.io',16 wif: 0xaa, // Network prefix for wif generation17 activePeer: {18 ip: 'node1.arknet.cloud',19 port: 400120 },21 peers: [22 { ip: '5.39.9.240', port: 4001 },23 { ip: '5.39.9.241', port: 4001 },24 { ip: '5.39.9.242', port: 4001 },25 { ip: '5.39.9.243', port: 4001 },26 { ip: '5.39.9.244', port: 4001 },27 { ip: '5.39.9.250', port: 4001 },28 { ip: '5.39.9.251', port: 4001 },29 { ip: '5.39.9.252', port: 4001 },30 { ip: '5.39.9.253', port: 4001 },31 { ip: '5.39.9.254', port: 4001 },32 { ip: '5.39.9.255', port: 4001 },33 { ip: '5.39.53.48', port: 4001 },34 { ip: '5.39.53.49', port: 4001 },35 { ip: '5.39.53.50', port: 4001 },36 { ip: '5.39.53.51', port: 4001 },37 { ip: '5.39.53.52', port: 4001 },38 { ip: '5.39.53.53', port: 4001 },39 { ip: '5.39.53.54', port: 4001 },40 { ip: '5.39.53.55', port: 4001 },41 { ip: '37.59.129.160', port: 4001 },42 { ip: '37.59.129.161', port: 4001 },43 { ip: '37.59.129.162', port: 4001 },44 { ip: '37.59.129.163', port: 4001 },45 { ip: '37.59.129.164', port: 4001 },46 { ip: '37.59.129.165', port: 4001 },47 { ip: '37.59.129.166', port: 4001 },48 { ip: '37.59.129.167', port: 4001 },49 { ip: '37.59.129.168', port: 4001 },50 { ip: '37.59.129.169', port: 4001 },51 { ip: '37.59.129.170', port: 4001 },52 { ip: '37.59.129.171', port: 4001 },53 { ip: '37.59.129.172', port: 4001 },54 { ip: '37.59.129.173', port: 4001 },55 { ip: '37.59.129.174', port: 4001 },56 { ip: '37.59.129.175', port: 4001 },57 { ip: '193.70.72.80', port: 4001 },58 { ip: '193.70.72.81', port: 4001 },59 { ip: '193.70.72.82', port: 4001 },60 { ip: '193.70.72.83', port: 4001 },61 { ip: '193.70.72.84', port: 4001 },62 { ip: '193.70.72.85', port: 4001 },63 { ip: '193.70.72.86', port: 4001 },64 { ip: '193.70.72.87', port: 4001 },65 { ip: '193.70.72.88', port: 4001 },66 { ip: '193.70.72.89', port: 4001 },67 { ip: '193.70.72.90', port: 4001 }68 ],69 },70 /** @type {Network} */71 testnet: {72 messagePrefix: '\x18Ark Testnet Signed Message:\n',73 bip32: {74 public: 0x043587cf,75 private: 0x0435839476 },77 name: 'devnet',78 nethash: '578e820911f24e039733b45e4882b73e301f813a0d2c31330dafda84534ffa23',79 token: 'DARK',80 symbol: 'DѦ',81 pubKeyHash: 0x52, // Addresses will begin with 'a'82 explorer: 'https://dexplorer.ark.io',83 wif: 0xba, // Network prefix for wif generation84 activePeer: {85 ip: '104.238.165.129',86 port: 400287 },88 peers: [89 { ip: '45.63.74.5', port: 4002 },90 { ip: '167.114.29.50', port: 4002 },91 { ip: '167.114.29.45', port: 4002 },92 { ip: '167.114.43.35', port: 4002 },93 { ip: '104.129.43.144', port: 4002 },94 { ip: '167.114.29.58', port: 4002 },95 { ip: '173.253.129.20', port: 4002 },96 { ip: '62.113.246.106', port: 4002 },97 { ip: '45.76.218.117', port: 4002 },98 { ip: '158.69.193.185', port: 4002 },99 { ip: '144.217.194.188', port: 4002 },100 { ip: '167.114.29.57', port: 4002 },101 { ip: '167.114.29.40', port: 4002 },102 { ip: '167.114.29.63', port: 4002 },103 { ip: '185.177.21.65', port: 4002 },104 { ip: '167.114.29.62', port: 4002 },105 { ip: '167.114.29.54', port: 4002 },106 { ip: '45.76.139.131', port: 4002 },107 { ip: '138.68.29.19', port: 4002 },108 { ip: '216.174.63.138', port: 4002 },109 { ip: '213.32.9.98', port: 4002 },110 { ip: '137.74.168.191', port: 4002 },111 { ip: '104.236.122.76', port: 4002 },112 { ip: '167.114.29.47', port: 4002 },113 { ip: '167.114.29.37', port: 4002 },114 { ip: '45.63.42.140', port: 4002 },115 { ip: '45.33.86.168', port: 4002 },116 { ip: '108.61.209.209', port: 4002 },117 { ip: '167.114.29.33', port: 4002 },118 { ip: '107.170.196.22', port: 4002 },119 { ip: '178.62.102.209', port: 4002 },120 { ip: '145.239.88.3', port: 4002 },121 { ip: '167.114.43.37', port: 4002 },122 { ip: '145.239.88.2', port: 4002 },123 { ip: '217.182.70.37', port: 4002 },124 { ip: '185.5.54.0', port: 4002 },125 { ip: '45.76.174.177', port: 4002 },126 { ip: '216.174.63.137', port: 4002 },127 { ip: '167.114.29.59', port: 4002 },128 { ip: '104.238.165.129', port: 4002 },129 { ip: '217.182.79.88', port: 4002 },130 { ip: '167.114.29.61', port: 4002 },131 { ip: '51.255.198.137', port: 4002 },132 { ip: '167.114.29.38', port: 4002 },133 { ip: '167.114.43.33', port: 4002 },134 { ip: '45.77.117.174', port: 4002 },135 { ip: '213.32.9.97', port: 4002 },136 { ip: '193.70.1.222', port: 4002 },137 { ip: '45.76.39.61', port: 4002 },138 { ip: '204.10.184.45', port: 4002 },139 { ip: '45.76.93.4', port: 4002 },140 { ip: '167.114.29.46', port: 4002 },141 { ip: '91.121.1.174', port: 4002 },142 { ip: '165.227.59.129', port: 4002 },143 { ip: '167.114.29.44', port: 4002 },144 { ip: '139.99.156.231', port: 4002 },145 { ip: '164.8.251.90', port: 4002 },146 { ip: '167.114.29.56', port: 4002 },147 { ip: '108.61.169.37', port: 4002 },148 { ip: '104.238.189.78', port: 4002 },149 { ip: '173.254.228.67', port: 4002 },150 { ip: '204.10.184.46', port: 4002 },151 { ip: '66.70.207.89', port: 4002 },152 { ip: '172.110.20.39', port: 4002 },153 { ip: '137.74.47.141', port: 4002 },154 { ip: '167.114.29.41', port: 4002 },155 { ip: '167.114.29.52', port: 4002 },156 { ip: '167.114.43.41', port: 4002 },157 { ip: '51.254.103.18', port: 4002 },158 { ip: '167.114.43.47', port: 4002 },159 { ip: '45.76.136.154', port: 4002 },160 { ip: '167.114.29.39', port: 4002 },161 { ip: '167.114.29.34', port: 4002 },162 { ip: '138.197.165.165', port: 4002 },163 { ip: '167.114.43.34', port: 4002 },164 { ip: '145.239.88.101', port: 4002 },165 { ip: '45.76.245.155', port: 4002 },166 { ip: '167.114.43.43', port: 4002 },167 { ip: '91.134.115.30', port: 4002 },168 { ip: '46.231.204.207', port: 4002 },169 { ip: '167.114.43.46', port: 4002 },170 { ip: '138.197.29.215', port: 4002 },171 { ip: '104.238.177.174', port: 4002 },172 { ip: '109.154.47.137', port: 4002 },173 { ip: '104.207.138.122', port: 4002 },174 { ip: '138.68.21.196', port: 4002 },175 { ip: '167.114.29.36', port: 4002 },176 { ip: '165.227.150.45', port: 4002 },177 { ip: '37.59.70.165', port: 4002 },178 { ip: '94.177.218.138', port: 4002 },179 { ip: '167.114.29.55', port: 4002 },180 { ip: '51.254.201.227', port: 4002 },181 { ip: '167.114.43.48', port: 4002 },182 { ip: '104.154.82.122', port: 4002 },183 { ip: '217.182.78.226', port: 4002 },184 { ip: '207.154.220.137', port: 4002 },185 { ip: '195.181.219.91', port: 4002 },186 { ip: '192.155.91.248', port: 4002 },187 { ip: '167.114.29.53', port: 4002 },188 { ip: '43.224.34.53', port: 4002 },189 { ip: '167.114.43.40', port: 4002 },190 { ip: '138.197.206.43', port: 4002 }191 ]192 },193 /** @type {Network} */194 bitcoin: {195 messagePrefix: '\x18Bitcoin Signed Message:\n',196 bip32: {197 public: 0x0488b21e,198 private: 0x0488ade4199 },200 pubKeyHash: 0x00,201 wif: 0x80202 }...

Full Screen

Full Screen

openolt_statistics.py

Source:openolt_statistics.py Github

copy

Full Screen

...34 # if port_stats.intf_id in [129, 130, 131]:35 # self.log.debug('those uplinks are not created')36 # return37 # # update port object stats38 # port = self.device.adapter_agent.get_port(self.device.device_id,39 # port_no=port_stats.intf_id)40 #41 # if port is None:42 # self.log.warn('port associated with this stats does not exist')43 # return44 #45 # port.rx_packets = port_stats.rx_packets46 # port.rx_bytes = port_stats.rx_bytes47 # port.rx_errors = port_stats.rx_error_packets48 # port.tx_packets = port_stats.tx_packets49 # port.tx_bytes = port_stats.tx_bytes50 # port.tx_errors = port_stats.tx_error_packets51 #52 # # Add port does an update if port exists53 # self.device.adapter_agent.add_port(self.device.device_id, port)54 def flow_statistics_indication(self, flow_stats):55 self.log.info('flow-stats-collected', stats=flow_stats)56 # TODO: send to kafka ?57 # FIXME: etcd problem, do not update objects for now58 # # UNTESTED : the openolt driver does not yet provide flow stats59 # self.device.adapter_agent.update_flow_stats(self.device.logical_device_id,60 # flow_id=flow_stats.flow_id, packet_count=flow_stats.tx_packets,61 # byte_count=flow_stats.tx_bytes)62 def ports_statistics_kpis(self, port_stats):63 pm_data = {}64 pm_data["rx_bytes"] = port_stats.rx_bytes65 pm_data["rx_packets"] = port_stats.rx_packets66 pm_data["rx_ucast_packets"] = port_stats.rx_ucast_packets67 pm_data["rx_mcast_packets"] = port_stats.rx_mcast_packets68 pm_data["rx_bcast_packets"] = port_stats.rx_bcast_packets69 pm_data["rx_error_packets"] = port_stats.rx_error_packets70 pm_data["tx_bytes"] = port_stats.tx_bytes71 pm_data["tx_packets"] = port_stats.tx_packets72 pm_data["tx_ucast_packets"] = port_stats.tx_ucast_packets73 pm_data["tx_mcast_packets"] = port_stats.tx_mcast_packets74 pm_data["tx_bcast_packets"] = port_stats.tx_bcast_packets75 pm_data["tx_error_packets"] = port_stats.tx_error_packets76 pm_data["rx_crc_errors"] = port_stats.rx_crc_errors77 pm_data["bip_errors"] = port_stats.bip_errors78 prefix = 'voltha.openolt.{}'.format(self.device.device_id)79 # FIXME80 if port_stats.intf_id < 132:81 prefixes = {82 prefix + 'nni.{}'.format(port_stats.intf_id): MetricValuePairs(83 metrics=pm_data)84 }85 else:86 prefixes = {87 prefix + '.pon.{}'.format(platform.intf_id_from_pon_port_no(88 port_stats.intf_id)): MetricValuePairs(89 metrics=pm_data)90 }91 kpi_event = KpiEvent(92 type=KpiEventType.slice,93 ts=port_stats.timestamp,94 prefixes=prefixes)95 self.device.adapter_agent.submit_kpis(kpi_event)96 def update_logical_port_stats(self, port_stats):97 # FIXME98 label = 'nni-{}'.format(port_stats.intf_id)99 try:100 logical_port = self.device.adapter_agent.get_logical_port(101 self.device.logical_device_id, label)102 except KeyError as e:103 self.log.warn('logical port was not found, it may not have been '104 'created yet', exception=e)105 return106 if logical_port is None:107 self.log.error('logical-port-is-None',108 logical_device_id=self.device.logical_device_id, label=label,109 port_stats=port_stats)110 return111 logical_port.ofp_port_stats.rx_packets = port_stats.rx_packets112 logical_port.ofp_port_stats.rx_bytes = port_stats.rx_bytes113 logical_port.ofp_port_stats.tx_packets = port_stats.tx_packets114 logical_port.ofp_port_stats.tx_bytes = port_stats.tx_bytes115 logical_port.ofp_port_stats.rx_errors = port_stats.rx_error_packets116 logical_port.ofp_port_stats.tx_errors = port_stats.tx_error_packets117 logical_port.ofp_port_stats.rx_crc_err = port_stats.rx_crc_errors118 self.log.debug('after-stats-update', port=logical_port)119 self.device.adapter_agent.update_logical_port(...

Full Screen

Full Screen

serialport-basic.js

Source:serialport-basic.js Github

copy

Full Screen

1"use strict";2var sinon = require("sinon");3var chai = require('chai');4var expect = chai.expect;5var MockedSerialPort = require('../test_mocks/linux-hardware');6var SerialPort = MockedSerialPort.SerialPort;7var hardware = MockedSerialPort.hardware;8describe('SerialPort', function () {9 var sandbox;10 beforeEach(function () {11 sandbox = sinon.sandbox.create();12 // Create a port for fun and profit13 hardware.reset();14 hardware.createPort('/dev/exists');15 });16 afterEach(function () {17 sandbox.restore();18 });19 describe('Constructor', function () {20 it("opens the port immediately", function (done) {21 var port = new SerialPort('/dev/exists', function (err) {22 expect(err).to.not.be.ok;23 done();24 });25 });26 it('emits an error on the factory when erroring without a callback', function (done) {27 // finish the test on error28 MockedSerialPort.once('error', function (err) {29 chai.assert.isDefined(err, "didn't get an error");30 done();31 });32 var port = new SerialPort('/dev/johnJacobJingleheimerSchmidt');33 });34 it('errors with invalid databits', function (done) {35 var errorCallback = function (err) {36 chai.assert.isDefined(err, 'err is not defined');37 done();38 };39 var port = new SerialPort('/dev/exists', { databits : 19 }, false, errorCallback);40 });41 it('allows optional options', function (done) {42 var cb = function () {};43 var port = new SerialPort('/dev/exists', cb);44 expect(typeof port.options).to.eq('object');45 done();46 });47 });48 describe('reading data', function () {49 it('emits data events by default', function (done) {50 var testData = new Buffer("I am a really short string");51 var port = new SerialPort('/dev/exists', function () {52 port.once('data', function(recvData) {53 expect(recvData).to.eql(testData);54 done();55 });56 hardware.emitData('/dev/exists', testData);57 });58 });59 it('calls the dataCallback if set', function (done) {60 var testData = new Buffer("I am a really short string");61 var opt = {62 dataCallback: function (recvData) {63 expect(recvData).to.eql(testData);64 done();65 }66 };67 var port = new SerialPort('/dev/exists', opt, function () {68 hardware.emitData('/dev/exists', testData);69 });70 });71 });72 describe('#open', function () {73 it('passes the port to the bindings', function (done) {74 var openSpy = sandbox.spy(MockedSerialPort.SerialPortBinding, 'open');75 var port = new SerialPort('/dev/exists', {}, false);76 port.open(function (err) {77 expect(err).to.not.be.ok;78 expect(openSpy.calledWith('/dev/exists'));79 done();80 });81 });82 it('calls back an error when opening an invalid port', function (done) {83 var port = new SerialPort('/dev/unhappy', {}, false);84 port.open(function (err) {85 expect(err).to.be.ok;86 done();87 });88 });89 it("emits data after being reopened", function (done) {90 var data = new Buffer("Howdy!");91 var port = new SerialPort('/dev/exists', function () {92 port.close();93 port.open(function () {94 port.once('data', function (res) {95 expect(res).to.eql(data);96 done();97 });98 hardware.emitData('/dev/exists', data);99 });100 });101 });102 });103 describe('close', function () {104 it("fires a close event when it's closed", function (done) {105 var port = new SerialPort('/dev/exists', function () {106 var closeSpy = sandbox.spy();107 port.on('close', closeSpy);108 port.close();109 expect(closeSpy.calledOnce);110 done();111 });112 });113 it("fires a close event after being reopened", function (done) {114 var port = new SerialPort('/dev/exists', function () {115 var closeSpy = sandbox.spy();116 port.on('close', closeSpy);117 port.close();118 port.open();119 port.close();120 expect(closeSpy.calledTwice);121 done();122 });123 });124 });125 describe('disconnect', function () {126 it("fires a disconnect event", function (done) {127 var port = new SerialPort('/dev/exists', {128 disconnectedCallback: function (err) {129 expect(err).to.not.be.ok;130 done();131 }132 }, function () {133 hardware.disconnect('/dev/exists');134 });135 });136 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const port = fc.integer(0, 65535);3fc.assert(4 fc.property(port, (p) => {5 return p >= 0 && p <= 65535;6 }),7 { verbose: true }8);9const fc = require('fast-check');10const port = fc.integer(0, 65535);11fc.assert(12 fc.property(port, (p) => {13 return p >= 0 && p <= 65535;14 }),15 { verbose: true }16);17const fc = require('fast-check');18const port = fc.integer(0, 65535);19fc.assert(20 fc.property(port, (p) => {21 return p >= 0 && p <= 65535;22 }),23 { verbose: true }24);25const fc = require('fast-check');26const port = fc.integer(0, 65535);27fc.assert(28 fc.property(port, (p) => {29 return p >= 0 && p <= 65535;30 }),31 { verbose: true }32);33const fc = require('fast-check');34const port = fc.integer(0, 65535);35fc.assert(36 fc.property(port, (p) => {37 return p >= 0 && p <= 65535;38 }),39 { verbose: true }40);41const fc = require('fast-check');42const port = fc.integer(0, 65535);43fc.assert(44 fc.property(port, (p) => {45 return p >= 0 && p <= 65535;46 }),47 { verbose: true }48);49const fc = require('fast-check');50const port = fc.integer(0, 65535);51fc.assert(52 fc.property(port, (p) => {53 return p >= 0 && p <= 65535;54 }),

Full Screen

Using AI Code Generation

copy

Full Screen

1const { port } = require('fast-check-monorepo');2const fc = require('fast-check');3const { port } = require('fast-check-monorepo');4const fc = require('fast-check');5const arb = port();6fc.assert(7 fc.property(arb, (p) => {8 console.log(p);9 return true;10 })11);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { port } from 'fast-check-monorepo'2console.log(port(1, 1000))3import { port } from 'fast-check-monorepo'4console.log(port(1, 1000))5import { port } from 'fast-check-monorepo'6console.log(port(1, 1000))7import { port } from 'fast-check-monorepo'8console.log(port(1, 1000))9import { port } from 'fast-check-monorepo'10console.log(port(1, 1000))11import { port } from 'fast-check-monorepo'12console.log(port(1, 1000))13import { port } from 'fast-check-monorepo'14console.log(port(1, 1000))15import { port } from 'fast-check-monorepo'16console.log(port(1, 1000))17import { port } from 'fast-check-monorepo'18console.log(port(1, 1000))19import { port } from 'fast-check-monorepo'20console.log(port(1, 1000))21import { port } from 'fast-check-monorepo'22console.log(port(1, 1000))23import { port } from 'fast-check-monorepo'24console.log(port(1, 1000))

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { port } = require('fast-check-monorepo');3const isPort = port();4fc.assert(5 fc.property(fc.integer(), (n) => {6 console.log(n);7 return isPort(n);8 })9);10const fc = require('fast-check');11const { port } = require('fast-check-monorepo');12const isPort = port();13fc.assert(14 fc.property(fc.integer(), (n) => {15 console.log(n);16 return isPort(n);17 })18);19const fc = require('fast-check');20const { port } = require('fast-check-monorepo');21const isPort = port();22fc.assert(23 fc.property(fc.integer(), (n) => {24 console.log(n);25 return isPort(n);26 })27);28const fc = require('fast-check');29const { port } = require('fast-check-monorepo');30const isPort = port();31fc.assert(32 fc.property(fc.integer(), (n) => {33 console.log(n);34 return isPort(n);35 })36);37const fc = require('fast-check');38const { port } = require('fast-check-monorepo');39const isPort = port();40fc.assert(41 fc.property(fc.integer(), (n) => {42 console.log(n);43 return isPort(n);44 })45);46const fc = require('fast-check');47const { port } = require('fast-check-monorepo');48const isPort = port();49fc.assert(50 fc.property(fc.integer(), (n) => {51 console.log(n);52 return isPort(n);53 })54);55const fc = require('fast-check');56const { port } = require('fast-check-monorepo');57const isPort = port();58fc.assert(59 fc.property(fc.integer(), (n) => {60 console.log(n);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { port } from "fast-check-monorepo";2import { port } from "fast-check-monorepo";3import { port } from "fast-check-monorepo";4import { port } from "fast-check-monorepo";5import { port } from "fast-check-monorepo";6import { port } from "fast-check-monorepo";7import { port } from "fast-check-monorepo";8import { port } from "fast-check-monorepo";9import { port } from "fast-check-monorepo";10import { port } from "fast-check-monorepo";

Full Screen

Using AI Code Generation

copy

Full Screen

1const { port } = require('fast-check')2const { port: port2 } = require('fast-check-monorepo')3console.log(port)4console.log(port2)5console.log(port === port2)6 at Object.<anonymous> (test3.js:6:13)7 at Module._compile (internal/modules/cjs/loader.js:999:30)8 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)9 at Module.load (internal/modules/cjs/loader.js:863:32)10 at Function.Module._load (internal/modules/cjs/loader.js:708:14)11 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)12const { port } = require('fast-check');13console.log(port);14const { port } = require('fast-check-monorepo');15console.log(port);16const { port } = require('fast-check');17const { port: port2 } = require('fast-check-monorepo');18console.log(port);19console.log(port2);20console.log(port === port2);21I've run the following commands (node v12.19.0):

Full Screen

Using AI Code Generation

copy

Full Screen

1const { port } = require('fast-check');2describe('port method', () => {3 it('should return a valid port number', () => {4 const portNumber = port().next().value;5 expect(portNumber).toBeGreaterThanOrEqual(1);6 expect(portNumber).toBeLessThanOrEqual(65535);7 });8});9const { domain } = require('fast-check');10describe('domain method', () => {11 it('should return a valid domain name', () => {12 const domainName = domain().next().value;13 expect(domainName).toMatch(/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/);14 });15});16const { ipv4 } = require('fast-check');17describe('ipv4 method', () => {18 it('should return a valid ipv4 address', () => {19 const ipv4Address = ipv4().next().value;20 expect(ipv4Address).toMatch(21 /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,22 );23 });24});25const { ipv6 } = require('fast-check');26describe('ipv6 method', () => {27 it('should return a valid ipv6 address', () => {28 const ipv6Address = ipv6().next().value;29 expect(ip

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { port } = require('fast-check-monorepo');3const portGen = port();4console.log(portGen);5const portProp = fc.property(portGen, (p) => {6if (p === 0) {7return true;8}9return p > 0 && p < 65536;10});11fc.assert(portProp);12I was able to use the port method of fast-check-monorepo in my test3.js file. I was able to generate port numbers and assert that they were within the correct range. I was able to use the port method in my test3.js file because I imported the port method from the fast-check-monorepo library. I was able to import the port method from the fast-check-monorepo library because I installed the fast-check-mon

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2fc.assert(3 fc.property(fc.integer(), fc.integer(), (a, b) => {4 return a + b >= a;5 })6);7"exports": {8 ".": {9 "import": "./lib/src/index.js",10 }11 },12 throw new ERR_REQUIRE_ESM(filename);13Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\james\Documents\GitHub\fast-check-monorepo\lib\cjs\src\index.js14 at new NodeError (node:internal/errors:329:5)15 at Object.Module._extensions..js (node:internal/modules/cjs/loader:1167:13)16 at Module.load (node:internal/modules/cjs/loader:996:32)17 at Function.Module._load (node:internal/modules/cjs/loader:896:14)18 at Module.require (node:internal/modules/cjs/loader:1033:19)19 at require (node:internal/modules/cjs/helpers:72:18)20 at Object.<anonymous> (C:\Users\james\Documents\GitHub\

Full Screen

Using AI Code Generation

copy

Full Screen

1const port = require('fast-check-monorepo');2console.log(port());3console.log(port(1, 2, 3));4console.log(port(1, 2, 3, 4));5console.log(port(1, 2, 3, 4, 5));6console.log(port(1, 2, 3, 4, 5, 6));7console.log(port(1, 2, 3, 4, 5, 6, 7));8console.log(port(1, 2, 3, 4, 5, 6, 7, 8));9console.log(port(1, 2, 3, 4, 5, 6, 7, 8, 9));10console.log(port(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));11console.log(port(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));12console.log(port(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12));13console.log(port(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13));14console.log(port(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14));15console.log(port(1, 2

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 fast-check-monorepo 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