content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
replace string replace with string templates
35ee7c8246d819f5963ec2ea9a6f3a9697c5507c
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleJniH.js <ide> type FilesOutput = Map<string, string>; <ide> <ide> const {getModules} = require('./Utils'); <ide> <del>const moduleSpecTemplate = `/** <del> * JNI C++ class for module '::_HASTE_MODULE_NAME_::' <add>const ModuleClassDeclarationTemplate = ({ <add> hasteModuleName, <add>}: $ReadOnly<{|hasteModuleName: string|}>) => { <add> return `/** <add> * JNI C++ class for module '${hasteModuleName}' <ide> */ <del>class JSI_EXPORT ::_HASTE_MODULE_NAME_::SpecJSI : public JavaTurboModule { <add>class JSI_EXPORT ${hasteModuleName}SpecJSI : public JavaTurboModule { <ide> public: <del> ::_HASTE_MODULE_NAME_::SpecJSI(const JavaTurboModule::InitParams &params); <add> ${hasteModuleName}SpecJSI(const JavaTurboModule::InitParams &params); <ide> }; <ide> `; <add>}; <ide> <del>const template = ` <add>const HeaderFileTemplate = ({ <add> modules, <add> libraryName, <add>}: $ReadOnly<{|modules: string, libraryName: string|}>) => { <add> return ` <ide> /** <ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates. <ide> * <ide> const template = ` <ide> namespace facebook { <ide> namespace react { <ide> <del>::_MODULES_:: <add>${modules} <ide> <del>std::shared_ptr<TurboModule> ::_LIBRARY_NAME_::_ModuleProvider(const std::string moduleName, const JavaTurboModule::InitParams &params); <add>std::shared_ptr<TurboModule> ${libraryName}_ModuleProvider(const std::string moduleName, const JavaTurboModule::InitParams &params); <ide> <ide> } // namespace react <ide> } // namespace facebook <ide> `; <add>}; <ide> <del>const androidMkTemplate = `# Copyright (c) Facebook, Inc. and its affiliates. <add>const AndroidMkTemplate = ({libraryName}: $ReadOnly<{libraryName: string}>) => { <add> return `# Copyright (c) Facebook, Inc. and its affiliates. <ide> # <ide> # This source code is licensed under the MIT license found in the <ide> # LICENSE file in the root directory of this source tree. <ide> LOCAL_PATH := $(call my-dir) <ide> <ide> include $(CLEAR_VARS) <ide> <del>LOCAL_MODULE := ::_LIBRARY_NAME_:: <add>LOCAL_MODULE := ${libraryName} <ide> <ide> LOCAL_C_INCLUDES := $(LOCAL_PATH) <ide> <ide> LOCAL_CFLAGS += -fexceptions -frtti -std=c++14 -Wall <ide> <ide> include $(BUILD_SHARED_LIBRARY) <ide> `; <add>}; <ide> <ide> module.exports = { <ide> generate( <ide> module.exports = { <ide> ); <ide> }) <ide> .sort() <del> .map(hasteModuleName => <del> moduleSpecTemplate.replace(/::_HASTE_MODULE_NAME_::/g, hasteModuleName), <del> ) <add> .map(hasteModuleName => ModuleClassDeclarationTemplate({hasteModuleName})) <ide> .join('\n'); <ide> <ide> const fileName = `${moduleSpecName}.h`; <del> const replacedTemplate = template <del> .replace(/::_MODULES_::/g, modules) <del> .replace(/::_LIBRARY_NAME_::/g, libraryName); <add> const replacedTemplate = HeaderFileTemplate({ <add> modules: modules, <add> libraryName: libraryName, <add> }); <ide> return new Map([ <ide> [fileName, replacedTemplate], <ide> [ <ide> 'Android.mk', <del> androidMkTemplate.replace( <del> /::_LIBRARY_NAME_::/g, <del> `react_codegen_${libraryName.toLowerCase()}`, <del> ), <add> AndroidMkTemplate({ <add> libraryName: `react_codegen_${libraryName.toLowerCase()}`, <add> }), <ide> ], <ide> ]); <ide> },
1
Text
Text
remove redundant chown commands
5f29dee138a2478f89480710af3905546fa98368
<ide><path>share/doc/homebrew/El_Capitan_and_Homebrew.md <ide> This is how to fix Homebrew on El Capitan if you see permission issues: <ide> ## If `/usr/local` exists already: <ide> <ide> ```bash <del>sudo chown $(whoami):admin /usr/local && sudo chown -R $(whoami):admin /usr/local <add>sudo chown -R $(whoami):admin /usr/local <ide> ``` <ide> <ide> ## If `/usr/local` does not exist: <ide> sudo chown $(whoami):admin /usr/local && sudo chown -R $(whoami):admin /usr/loca <ide> * Open your Terminal application and execute: <ide> <ide> ```bash <del> sudo mkdir /usr/local && sudo chflags norestricted /usr/local && sudo chown $(whoami):admin /usr/local && sudo chown -R $(whoami):admin /usr/local <add> sudo mkdir /usr/local && sudo chflags norestricted /usr/local && sudo chown -R $(whoami):admin /usr/local <ide> ``` <ide> <ide> * Reboot back into Recovery Mode & access the Terminal again.
1
Javascript
Javascript
improve buffer.readint(b|l)e benchmarks
94d64877ff2b9d5fcfb40d24358337a95c333f66
<ide><path>benchmark/buffers/buffer-read-with-byteLength.js <add>'use strict'; <add>const common = require('../common.js'); <add> <add>const types = [ <add> 'IntLE', <add> 'IntBE', <add>]; <add> <add>const bench = common.createBenchmark(main, { <add> noAssert: ['false', 'true'], <add> buffer: ['fast', 'slow'], <add> type: types, <add> millions: [1], <add> byteLength: [1, 2, 4, 6] <add>}); <add> <add>function main(conf) { <add> const noAssert = conf.noAssert === 'true'; <add> const len = conf.millions * 1e6; <add> const clazz = conf.buf === 'fast' ? Buffer : require('buffer').SlowBuffer; <add> const buff = new clazz(8); <add> const type = conf.type || 'UInt8'; <add> const fn = `read${type}`; <add> <add> buff.writeDoubleLE(0, 0, noAssert); <add> const testFunction = new Function('buff', ` <add> for (var i = 0; i !== ${len}; i++) { <add> buff.${fn}(0, ${conf.byteLength}, ${JSON.stringify(noAssert)}); <add> } <add> `); <add> bench.start(); <add> testFunction(buff); <add> bench.end(len / 1e6); <add>} <ide><path>benchmark/buffers/buffer-read.js <ide> const types = [ <ide> 'FloatLE', <ide> 'FloatBE', <ide> 'DoubleLE', <del> 'DoubleBE', <del> 'IntLE', <del> 'IntBE', <add> 'DoubleBE' <ide> ]; <ide> <ide> const bench = common.createBenchmark(main, { <ide> function main(conf) { <ide> const fn = `read${type}`; <ide> <ide> buff.writeDoubleLE(0, 0, noAssert); <del> <del> var call; <del> if (fn === 'readIntLE' || fn === 'readIntBE') { <del> call = `buff.${fn}(0, 1, ${JSON.stringify(noAssert)})`; <del> } else { <del> call = `buff.${fn}(0, ${JSON.stringify(noAssert)})`; <del> } <del> <del> const testFunction = new Function( <del> 'buff', <del> `for (var i = 0; i !== ${len}; ++i) { ${call}; }` <del> ); <del> <add> const testFunction = new Function('buff', ` <add> for (var i = 0; i !== ${len}; i++) { <add> buff.${fn}(0, ${JSON.stringify(noAssert)}); <add> } <add> `); <ide> bench.start(); <ide> testFunction(buff); <ide> bench.end(len / 1e6); <ide><path>test/sequential/test-benchmark-buffer.js <ide> runBenchmark('buffers', <ide> 'aligned=true', <ide> 'args=1', <ide> 'buffer=fast', <add> 'byteLength=1', <ide> 'encoding=utf8', <add> 'endian=BE', <ide> 'len=2', <ide> 'method=', <ide> 'n=1', <ide> runBenchmark('buffers', <ide> 'size=1', <ide> 'source=array', <ide> 'type=', <add> 'value=0', <ide> 'withTotalLength=0' <ide> ], <ide> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
3
Javascript
Javascript
add glsl annotation
a48a395a0327b35bca6cd5013cca22f2f7d33f5b
<ide><path>examples/jsm/shaders/MMDToonShader.js <ide> <ide> import { UniformsUtils, ShaderLib } from 'three'; <ide> <del>const lights_mmd_toon_pars_fragment = ` <add>const lights_mmd_toon_pars_fragment = /* glsl */` <ide> varying vec3 vViewPosition; <ide> <ide> struct BlinnPhongMaterial { <ide> void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in Geometric <ide> #define Material_LightProbeLOD( material ) (0) <ide> `; <ide> <del>const mmd_toon_matcap_fragment = ` <add>const mmd_toon_matcap_fragment = /* glsl */` <ide> #ifdef USE_MATCAP <ide> <ide> vec3 viewDir = normalize( vViewPosition );
1
Javascript
Javascript
reuse tls sessions in agent
2ca5a3db47b930912161074c7b514c769113433b
<ide><path>lib/_http_agent.js <ide> Agent.prototype.createSocket = function(req, options) { <ide> } <ide> <ide> var name = self.getName(options); <add> options._agentKey = name; <ide> <ide> debug('createConnection', name, options); <ide> options.encoding = null; <ide><path>lib/_tls_wrap.js <ide> TLSSocket.prototype._start = function() { <ide> this._handle.start(); <ide> }; <ide> <add>TLSSocket.prototype._isSessionResumed = function _isSessionResumed(session) { <add> if (!session) <add> return false; <add> <add> var next = this.getSession(); <add> if (!next) <add> return false; <add> <add> return next.equals(session); <add>}; <add> <ide> TLSSocket.prototype.setServername = function(name) { <ide> this._handle.setServername(name); <ide> }; <ide> exports.connect = function(/* [port, host], options, cb */) { <ide> var verifyError = socket._handle.verifyError(); <ide> <ide> // Verify that server's identity matches it's certificate's names <del> if (!verifyError) { <add> // Unless server has resumed our existing session <add> if (!verifyError && !socket._isSessionResumed(options.session)) { <ide> var cert = socket.getPeerCertificate(); <ide> verifyError = options.checkServerIdentity(hostname, cert); <ide> } <ide><path>lib/https.js <ide> function createConnection(port, host, options) { <ide> } <ide> <ide> debug('createConnection', options); <del> return tls.connect(options); <add> <add> if (options._agentKey) { <add> const session = this._getSession(options._agentKey); <add> if (session) { <add> debug('reuse session for %j', options._agentKey); <add> options = util._extend({ <add> session: session <add> }, options); <add> } <add> } <add> <add> const self = this; <add> const socket = tls.connect(options, function() { <add> if (!options._agentKey) <add> return; <add> <add> self._cacheSession(options._agentKey, socket.getSession()); <add> }); <add> return socket; <ide> } <ide> <ide> <ide> function Agent(options) { <ide> http.Agent.call(this, options); <ide> this.defaultPort = 443; <ide> this.protocol = 'https:'; <add> this.maxCachedSessions = this.options.maxCachedSessions; <add> if (this.maxCachedSessions === undefined) <add> this.maxCachedSessions = 100; <add> <add> this._sessionCache = { <add> map: {}, <add> list: [] <add> }; <ide> } <ide> inherits(Agent, http.Agent); <ide> Agent.prototype.createConnection = createConnection; <ide> Agent.prototype.getName = function(options) { <ide> return name; <ide> }; <ide> <add>Agent.prototype._getSession = function _getSession(key) { <add> return this._sessionCache.map[key]; <add>}; <add> <add>Agent.prototype._cacheSession = function _cacheSession(key, session) { <add> // Fast case - update existing entry <add> if (this._sessionCache.map[key]) { <add> this._sessionCache.map[key] = session; <add> return; <add> } <add> <add> // Put new entry <add> if (this._sessionCache.list.length >= this.maxCachedSessions) { <add> const oldKey = this._sessionCache.list.shift(); <add> debug('evicting %j', oldKey); <add> delete this._sessionCache.map[oldKey]; <add> } <add> <add> this._sessionCache.list.push(key); <add> this._sessionCache.map[key] = session; <add>}; <add> <ide> const globalAgent = new Agent(); <ide> <ide> exports.globalAgent = globalAgent; <ide><path>test/parallel/test-https-agent-session-reuse.js <add>'use strict'; <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>if (!common.hasCrypto) { <add> console.log('1..0 # Skipped: missing crypto'); <add> return; <add>} <add> <add>var https = require('https'); <add>var crypto = require('crypto'); <add> <add>var fs = require('fs'); <add> <add>var options = { <add> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <add> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <add>}; <add> <add>var ca = fs.readFileSync(common.fixturesDir + '/keys/ca1-cert.pem'); <add> <add>var clientSessions = {}; <add>var serverRequests = 0; <add> <add>var agent = new https.Agent({ <add> maxCachedSessions: 1 <add>}); <add> <add>var server = https.createServer(options, function(req, res) { <add> if (req.url === '/drop-key') <add> server.setTicketKeys(crypto.randomBytes(48)); <add> <add> serverRequests++; <add> res.end('ok'); <add>}).listen(common.PORT, function() { <add> var queue = [ <add> { <add> name: 'first', <add> <add> method: 'GET', <add> path: '/', <add> servername: 'agent1', <add> ca: ca, <add> port: common.PORT <add> }, <add> { <add> name: 'first-reuse', <add> <add> method: 'GET', <add> path: '/', <add> servername: 'agent1', <add> ca: ca, <add> port: common.PORT <add> }, <add> { <add> name: 'cipher-change', <add> <add> method: 'GET', <add> path: '/', <add> servername: 'agent1', <add> <add> // Choose different cipher to use different cache entry <add> ciphers: 'AES256-SHA', <add> ca: ca, <add> port: common.PORT <add> }, <add> // Change the ticket key to ensure session is updated in cache <add> { <add> name: 'before-drop', <add> <add> method: 'GET', <add> path: '/drop-key', <add> servername: 'agent1', <add> ca: ca, <add> port: common.PORT <add> }, <add> <add> // Ticket will be updated starting from this <add> { <add> name: 'after-drop', <add> <add> method: 'GET', <add> path: '/', <add> servername: 'agent1', <add> ca: ca, <add> port: common.PORT <add> }, <add> { <add> name: 'after-drop-reuse', <add> <add> method: 'GET', <add> path: '/', <add> servername: 'agent1', <add> ca: ca, <add> port: common.PORT <add> } <add> ]; <add> <add> function request() { <add> var options = queue.shift(); <add> options.agent = agent; <add> https.request(options, function(res) { <add> clientSessions[options.name] = res.socket.getSession(); <add> <add> res.resume(); <add> res.on('end', function() { <add> if (queue.length !== 0) <add> return request(); <add> server.close(); <add> }); <add> }).end(); <add> } <add> request(); <add>}); <add> <add>process.on('exit', function() { <add> assert.equal(serverRequests, 6); <add> assert.equal(clientSessions['first'].toString('hex'), <add> clientSessions['first-reuse'].toString('hex')); <add> assert.notEqual(clientSessions['first'].toString('hex'), <add> clientSessions['cipher-change'].toString('hex')); <add> assert.notEqual(clientSessions['first'].toString('hex'), <add> clientSessions['before-drop'].toString('hex')); <add> assert.notEqual(clientSessions['cipher-change'].toString('hex'), <add> clientSessions['before-drop'].toString('hex')); <add> assert.notEqual(clientSessions['before-drop'].toString('hex'), <add> clientSessions['after-drop'].toString('hex')); <add> assert.equal(clientSessions['after-drop'].toString('hex'), <add> clientSessions['after-drop-reuse'].toString('hex')); <add>});
4
PHP
PHP
use reflection api instead of array diffs
29e1667b994e32debe9ed1053f81ca7905cf04ff
<ide><path>src/Shell/Task/TestTask.php <ide> use Cake\ORM\Table; <ide> use Cake\ORM\TableRegistry; <ide> use Cake\Utility\Inflector; <add>use ReflectionClass; <ide> <ide> /** <ide> * Task class for creating and updating test files. <ide> public function mapType($type) { <ide> * @return array Array of method names. <ide> */ <ide> public function getTestableMethods($className) { <del> $classMethods = get_class_methods($className); <del> $parentMethods = get_class_methods(get_parent_class($className)); <del> $thisMethods = array_diff($classMethods, $parentMethods); <add> $class = new ReflectionClass($className); <ide> $out = []; <del> foreach ($thisMethods as $method) { <del> if (substr($method, 0, 1) !== '_' && $method != strtolower($className)) { <del> $out[] = $method; <add> foreach ($class->getMethods() as $method) { <add> if ($method->getDeclaringClass()->getName() != $className) { <add> continue; <add> } <add> if (!$method->isPublic()) { <add> continue; <ide> } <add> $out[] = $method->getName(); <ide> } <ide> return $out; <ide> } <ide><path>tests/TestCase/Shell/Task/TestTaskTest.php <ide> public function testOutputClassOptionsForTablePlugin() { <ide> */ <ide> public function testMethodIntrospection() { <ide> $result = $this->Task->getTestableMethods('TestApp\Model\Table\ArticlesTable'); <del> $expected = ['findpublished', 'dosomething', 'dosomethingelse']; <add> $expected = ['initialize', 'findpublished', 'dosomething', 'dosomethingelse']; <ide> $this->assertEquals($expected, array_map('strtolower', $result)); <ide> } <ide>
2
Python
Python
allow custom code for processors
45f56580a7e11b5b894374f8e1c7bdd54d982682
<ide><path>src/transformers/dynamic_module_utils.py <ide> def custom_object_save(obj, folder, config=None): <ide> "this code in a separate module so we can include it in the saved folder and make it easier to share via " <ide> "the Hub." <ide> ) <del> # Add object class to the config auto_map <del> if config is not None: <add> <add> def _set_auto_map_in_config(_config): <ide> module_name = obj.__class__.__module__ <ide> last_module = module_name.split(".")[-1] <ide> full_name = f"{last_module}.{obj.__class__.__name__}" <ide> def custom_object_save(obj, folder, config=None): <ide> <ide> full_name = (slow_tokenizer_class, fast_tokenizer_class) <ide> <del> if isinstance(config, dict): <del> config["auto_map"] = full_name <del> elif getattr(config, "auto_map", None) is not None: <del> config.auto_map[obj._auto_class] = full_name <add> if isinstance(_config, dict): <add> auto_map = _config.get("auto_map", {}) <add> auto_map[obj._auto_class] = full_name <add> _config["auto_map"] = auto_map <add> elif getattr(_config, "auto_map", None) is not None: <add> _config.auto_map[obj._auto_class] = full_name <ide> else: <del> config.auto_map = {obj._auto_class: full_name} <add> _config.auto_map = {obj._auto_class: full_name} <add> <add> # Add object class to the config auto_map <add> if isinstance(config, (list, tuple)): <add> for cfg in config: <add> _set_auto_map_in_config(cfg) <add> elif config is not None: <add> _set_auto_map_in_config(config) <ide> <ide> # Copy module file to the output folder. <ide> object_file = sys.modules[obj.__module__].__file__ <ide><path>src/transformers/models/auto/processing_auto.py <ide> <ide> # Build the list of all feature extractors <ide> from ...configuration_utils import PretrainedConfig <add>from ...dynamic_module_utils import get_class_from_dynamic_module <ide> from ...feature_extraction_utils import FeatureExtractionMixin <ide> from ...file_utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo <ide> from ...tokenization_utils import TOKENIZER_CONFIG_FILE <add>from ...utils import logging <ide> from .auto_factory import _LazyAutoMapping <ide> from .configuration_auto import ( <ide> CONFIG_MAPPING_NAMES, <ide> AutoConfig, <del> config_class_to_model_type, <ide> model_type_to_module_name, <ide> replace_list_option_in_docstrings, <ide> ) <ide> <ide> <add>logger = logging.get_logger(__name__) <add> <ide> PROCESSOR_MAPPING_NAMES = OrderedDict( <ide> [ <ide> ("clip", "CLIPProcessor"), <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary <ide> consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of <ide> `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored. <add> trust_remote_code (`bool`, *optional*, defaults to `False`): <add> Whether or not to allow for custom models defined on the Hub in their own modeling files. This option <add> should only be set to `True` for repositories you trust and in which you have read the code, as it will <add> execute code present on the Hub on your local machine. <ide> kwargs (`Dict[str, Any]`, *optional*): <ide> The values in kwargs of any keys which are feature extractor attributes will be used to override the <ide> loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> >>> processor = AutoProcessor.from_pretrained("./test/saved_model/") <ide> ```""" <ide> config = kwargs.pop("config", None) <add> trust_remote_code = kwargs.pop("trust_remote_code", False) <ide> kwargs["_from_auto"] = True <ide> <add> processor_class = None <add> processor_auto_map = None <add> <ide> # First, let's see if we have a preprocessor config. <del> # Filter the kwargs for `get_file_from_repo``. <add> # Filter the kwargs for `get_file_from_repo`. <ide> get_file_from_repo_kwargs = { <ide> key: kwargs[key] for key in inspect.signature(get_file_from_repo).parameters.keys() if key in kwargs <ide> } <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> ) <ide> if preprocessor_config_file is not None: <ide> config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs) <del> if "processor_class" in config_dict: <del> processor_class = processor_class_from_name(config_dict["processor_class"]) <del> return processor_class.from_pretrained(pretrained_model_name_or_path, **kwargs) <del> <del> # Next, let's check whether the processor class is saved in a tokenizer <del> # Let's start by checking whether the processor class is saved in a feature extractor <del> tokenizer_config_file = get_file_from_repo( <del> pretrained_model_name_or_path, TOKENIZER_CONFIG_FILE, **get_file_from_repo_kwargs <del> ) <del> if tokenizer_config_file is not None: <del> with open(tokenizer_config_file, encoding="utf-8") as reader: <del> config_dict = json.load(reader) <del> <del> if "processor_class" in config_dict: <del> processor_class = processor_class_from_name(config_dict["processor_class"]) <del> return processor_class.from_pretrained(pretrained_model_name_or_path, **kwargs) <del> <del> # Otherwise, load config, if it can be loaded. <del> if not isinstance(config, PretrainedConfig): <del> config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <del> <del> model_type = config_class_to_model_type(type(config).__name__) <del> <del> if getattr(config, "processor_class", None) is not None: <del> processor_class = processor_class_from_name(config.processor_class) <del> return processor_class.from_pretrained(pretrained_model_name_or_path, **kwargs) <del> <del> model_type = config_class_to_model_type(type(config).__name__) <del> if model_type is not None: <add> processor_class = config_dict.get("processor_class", None) <add> if "AutoProcessor" in config_dict.get("auto_map", {}): <add> processor_auto_map = config_dict["auto_map"]["AutoProcessor"] <add> <add> if processor_class is None: <add> # Next, let's check whether the processor class is saved in a tokenizer <add> tokenizer_config_file = get_file_from_repo( <add> pretrained_model_name_or_path, TOKENIZER_CONFIG_FILE, **get_file_from_repo_kwargs <add> ) <add> if tokenizer_config_file is not None: <add> with open(tokenizer_config_file, encoding="utf-8") as reader: <add> config_dict = json.load(reader) <add> <add> processor_class = config_dict.get("processor_class", None) <add> if "AutoProcessor" in config_dict.get("auto_map", {}): <add> processor_auto_map = config_dict["auto_map"]["AutoProcessor"] <add> <add> if processor_class is None: <add> # Otherwise, load config, if it can be loaded. <add> if not isinstance(config, PretrainedConfig): <add> config = AutoConfig.from_pretrained( <add> pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs <add> ) <add> <add> # And check if the config contains the processor class. <add> processor_class = getattr(config, "processor_class", None) <add> if hasattr(config, "auto_map") and "AutoProcessor" in config.auto_map: <add> processor_auto_map = config.auto_map["AutoProcessor"] <add> <add> if processor_class is not None: <add> # If we have custom code for a feature extractor, we get the proper class. <add> if processor_auto_map is not None: <add> if not trust_remote_code: <add> raise ValueError( <add> f"Loading {pretrained_model_name_or_path} requires you to execute the feature extractor file " <add> "in that repo on your local machine. Make sure you have read the code there to avoid " <add> "malicious use, then set the option `trust_remote_code=True` to remove this error." <add> ) <add> if kwargs.get("revision", None) is None: <add> logger.warning( <add> "Explicitly passing a `revision` is encouraged when loading a feature extractor with custom " <add> "code to ensure no malicious code has been contributed in a newer revision." <add> ) <add> <add> module_file, class_name = processor_auto_map.split(".") <add> processor_class = get_class_from_dynamic_module( <add> pretrained_model_name_or_path, module_file + ".py", class_name, **kwargs <add> ) <add> else: <add> processor_class = processor_class_from_name(processor_class) <add> <add> return processor_class.from_pretrained( <add> pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs <add> ) <add> <add> # Last try: we use the PROCESSOR_MAPPING. <add> if type(config) in PROCESSOR_MAPPING: <ide> return PROCESSOR_MAPPING[type(config)].from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> <ide> raise ValueError( <ide><path>src/transformers/models/auto/tokenization_auto.py <ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): <ide> # Next, let's try to use the tokenizer_config file to get the tokenizer class. <ide> tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs) <ide> config_tokenizer_class = tokenizer_config.get("tokenizer_class") <del> tokenizer_auto_map = tokenizer_config.get("auto_map") <add> tokenizer_auto_map = None <add> if "auto_map" in tokenizer_config: <add> if isinstance(tokenizer_config["auto_map"], (tuple, list)): <add> # Legacy format for dynamic tokenizers <add> tokenizer_auto_map = tokenizer_config["auto_map"] <add> else: <add> tokenizer_auto_map = tokenizer_config["auto_map"].get("AutoTokenizer", None) <ide> <ide> # If that did not work, let's try to use the config. <ide> if config_tokenizer_class is None: <ide><path>src/transformers/processing_utils.py <ide> """ <ide> <ide> import importlib.util <add>import os <ide> from pathlib import Path <ide> <add>from .dynamic_module_utils import custom_object_save <add>from .tokenization_utils_base import PreTrainedTokenizerBase <ide> <del># Comment to write <add> <add># Dynamically import the Transformers module to grab the attribute classes of the processor form their names. <ide> spec = importlib.util.spec_from_file_location( <ide> "transformers", Path(__file__).parent / "__init__.py", submodule_search_locations=[Path(__file__).parent] <ide> ) <ide> class ProcessorMixin: <ide> # Names need to be attr_class for attr in attributes <ide> feature_extractor_class = None <ide> tokenizer_class = None <add> _auto_class = None <ide> <ide> # args have to match the attributes class attribute <ide> def __init__(self, *args, **kwargs): <ide> def save_pretrained(self, save_directory): <ide> Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will <ide> be created if it does not exist). <ide> """ <add> os.makedirs(save_directory, exist_ok=True) <add> # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be <add> # loaded from the Hub. <add> if self._auto_class is not None: <add> attrs = [getattr(self, attribute_name) for attribute_name in self.attributes] <add> configs = [(a.init_kwargs if isinstance(a, PreTrainedTokenizerBase) else a) for a in attrs] <add> custom_object_save(self, save_directory, config=configs) <add> <ide> for attribute_name in self.attributes: <ide> attribute = getattr(self, attribute_name) <ide> # Include the processor class in the attribute config so this processor can then be reloaded with the <ide> def save_pretrained(self, save_directory): <ide> attribute._set_processor_class(self.__class__.__name__) <ide> attribute.save_pretrained(save_directory) <ide> <add> if self._auto_class is not None: <add> # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up. <add> for attribute_name in self.attributes: <add> attribute = getattr(self, attribute_name) <add> if isinstance(attribute, PreTrainedTokenizerBase): <add> del attribute.init_kwargs["auto_map"] <add> <ide> @classmethod <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> r""" <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> args = cls._get_arguments_from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> return cls(*args) <ide> <add> @classmethod <add> def register_for_auto_class(cls, auto_class="AutoProcessor"): <add> """ <add> Register this class with a given auto class. This should only be used for custom feature extractors as the ones <add> in the library are already mapped with `AutoProcessor`. <add> <add> <Tip warning={true}> <add> <add> This API is experimental and may have some slight breaking changes in the next releases. <add> <add> </Tip> <add> <add> Args: <add> auto_class (`str` or `type`, *optional*, defaults to `"AutoProcessor"`): <add> The auto class to register this new feature extractor with. <add> """ <add> if not isinstance(auto_class, str): <add> auto_class = auto_class.__name__ <add> <add> import transformers.models.auto as auto_module <add> <add> if not hasattr(auto_module, auto_class): <add> raise ValueError(f"{auto_class} is not a valid auto class.") <add> <add> cls._auto_class = auto_class <add> <ide> @classmethod <ide> def _get_arguments_from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> args = [] <ide><path>tests/test_feature_extraction_common.py <ide> if is_vision_available(): <ide> from PIL import Image <ide> <del>SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures") <del> <ide> <ide> SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures") <ide> <ide> def test_init_without_params(self): <ide> <ide> <ide> @is_staging_test <del>class ConfigPushToHubTester(unittest.TestCase): <add>class FeatureExtractorPushToHubTester(unittest.TestCase): <ide> @classmethod <ide> def setUpClass(cls): <ide> cls._token = login(username=USER, password=PASS) <ide><path>tests/test_processor_auto.py <ide> <ide> import json <ide> import os <add>import sys <ide> import tempfile <ide> import unittest <add>from pathlib import Path <ide> from shutil import copyfile <ide> <add>from huggingface_hub import Repository, delete_repo, login <add>from requests.exceptions import HTTPError <ide> from transformers import AutoProcessor, AutoTokenizer, Wav2Vec2Config, Wav2Vec2FeatureExtractor, Wav2Vec2Processor <del>from transformers.file_utils import FEATURE_EXTRACTOR_NAME <add>from transformers.file_utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available <add>from transformers.testing_utils import PASS, USER, is_staging_test <ide> from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE <ide> <ide> <add>sys.path.append(str(Path(__file__).parent.parent / "utils")) <add> <add>from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 <add>from test_module.custom_processing import CustomProcessor # noqa E402 <add>from test_module.custom_tokenization import CustomTokenizer # noqa E402 <add> <add> <ide> SAMPLE_PROCESSOR_CONFIG = os.path.join( <ide> os.path.dirname(os.path.abspath(__file__)), "fixtures/dummy_feature_extractor_config.json" <ide> ) <ide> SAMPLE_VOCAB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures/vocab.json") <ide> <add>SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures") <add> <ide> <ide> class AutoFeatureExtractorTest(unittest.TestCase): <ide> def test_processor_from_model_shortcut(self): <ide> def test_processor_from_local_directory_from_model_config(self): <ide> processor = AutoProcessor.from_pretrained(tmpdirname) <ide> <ide> self.assertIsInstance(processor, Wav2Vec2Processor) <add> <add> def test_from_pretrained_dynamic_processor(self): <add> processor = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor", trust_remote_code=True) <add> self.assertTrue(processor.special_attribute_present) <add> self.assertEqual(processor.__class__.__name__, "NewProcessor") <add> <add> feature_extractor = processor.feature_extractor <add> self.assertTrue(feature_extractor.special_attribute_present) <add> self.assertEqual(feature_extractor.__class__.__name__, "NewFeatureExtractor") <add> <add> tokenizer = processor.tokenizer <add> self.assertTrue(tokenizer.special_attribute_present) <add> if is_tokenizers_available(): <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast") <add> <add> # Test we can also load the slow version <add> processor = AutoProcessor.from_pretrained( <add> "hf-internal-testing/test_dynamic_processor", trust_remote_code=True, use_fast=False <add> ) <add> tokenizer = processor.tokenizer <add> self.assertTrue(tokenizer.special_attribute_present) <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") <add> else: <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") <add> <add> <add>@is_staging_test <add>class ProcessorPushToHubTester(unittest.TestCase): <add> vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] <add> <add> @classmethod <add> def setUpClass(cls): <add> cls._token = login(username=USER, password=PASS) <add> <add> @classmethod <add> def tearDownClass(cls): <add> try: <add> delete_repo(token=cls._token, name="test-dynamic-processor") <add> except HTTPError: <add> pass <add> <add> def test_push_to_hub_dynamic_processor(self): <add> CustomFeatureExtractor.register_for_auto_class() <add> CustomTokenizer.register_for_auto_class() <add> CustomProcessor.register_for_auto_class() <add> <add> feature_extractor = CustomFeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) <add> <add> with tempfile.TemporaryDirectory() as tmp_dir: <add> vocab_file = os.path.join(tmp_dir, "vocab.txt") <add> with open(vocab_file, "w", encoding="utf-8") as vocab_writer: <add> vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) <add> tokenizer = CustomTokenizer(vocab_file) <add> <add> processor = CustomProcessor(feature_extractor, tokenizer) <add> <add> with tempfile.TemporaryDirectory() as tmp_dir: <add> repo = Repository(tmp_dir, clone_from=f"{USER}/test-dynamic-processor", use_auth_token=self._token) <add> processor.save_pretrained(tmp_dir) <add> <add> # This has added the proper auto_map field to the feature extractor config <add> self.assertDictEqual( <add> processor.feature_extractor.auto_map, <add> { <add> "AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor", <add> "AutoProcessor": "custom_processing.CustomProcessor", <add> }, <add> ) <add> <add> # This has added the proper auto_map field to the tokenizer config <add> with open(os.path.join(tmp_dir, "tokenizer_config.json")) as f: <add> tokenizer_config = json.load(f) <add> self.assertDictEqual( <add> tokenizer_config["auto_map"], <add> { <add> "AutoTokenizer": ["custom_tokenization.CustomTokenizer", None], <add> "AutoProcessor": "custom_processing.CustomProcessor", <add> }, <add> ) <add> <add> # The code has been copied from fixtures <add> self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "custom_feature_extraction.py"))) <add> self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "custom_tokenization.py"))) <add> self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "custom_processing.py"))) <add> <add> repo.push_to_hub() <add> <add> new_processor = AutoProcessor.from_pretrained(f"{USER}/test-dynamic-processor", trust_remote_code=True) <add> # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module <add> self.assertEqual(new_processor.__class__.__name__, "CustomProcessor") <ide><path>tests/test_tokenization_auto.py <ide> def test_new_tokenizer_fast_registration(self): <ide> if CustomConfig in TOKENIZER_MAPPING._extra_content: <ide> del TOKENIZER_MAPPING._extra_content[CustomConfig] <ide> <add> def test_from_pretrained_dynamic_tokenizer(self): <add> tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True) <add> self.assertTrue(tokenizer.special_attribute_present) <add> if is_tokenizers_available(): <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast") <add> <add> # Test we can also load the slow version <add> tokenizer = AutoTokenizer.from_pretrained( <add> "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True, use_fast=False <add> ) <add> self.assertTrue(tokenizer.special_attribute_present) <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") <add> else: <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") <add> <add> def test_from_pretrained_dynamic_tokenizer_legacy_format(self): <add> tokenizer = AutoTokenizer.from_pretrained( <add> "hf-internal-testing/test_dynamic_tokenizer_legacy", trust_remote_code=True <add> ) <add> self.assertTrue(tokenizer.special_attribute_present) <add> if is_tokenizers_available(): <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast") <add> <add> # Test we can also load the slow version <add> tokenizer = AutoTokenizer.from_pretrained( <add> "hf-internal-testing/test_dynamic_tokenizer_legacy", trust_remote_code=True, use_fast=False <add> ) <add> self.assertTrue(tokenizer.special_attribute_present) <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") <add> else: <add> self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") <add> <ide> def test_repo_not_found(self): <ide> with self.assertRaisesRegex( <ide> EnvironmentError, "bert-base is not a local folder and is not a valid model identifier" <ide><path>tests/test_tokenization_common.py <ide> def test_push_to_hub_dynamic_tokenizer(self): <ide> <ide> with open(os.path.join(tmp_dir, "tokenizer_config.json")) as f: <ide> tokenizer_config = json.load(f) <del> self.assertEqual(tokenizer_config["auto_map"], ["custom_tokenization.CustomTokenizer", None]) <add> self.assertDictEqual( <add> tokenizer_config["auto_map"], {"AutoTokenizer": ["custom_tokenization.CustomTokenizer", None]} <add> ) <ide> <ide> repo.push_to_hub() <ide> <ide> def test_push_to_hub_dynamic_tokenizer(self): <ide> <ide> with open(os.path.join(tmp_dir, "tokenizer_config.json")) as f: <ide> tokenizer_config = json.load(f) <del> self.assertEqual( <add> self.assertDictEqual( <ide> tokenizer_config["auto_map"], <del> ["custom_tokenization.CustomTokenizer", "custom_tokenization_fast.CustomTokenizerFast"], <add> { <add> "AutoTokenizer": [ <add> "custom_tokenization.CustomTokenizer", <add> "custom_tokenization_fast.CustomTokenizerFast", <add> ] <add> }, <ide> ) <ide> <ide> repo.push_to_hub() <ide><path>utils/test_module/custom_processing.py <add>from transformers import ProcessorMixin <add> <add> <add>class CustomProcessor(ProcessorMixin): <add> feature_extractor_class = "AutoFeatureExtractor" <add> tokenizer_class = "AutoTokenizer"
9
Javascript
Javascript
fix abort on bad address input
f40caf728247ce78a1fe0a0673c4893fe299fafc
<ide><path>lib/net.js <ide> const WriteWrap = process.binding('stream_wrap').WriteWrap; <ide> const async_id_symbol = process.binding('async_wrap').async_id_symbol; <ide> const { newUid, setInitTriggerId } = require('async_hooks'); <ide> const nextTick = require('internal/process/next_tick').nextTick; <add>const errors = require('internal/errors'); <ide> <ide> var cluster; <ide> var dns; <ide> Socket.prototype.connect = function() { <ide> this._sockname = null; <ide> } <ide> <del> var pipe = !!options.path; <del> debug('pipe', pipe, options.path); <add> const path = options.path; <add> var pipe = !!path; <add> debug('pipe', pipe, path); <ide> <ide> if (!this._handle) { <ide> this._handle = pipe ? new Pipe() : new TCP(); <ide> Socket.prototype.connect = function() { <ide> this.writable = true; <ide> <ide> if (pipe) { <del> internalConnect(this, options.path); <add> if (typeof path !== 'string') { <add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', <add> 'options.path', <add> 'string', <add> path); <add> } <add> internalConnect(this, path); <ide> } else { <ide> lookupAndConnect(this, options); <ide> } <ide><path>test/parallel/test-net-better-error-messages-path.js <ide> const common = require('../common'); <ide> const net = require('net'); <ide> const assert = require('assert'); <del>const fp = '/tmp/fadagagsdfgsdf'; <del>const c = net.connect(fp); <ide> <del>c.on('connect', common.mustNotCall()); <add>{ <add> const fp = '/tmp/fadagagsdfgsdf'; <add> const c = net.connect(fp); <ide> <del>c.on('error', common.mustCall(function(e) { <del> assert.strictEqual(e.code, 'ENOENT'); <del> assert.strictEqual(e.message, `connect ENOENT ${fp}`); <del>})); <add> c.on('connect', common.mustNotCall()); <add> c.on('error', common.expectsError({ <add> code: 'ENOENT', <add> message: `connect ENOENT ${fp}` <add> })); <add>} <add> <add>{ <add> assert.throws( <add> () => net.createConnection({ path: {} }), <add> common.expectsError({ code: 'ERR_INVALID_ARG_TYPE' }) <add> ); <add>}
2
PHP
PHP
improve testability of batched jobs
a155ccdafa229cbd0fac0033a98a24119064f87a
<ide><path>src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php <ide> <ide> class BatchRepositoryFake implements BatchRepository <ide> { <add> /** <add> * The batches stored in the repository. <add> * <add> * @var \Illuminate\Bus\Batch[] <add> */ <add> protected $batches = []; <add> <ide> /** <ide> * Retrieve a list of batches. <ide> * <ide> class BatchRepositoryFake implements BatchRepository <ide> */ <ide> public function get($limit, $before) <ide> { <del> return []; <add> return $this->batches; <ide> } <ide> <ide> /** <ide> public function get($limit, $before) <ide> */ <ide> public function find(string $batchId) <ide> { <del> // <add> return $this->batches[$batchId] ?? null; <ide> } <ide> <ide> /** <ide> public function find(string $batchId) <ide> */ <ide> public function store(PendingBatch $batch) <ide> { <del> return new Batch( <add> $id = (string) Str::orderedUuid(); <add> <add> $this->batches[$id] = new Batch( <ide> new QueueFake(Facade::getFacadeApplication()), <ide> $this, <del> (string) Str::orderedUuid(), <add> $id, <ide> $batch->name, <ide> count($batch->jobs), <ide> count($batch->jobs), <ide> public function store(PendingBatch $batch) <ide> null, <ide> null <ide> ); <add> <add> return $this->batches[$id]; <ide> } <ide> <ide> /** <ide> public function incrementFailedJobs(string $batchId, string $jobId) <ide> */ <ide> public function markAsFinished(string $batchId) <ide> { <del> // <add> if (isset($this->batches[$batchId])) { <add> $this->batches[$batchId]->finishedAt = now(); <add> } <ide> } <ide> <ide> /** <ide> public function markAsFinished(string $batchId) <ide> */ <ide> public function cancel(string $batchId) <ide> { <del> // <add> if (isset($this->batches[$batchId])) { <add> $this->batches[$batchId]->cancelledAt = now(); <add> } <ide> } <ide> <ide> /** <ide> public function cancel(string $batchId) <ide> */ <ide> public function delete(string $batchId) <ide> { <del> // <add> unset($this->batches[$batchId]); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Support/Testing/Fakes/BusFake.php <ide> class BusFake implements QueueingDispatcher <ide> */ <ide> protected $jobsToFake; <ide> <add> /** <add> * The fake repository to track batched jobs. <add> * <add> * @var \Illuminate\Bus\BatchRepository <add> */ <add> protected $batchRepository; <add> <ide> /** <ide> * The commands that have been dispatched. <ide> * <ide> class BusFake implements QueueingDispatcher <ide> public function __construct(QueueingDispatcher $dispatcher, $jobsToFake = []) <ide> { <ide> $this->dispatcher = $dispatcher; <del> <ide> $this->jobsToFake = Arr::wrap($jobsToFake); <add> $this->batchRepository = new BatchRepositoryFake; <ide> } <ide> <ide> /** <ide> public function chain($jobs) <ide> */ <ide> public function findBatch(string $batchId) <ide> { <del> // <add> return $this->batchRepository->find($batchId); <ide> } <ide> <ide> /** <ide> public function recordPendingBatch(PendingBatch $pendingBatch) <ide> { <ide> $this->batches[] = $pendingBatch; <ide> <del> return (new BatchRepositoryFake)->store($pendingBatch); <add> return $this->batchRepository->store($pendingBatch); <ide> } <ide> <ide> /** <ide><path>tests/Support/SupportTestingBusFakeTest.php <ide> public function testAssertNothingBatched() <ide> $this->assertThat($e, new ExceptionMessage('Batched jobs were dispatched unexpectedly.')); <ide> } <ide> } <add> <add> public function testFindBatch() <add> { <add> $this->assertNull($this->fake->findBatch('non-existent-batch')); <add> <add> $batch = $this->fake->batch([])->dispatch(); <add> <add> $this->assertSame($batch, $this->fake->findBatch($batch->id)); <add> } <add> <add> public function testBatchesCanBeCancelled() <add> { <add> $batch = $this->fake->batch([])->dispatch(); <add> <add> $this->assertFalse($batch->cancelled()); <add> <add> $batch->cancel(); <add> <add> $this->assertTrue($batch->cancelled()); <add> } <ide> } <ide> <ide> class BusJobStub
3
Text
Text
remove secret from 'publicruntimeconfig' example
4594b7cb07baefd16c87626aa198bfef171d62e8
<ide><path>packages/next/README.md <ide> The `next/config` module gives your app access to runtime configuration stored i <ide> // next.config.js <ide> module.exports = { <ide> serverRuntimeConfig: { // Will only be available on the server side <del> mySecret: 'secret' <add> mySecret: 'secret', <add> secondSecret: process.env.SECOND_SECRET // Pass through env variables <ide> }, <ide> publicRuntimeConfig: { // Will be available on both server and client <ide> staticFolder: '/static', <del> mySecret: process.env.MY_SECRET // Pass through env variables <ide> } <ide> } <ide> ```
1
Javascript
Javascript
add brand checks for detached properties/methods
966060df0e4aa7d79bfdd9fe2163b12298cf59b7
<ide><path>lib/internal/worker/io.js <ide> const { inspect } = require('internal/util/inspect'); <ide> const { <ide> codes: { <ide> ERR_INVALID_ARG_TYPE, <add> ERR_INVALID_THIS, <ide> ERR_MISSING_ARGS, <ide> } <ide> } = require('internal/errors'); <ide> const kStartedReading = Symbol('kStartedReading'); <ide> const kStdioWantsMoreDataCallback = Symbol('kStdioWantsMoreDataCallback'); <ide> const kCurrentlyReceivingPorts = <ide> SymbolFor('nodejs.internal.kCurrentlyReceivingPorts'); <add>const kType = Symbol('kType'); <ide> <ide> const messageTypes = { <ide> UP_AND_RUNNING: 'upAndRunning', <ide> function onMessageEvent(type, data) { <ide> this.dispatchEvent(new MessageEvent(type, { data })); <ide> } <ide> <add>function isBroadcastChannel(value) { <add> return value?.[kType] === 'BroadcastChannel'; <add>} <add> <ide> class BroadcastChannel extends EventTarget { <ide> constructor(name) { <ide> if (arguments.length === 0) <ide> throw new ERR_MISSING_ARGS('name'); <ide> super(); <add> this[kType] = 'BroadcastChannel'; <ide> this[kName] = `${name}`; <ide> this[kHandle] = broadcastChannel(this[kName]); <ide> this[kOnMessage] = FunctionPrototypeBind(onMessageEvent, this, 'message'); <ide> class BroadcastChannel extends EventTarget { <ide> } <ide> <ide> [inspect.custom](depth, options) { <add> if (!isBroadcastChannel(this)) <add> throw new ERR_INVALID_THIS('BroadcastChannel'); <ide> if (depth < 0) <ide> return 'BroadcastChannel'; <ide> <ide> class BroadcastChannel extends EventTarget { <ide> }, opts)}`; <ide> } <ide> <del> get name() { return this[kName]; } <add> get name() { <add> if (!isBroadcastChannel(this)) <add> throw new ERR_INVALID_THIS('BroadcastChannel'); <add> return this[kName]; <add> } <ide> <ide> close() { <add> if (!isBroadcastChannel(this)) <add> throw new ERR_INVALID_THIS('BroadcastChannel'); <ide> if (this[kHandle] === undefined) <ide> return; <ide> this[kHandle].off('message', this[kOnMessage]); <ide> class BroadcastChannel extends EventTarget { <ide> } <ide> <ide> postMessage(message) { <add> if (!isBroadcastChannel(this)) <add> throw new ERR_INVALID_THIS('BroadcastChannel'); <ide> if (arguments.length === 0) <ide> throw new ERR_MISSING_ARGS('message'); <ide> if (this[kHandle] === undefined) <ide> class BroadcastChannel extends EventTarget { <ide> throw new DOMException('Message could not be posted.'); <ide> } <ide> <add> // The ref() method is Node.js specific and not part of the standard <add> // BroadcastChannel API definition. Typically we shouldn't extend Web <add> // Platform APIs with Node.js specific methods but ref and unref <add> // are a bit special. <ide> ref() { <add> if (!isBroadcastChannel(this)) <add> throw new ERR_INVALID_THIS('BroadcastChannel'); <ide> if (this[kHandle]) <ide> this[kHandle].ref(); <ide> return this; <ide> } <ide> <add> // The unref() method is Node.js specific and not part of the standard <add> // BroadcastChannel API definition. Typically we shouldn't extend Web <add> // Platform APIs with Node.js specific methods but ref and unref <add> // are a bit special. <ide> unref() { <add> if (!isBroadcastChannel(this)) <add> throw new ERR_INVALID_THIS('BroadcastChannel'); <ide> if (this[kHandle]) <ide> this[kHandle].unref(); <ide> return this; <ide> } <ide> } <ide> <add>const kEnumerableProperty = ObjectCreate(null); <add>kEnumerableProperty.enumerable = true; <add> <add>ObjectDefineProperties(BroadcastChannel.prototype, { <add> name: kEnumerableProperty, <add> close: kEnumerableProperty, <add> postMessage: kEnumerableProperty, <add>}); <add> <ide> defineEventHandler(BroadcastChannel.prototype, 'message'); <ide> defineEventHandler(BroadcastChannel.prototype, 'messageerror'); <ide> <ide><path>test/parallel/test-worker-broadcastchannel.js <ide> assert.throws(() => new BroadcastChannel(), { <ide> bc1.close(); <ide> bc2.close(); <ide> } <add> <add>{ <add> assert.throws(() => Reflect.get(BroadcastChannel.prototype, 'name', {}), { <add> code: 'ERR_INVALID_THIS', <add> }); <add> <add> [ <add> 'close', <add> 'postMessage', <add> 'ref', <add> 'unref', <add> ].forEach((i) => { <add> assert.throws(() => Reflect.apply(BroadcastChannel.prototype[i], [], {}), { <add> code: 'ERR_INVALID_THIS', <add> }); <add> }); <add>}
2
Python
Python
show warning if '/' is used in a dag run id
451c7cbc42a83a180c4362693508ed33dd1d1dab
<ide><path>airflow/models/dag.py <ide> def create_dagrun( <ide> "Creating DagRun needs either `run_id` or both `run_type` and `execution_date`" <ide> ) <ide> <add> if run_id and "/" in run_id: <add> warnings.warn( <add> "Using forward slash ('/') in a DAG run ID is deprecated. Note that this character " <add> "also makes the run impossible to retrieve via Airflow's REST API.", <add> DeprecationWarning, <add> stacklevel=3, <add> ) <add> <ide> logical_date = timezone.coerce_datetime(execution_date) <ide> if data_interval is None and logical_date is not None: <ide> warnings.warn( <ide><path>airflow/www/views.py <ide> def trigger(self, session=None): <ide> flash(f"The run_id {dr.run_id} already exists", "error") <ide> return redirect(origin) <ide> <add> # Flash a warning when slash is used, but still allow it to continue on. <add> if run_id and "/" in run_id: <add> flash( <add> "Using forward slash ('/') in a DAG run ID is deprecated. Note that this character " <add> "also makes the run impossible to retrieve via Airflow's REST API.", <add> "warning", <add> ) <add> <ide> run_conf = {} <ide> if request_conf: <ide> try:
2
Text
Text
update the description of the deprecated module
1d752731011d35e985271334ff98186728949f03
<ide><path>README.md <ide> Some example modules that can be excluded are: <ide> - **ajax/script**: The `<script>` AJAX transport only; used to retrieve scripts. <ide> - **ajax/jsonp**: The JSONP AJAX transport only; depends on the ajax/script transport. <ide> - **css**: The `.css()` method plus non-animated `.show()`, `.hide()` and `.toggle()`. Also removes **all** modules depending on css (including **effects**, **dimensions**, and **offset**). <del>- **deprecated**: Methods documented as deprecated but not yet removed; currently only `.andSelf()`. <add>- **deprecated**: Methods documented as deprecated but not yet removed. <ide> - **dimensions**: The `.width()` and `.height()` methods, including `inner-` and `outer-` variations. <ide> - **effects**: The `.animate()` method and its shorthands such as `.slideUp()` or `.hide("slow")`. <ide> - **event**: The `.on()` and `.off()` methods and all event functionality. Also removes `event/alias`.
1
PHP
PHP
remove auth_mode from config/mail.php
0d939c9ebfcf1cac8ef1a26a7a2dce50a31e74ba
<ide><path>config/mail.php <ide> 'username' => env('MAIL_USERNAME'), <ide> 'password' => env('MAIL_PASSWORD'), <ide> 'timeout' => null, <del> 'auth_mode' => null, <ide> ], <ide> <ide> 'ses' => [
1
PHP
PHP
fix failing test
9f9cc3778994f3895aa38fd9f8c13b454cbab685
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php <ide> public function testAfterIdentifyForStatelessAuthentication(): void <ide> $this->Auth->setConfig('storage', 'Memory'); <ide> <ide> EventManager::instance()->on('Auth.afterIdentify', function (EventInterface $event) { <del> $user = $event->getData(0); <add> $user = $event->getData('0'); <ide> $user['from_callback'] = true; <ide> <ide> return $user;
1
Text
Text
fix example in child_process.md
0794c101efe223a3d4b79a2848327946fb1b8c60
<ide><path>doc/api/child_process.md <ide> grep.on('close', (code) => { <ide> ``` <ide> <ide> <del>Example of checking for failed exec: <add>Example of checking for failed `spawn`: <ide> <ide> ```js <ide> const { spawn } = require('child_process');
1
Ruby
Ruby
add synchronization to connection pool also
cab76ce6ac2983f59451e2d53b23746a2873aea0
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> def initialize(spec) <ide> <ide> # The ConnectionSpecification for this pool <ide> @spec = spec <add> <add> # The mutex used to synchronize pool access <add> @connection_mutex = Monitor.new <ide> end <ide> <ide> def active_connection_name #:nodoc: <ide> def retrieve_connection #:nodoc: <ide> # Verify the connection. <ide> conn.verify!(verification_timeout) <ide> else <del> self.connection = spec <add> self.set_connection spec <ide> conn = active_connections[name] <ide> end <ide> <ide> def connected? <ide> active_connections[active_connection_name] ? true : false <ide> end <ide> <add> # Disconnect all connections in the pool. <ide> def disconnect! <ide> clear_cache!(@active_connections) do |name, conn| <ide> conn.disconnect! <ide> end <ide> end <ide> <ide> # Set the connection for the class. <del> def connection=(spec) #:nodoc: <add> def set_connection(spec) #:nodoc: <ide> if spec.kind_of?(ActiveRecord::ConnectionAdapters::AbstractAdapter) <ide> active_connections[active_connection_name] = spec <ide> elsif spec.kind_of?(ActiveRecord::Base::ConnectionSpecification) <del> self.connection = ActiveRecord::Base.send(spec.adapter_method, spec.config) <add> self.set_connection ActiveRecord::Base.send(spec.adapter_method, spec.config) <ide> else <ide> raise ConnectionNotEstablished <ide> end <ide> end <ide> <add> synchronize :active_connection, :connection, :clear_active_connections!, <add> :clear_reloadable_connections!, :verify_active_connections!, :retrieve_connection, <add> :connected?, :disconnect!, :set_connection, :with => :@connection_mutex <add> <ide> private <ide> def clear_cache!(cache, &block) <ide> cache.each(&block) if block_given? <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb <ide> def synchronize <ide> @@connection_pools = {} <ide> <ide> class << self <add> # Turning on allow_concurrency basically switches a null mutex for a real one, so that <add> # multi-threaded access of the connection pools hash is synchronized. <ide> def allow_concurrency=(flag) <ide> if @@allow_concurrency != flag <ide> if flag <ide> def allow_concurrency=(flag) <ide> end <ide> end <ide> <del> # for internal use only <add> # for internal use only and for testing <ide> def active_connections #:nodoc: <ide> @@connection_pools.inject({}) do |hash,kv| <ide> hash[kv.first] = kv.last.active_connection <ide><path>activesupport/lib/active_support/core_ext/module/synchronization.rb <ide> def synchronize(*methods) <ide> raise ArgumentError, "Synchronization needs a mutex. Supply an options hash with a :with key as the last argument (e.g. synchronize :hello, :with => :@mutex)." <ide> end <ide> <del> methods.each do |method| <add> methods.flatten.each do |method| <ide> aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1 <ide> if instance_methods.include?("#{aliased_method}_without_synchronization#{punctuation}") <ide> raise ArgumentError, "#{method} is already synchronized. Double synchronization is not currently supported." <ide> end <ide> module_eval(<<-EOS, __FILE__, __LINE__) <ide> def #{aliased_method}_with_synchronization#{punctuation}(*args, &block) <ide> #{with}.synchronize do <del> #{aliased_method}_without_synchronization#{punctuation}(*args,&block) <add> #{aliased_method}_without_synchronization#{punctuation}(*args, &block) <ide> end <ide> end <ide> EOS
3
PHP
PHP
correct doc block
c7ec4ab7efd55786c5625f624bbb38f195fc44cf
<ide><path>Cake/Cache/CacheEngine.php <ide> abstract class CacheEngine { <ide> * Initialize the cache engine <ide> * <ide> * Called automatically by the cache frontend. Merge the runtime config with the defaults <del> * for the specific cache engine, and the general defaults before use <add> * before use. <ide> * <ide> * @param array $config Associative array of parameters for the engine <ide> * @return boolean True if the engine has been successfully initialized, false if not
1
Python
Python
use yaml safe load
dfd9805a23b2d366f5c332f4cb4131462c5ba82e
<ide><path>airflow/providers/google/cloud/operators/cloud_build.py <ide> def prepare_template(self) -> None: <ide> return <ide> with open(self.build_raw) as file: <ide> if any(self.build_raw.endswith(ext) for ext in ['.yaml', '.yml']): <del> self.build = yaml.load(file.read(), Loader=yaml.FullLoader) <add> self.build = yaml.safe_load(file.read()) <ide> if self.build_raw.endswith('.json'): <ide> self.build = json.loads(file.read()) <ide>
1
Ruby
Ruby
add regression tests for preloader query count
5e59f5f07582dd88b85928e8d886c5762fc8cdbc
<ide><path>activerecord/test/cases/associations_test.rb <ide> def test_legacy_preload_with_scope <ide> assert_predicate post.comments, :loaded? <ide> assert_equal [comments(:greetings)], post.comments <ide> end <add> <add> def test_preload_makes_correct_number_of_queries_on_array <add> post = posts(:welcome) <add> <add> assert_queries(1) do <add> preloader = ActiveRecord::Associations::Preloader.new(records: [post], associations: :comments) <add> preloader.call <add> end <add> end <add> <add> def test_preload_makes_correct_number_of_queries_on_relation <add> post = posts(:welcome) <add> relation = Post.where(id: post.id) <add> <add> assert_queries(2) do <add> preloader = ActiveRecord::Associations::Preloader.new(records: relation, associations: :comments) <add> preloader.call <add> end <add> end <ide> end <ide> <ide> class GeneratedMethodsTest < ActiveRecord::TestCase
1
Text
Text
add release notes
ee8504bc5ace8d3352166f1f2dce91b56fd9ad91
<ide><path>docs/sources/release-notes.md <ide> understanding, release <ide> <ide> #Release Notes <ide> <add>##Version 1.3.3 <add>(2014-12-11) <add> <add>This release fixes several security issues. In order to encourage immediate <add>upgrading, this release also patches some critical bugs. All users are highly <add>encouraged to upgrade as soon as possible. <add> <add>*Security fixes* <add> <add>Patches and changes were made to address the following vulnerabilities: <add> <add>* CVE-2014-9356: Path traversal during processing of absolute symlinks. <add>Absolute symlinks were not adequately checked for traversal which created a <add>vulnerability via image extraction and/or volume mounts. <add>* CVE-2014-9357: Escalation of privileges during decompression of LZMA (.xz) <add>archives. Docker 1.3.2 added `chroot` for archive extraction. This created a <add>vulnerability that could allow malicious images or builds to write files to the <add>host system and escape containerization, leading to privilege escalation. <add>* CVE-2014-9358: Path traversal and spoofing opportunities via image <add>identifiers. Image IDs passed either via `docker load` or registry communications <add>were not sufficiently validated. This created a vulnerability to path traversal <add>attacks wherein malicious images or repository spoofing could lead to graph <add>corruption and manipulation. <add> <add>*Runtime fixes* <add> <add>* Fixed an issue that cause image archives to be read slowly. <add> <add>*Client fixes* <add> <add>* Fixed a regression related to STDIN redirection. <add>* Fixed a regression involving `docker cp` when the current directory is the <add>destination. <add> <ide> ##Version 1.3.2 <ide> (2014-11-24) <ide>
1
Ruby
Ruby
add compatibility layer for `module homebrew`
acaee035dfddd1fd90b883f19cb2c9f52852c2f3
<ide><path>Library/Homebrew/compat.rb <ide> require "compat/tap" <ide> require "compat/formula" <ide> require "compat/formula_specialties" <add>require "compat/global" <ide> require "compat/hardware" <ide> require "compat/macos" <ide> require "compat/md5" <ide><path>Library/Homebrew/compat/global.rb <add>module Homebrew <add> module_function <add> <add> def method_missing(method, *args, &block) <add> if instance_methods.include?(method) <add> # odeprecated "#{self}##{method}", "'module_function' or 'def self.#{method}' to convert it to a class method" <add> return instance_method(method).bind(self).call(*args, &block) <add> end <add> super <add> end <add> <add> def respond_to_missing?(method, include_private = false) <add> return true if method_defined?(method) <add> super(method, include_private) <add> end <add>end
2
PHP
PHP
replace slash to double back slash
b890d6cdd0f45f642c6695b2ec10e34b360a6850
<ide><path>src/Illuminate/Console/GeneratorCommand.php <ide> protected function parseName($name) <ide> return $name; <ide> } <ide> <add> if (str_contains($name, '/')) <add> { <add> $name = str_replace('/', '\\', $name); <add> } <add> <ide> return $this->parseName($this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name); <ide> } <ide>
1
Javascript
Javascript
add ios linking location example to docs
ec68c97d72030cab6e3aef991dee8413d5a95c00
<ide><path>Libraries/Linking/Linking.js <ide> class Linking extends NativeEventEmitter { <ide> /** <ide> * Try to open the given `url` with any of the installed apps. <ide> * <del> * You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386"), a contact, <add> * You can use other URLs, like a location (e.g. "geo:37.484847,-122.148386" on Android <add> * or "http://maps.apple.com/?ll=37.484847,-122.148386" on iOS), a contact, <ide> * or any other URL that can be opened with the installed apps. <ide> * <ide> * NOTE: This method will fail if the system doesn't know how to open the specified URL.
1
Javascript
Javascript
hide lens flare if not visible
d24518dca32645d2bea0e8460181b00332d6c6bd
<ide><path>src/extras/renderers/plugins/LensFlarePlugin.js <ide> THREE.LensFlarePlugin = function () { <ide> <ide> flare = flares[ i ]; <ide> <add> if (!flare.visible) <add> continue; <add> <ide> tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] ); <ide> <ide> tempPosition.applyMatrix4( camera.matrixWorldInverse );
1
Javascript
Javascript
fix regression on duplex end
5a3f43b255af6968606f13258447894f946ee3ce
<ide><path>lib/internal/streams/writable.js <ide> function writeOrBuffer(stream, state, chunk, encoding, callback) { <ide> <ide> state.length += len; <ide> <add> // stream._write resets state.length <add> const ret = state.length < state.highWaterMark; <add> // We must ensure that previous needDrain will not be reset to false. <add> if (!ret) <add> state.needDrain = true; <add> <ide> if (state.writing || state.corked || state.errored || !state.constructed) { <ide> state.buffered.push({ chunk, encoding, callback }); <ide> if (state.allBuffers && encoding !== 'buffer') { <ide> function writeOrBuffer(stream, state, chunk, encoding, callback) { <ide> state.sync = false; <ide> } <ide> <del> const ret = state.length < state.highWaterMark; <del> <del> // We must ensure that previous needDrain will not be reset to false. <del> if (!ret) <del> state.needDrain = true; <del> <ide> // Return false if errored or destroyed in order to break <ide> // any synchronous while(stream.write(data)) loops. <ide> return ret && !state.errored && !state.destroyed; <ide><path>test/parallel/test-stream-duplex-readable-end.js <add>'use strict'; <add>// https://github.com/nodejs/node/issues/35926 <add>require('../common'); <add>const assert = require('assert'); <add>const stream = require('stream'); <add> <add>let loops = 5; <add> <add>const src = new stream.Readable({ <add> read() { <add> if (loops--) <add> this.push(Buffer.alloc(20000)); <add> } <add>}); <add> <add>const dst = new stream.Transform({ <add> transform(chunk, output, fn) { <add> this.push(null); <add> fn(); <add> } <add>}); <add> <add>src.pipe(dst); <add> <add>function parser_end() { <add> assert.ok(loops > 0); <add> dst.removeAllListeners(); <add>} <add> <add>dst.on('data', () => { }); <add>dst.on('end', parser_end); <add>dst.on('error', parser_end);
2
Ruby
Ruby
update documentation for dependency.expand
c5f73a01bec87f6c4d3c6b29676b82cc922187af
<ide><path>Library/Homebrew/dependency.rb <ide> def universal! <ide> tags << 'universal' if to_formula.build.has_option? 'universal' <ide> end <ide> <del> # Expand the dependencies of f recursively, optionally yielding <del> # [f, dep] to allow callers to apply arbitrary filters to the list. <del> # The default filter, which is used when a block is not supplied, <del> # omits optionals and recommendeds based on what the dependent has <del> # asked for. <add> # Expand the dependencies of dependent recursively, optionally yielding <add> # [dependent, dep] pairs to allow callers to apply arbitrary filters to <add> # the list. <add> # The default filter, which is applied when a block is not given, omits <add> # optionals and recommendeds based on what the dependent has asked for. <ide> def self.expand(dependent, &block) <ide> dependent.deps.map do |dep| <ide> prune = catch(:prune) do <ide> def self.expand(dependent, &block) <ide> end.flatten.compact.uniq <ide> end <ide> <del> # Used to prune dependencies when calling expand_dependencies with a block. <add> # Used to prune dependencies when calling expand with a block. <ide> def self.prune <ide> throw(:prune, true) <ide> end
1
Text
Text
use common malformed instead of misformatted
a52050877c91509f654dd6b2519c0132b7792578
<ide><path>doc/api/cli.md <ide> When set, the well known "root" CAs (like VeriSign) will be extended with the <ide> extra certificates in `file`. The file should consist of one or more trusted <ide> certificates in PEM format. A message will be emitted (once) with <ide> [`process.emitWarning()`][emit_warning] if the file is missing or <del>misformatted, but any errors are otherwise ignored. <add>malformed, but any errors are otherwise ignored. <ide> <ide> Note that neither the well known nor extra certificates are used when the `ca` <ide> options property is explicitly specified for a TLS or HTTPS client or server.
1
Ruby
Ruby
add test for test calls audit cop
5f981a8722487dd9ee127a59f4f0471fa35c3c4c
<ide><path>Library/Homebrew/test/rubocops/class_cop_spec.rb <ide> class Foo < Formula <ide> end <ide> end <ide> <add>describe RuboCop::Cop::FormulaAudit::TestCalls do <add> subject(:cop) { described_class.new } <add> <add> it "reports an offense when /usr/local/bin is found in test calls" do <add> expect_offense(<<~RUBY) <add> class Foo < Formula <add> url 'https://example.com/foo-1.0.tgz' <add> <add> test do <add> system "/usr/local/bin/test" <add> ^^^^^^^^^^^^^^^^^^^^^ use \#{bin} instead of /usr/local/bin in system <add> end <add> end <add> RUBY <add> end <add> <add> it "reports an offense when passing 0 as the second parameter to shell_output" do <add> expect_offense(<<~RUBY) <add> class Foo < Formula <add> url 'https://example.com/foo-1.0.tgz' <add> <add> test do <add> shell_output("\#{bin}/test", 0) <add> ^ Passing 0 to shell_output() is redundant <add> end <add> end <add> RUBY <add> end <add>end <add> <ide> describe RuboCop::Cop::FormulaAuditStrict::Test do <ide> subject(:cop) { described_class.new } <ide>
1
Javascript
Javascript
use random ports where possible
2bc7841d0fcdd066fe477873229125b6f003b693
<ide><path>test/parallel/test-async-wrap-check-providers.js <ide> net.createServer(function(c) { <ide> net.createServer(function(c) { <ide> c.end(); <ide> this.close(checkTLS); <del>}).listen(common.PORT, function() { <del> net.connect(common.PORT, noop); <add>}).listen(0, function() { <add> net.connect(this.address().port, noop); <ide> }); <ide> <del>dgram.createSocket('udp4').bind(common.PORT, function() { <del> this.send(Buffer.allocUnsafe(2), 0, 2, common.PORT, '::', () => { <add>dgram.createSocket('udp4').bind(0, function() { <add> this.send(Buffer.allocUnsafe(2), 0, 2, this.address().port, '::', () => { <ide> this.close(); <ide> }); <ide> }); <ide> function checkTLS() { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') <ide> }; <ide> const server = tls.createServer(options, noop) <del> .listen(common.PORT, function() { <del> tls.connect(common.PORT, { rejectUnauthorized: false }, function() { <add> .listen(0, function() { <add> const connectOpts = { rejectUnauthorized: false }; <add> tls.connect(this.address().port, connectOpts, function() { <ide> this.destroy(); <ide> server.close(); <ide> }); <ide><path>test/parallel/test-async-wrap-disabled-propagate-parent.js <ide> 'use strict'; <ide> <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> const async_wrap = process.binding('async_wrap'); <ide> const server = net.createServer(function(c) { <ide> c.end(); <ide> this.close(); <ide> }); <del>}).listen(common.PORT, function() { <del> net.connect(common.PORT, noop); <add>}).listen(0, function() { <add> net.connect(this.address().port, noop); <ide> }); <ide> <ide> async_wrap.disable(); <ide><path>test/parallel/test-async-wrap-propagate-parent.js <ide> 'use strict'; <ide> <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> const async_wrap = process.binding('async_wrap'); <ide> const server = net.createServer(function(c) { <ide> c.end(); <ide> this.close(); <ide> }); <del>}).listen(common.PORT, function() { <del> net.connect(common.PORT, noop); <add>}).listen(0, function() { <add> net.connect(this.address().port, noop); <ide> }); <ide> <ide> <ide><path>test/parallel/test-beforeexit-event.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <del>var common = require('../common'); <ide> var revivals = 0; <ide> var deaths = 0; <ide> <ide> function tryTimer() { <ide> function tryListen() { <ide> console.log('create a server'); <ide> net.createServer() <del> .listen(common.PORT) <add> .listen(0) <ide> .on('listening', function() { <ide> revivals++; <ide> this.close(); <ide><path>test/parallel/test-child-process-disconnect.js <ide> if (process.argv[2] === 'child') { <ide> <ide> // when the server is ready tell parent <ide> server.on('listening', function() { <del> process.send('ready'); <add> process.send({ msg: 'ready', port: server.address().port }); <ide> }); <ide> <del> server.listen(common.PORT); <add> server.listen(0); <ide> <ide> } else { <ide> // testcase <ide> if (process.argv[2] === 'child') { <ide> }); <ide> <ide> // when child is listening <del> child.on('message', function(msg) { <del> if (msg === 'ready') { <add> child.on('message', function(obj) { <add> if (obj && obj.msg === 'ready') { <ide> <ide> // connect to child using TCP to know if disconnect was emitted <del> var socket = net.connect(common.PORT); <add> var socket = net.connect(obj.port); <ide> <ide> socket.on('data', function(data) { <ide> data = data.toString(); <ide><path>test/parallel/test-child-process-fork-dgram.js <ide> if (process.argv[2] === 'child') { <ide> msg, <ide> 0, <ide> msg.length, <del> common.PORT, <add> server.address().port, <ide> '127.0.0.1', <ide> function(err) { <ide> if (err) throw err; <ide> if (process.argv[2] === 'child') { <ide> client.close(); <ide> }; <ide> <del> server.bind(common.PORT, '127.0.0.1'); <add> server.bind(0, '127.0.0.1'); <ide> <ide> process.once('exit', function() { <ide> assert(parentGotMessage); <ide><path>test/parallel/test-child-process-fork-net.js <ide> 'use strict'; <del>const assert = require('assert'); <ide> require('../common'); <add>const assert = require('assert'); <ide> const fork = require('child_process').fork; <ide> const net = require('net'); <ide> <ide><path>test/parallel/test-child-process-fork-net2.js <ide> if (process.argv[2] === 'child') { <ide> <ide> var j = count, client; <ide> while (j--) { <del> client = net.connect(common.PORT, '127.0.0.1'); <add> client = net.connect(this.address().port, '127.0.0.1'); <ide> client.on('error', function() { <ide> // This can happen if we kill the child too early. <ide> // The client should still get a close event afterwards. <ide> if (process.argv[2] === 'child') { <ide> child3.kill(); <ide> })); <ide> <del> server.listen(common.PORT, '127.0.0.1'); <add> server.listen(0, '127.0.0.1'); <ide> <ide> var closeServer = function() { <ide> server.close(); <ide><path>test/parallel/test-child-process-fork-regr-gh-2847.js <ide> var server = net.createServer(function(s) { <ide> setTimeout(function() { <ide> s.destroy(); <ide> }, 100); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> var worker = cluster.fork(); <ide> <ide> function send(callback) { <del> var s = net.connect(common.PORT, function() { <add> var s = net.connect(server.address().port, function() { <ide> worker.send({}, s, callback); <ide> }); <ide> <ide><path>test/parallel/test-child-process-recv-handle.js <ide> function master() { <ide> }); <ide> proc.stdout.on('data', function(data) { <ide> assert.equal(data, 'ok\r\n'); <del> net.createServer(common.fail).listen(common.PORT, function() { <add> net.createServer(common.fail).listen(0, function() { <ide> handle = this._handle; <ide> proc.send('one'); <ide> proc.send('two', handle); <ide><path>test/parallel/test-child-process-send-keep-open.js <ide> if (process.argv[2] !== 'child') { <ide> })); <ide> }); <ide> <del> server.listen(common.PORT, () => { <del> const socket = net.connect(common.PORT, common.localhostIPv4); <add> server.listen(0, () => { <add> const socket = net.connect(server.address().port, common.localhostIPv4); <ide> socket.setEncoding('utf8'); <ide> socket.on('data', (data) => result += data); <ide> }); <ide><path>test/parallel/test-child-process-send-returns-boolean.js <ide> s.on('exit', function() { <ide> handle.close(); <ide> }); <ide> <del>net.createServer(common.fail).listen(common.PORT, function() { <add>net.createServer(common.fail).listen(0, function() { <ide> handle = this._handle; <ide> assert.strictEqual(s.send('one', handle), true); <ide> assert.strictEqual(s.send('two', handle), true); <ide><path>test/parallel/test-crypto-verify-failure.js <ide> function verify() { <ide> .verify(certPem, 'asdfasdfas', 'base64'); <ide> } <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> tls.connect({ <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function() { <ide> verify(); <ide><path>test/parallel/test-dgram-address.js <ide> var family_ipv4 = 'IPv4'; <ide> socket_ipv4.on('listening', function() { <ide> var address_ipv4 = socket_ipv4.address(); <ide> assert.strictEqual(address_ipv4.address, common.localhostIPv4); <del> assert.strictEqual(address_ipv4.port, common.PORT); <add> assert.strictEqual(typeof address_ipv4.port, 'number'); <add> assert.ok(isFinite(address_ipv4.port)); <add> assert.ok(address_ipv4.port > 0); <ide> assert.strictEqual(address_ipv4.family, family_ipv4); <ide> socket_ipv4.close(); <ide> }); <ide> socket_ipv4.on('error', function(e) { <ide> socket_ipv4.close(); <ide> }); <ide> <del>socket_ipv4.bind(common.PORT, common.localhostIPv4); <add>socket_ipv4.bind(0, common.localhostIPv4); <ide> <ide> // IPv6 Test <ide> var localhost_ipv6 = '::1'; <ide> var family_ipv6 = 'IPv6'; <ide> socket_ipv6.on('listening', function() { <ide> var address_ipv6 = socket_ipv6.address(); <ide> assert.strictEqual(address_ipv6.address, localhost_ipv6); <del> assert.strictEqual(address_ipv6.port, common.PORT); <add> assert.strictEqual(typeof address_ipv6.port, 'number'); <add> assert.ok(isFinite(address_ipv6.port)); <add> assert.ok(address_ipv6.port > 0); <ide> assert.strictEqual(address_ipv6.family, family_ipv6); <ide> socket_ipv6.close(); <ide> }); <ide> socket_ipv6.on('error', function(e) { <ide> socket_ipv6.close(); <ide> }); <ide> <del>socket_ipv6.bind(common.PORT, localhost_ipv6); <add>socket_ipv6.bind(0, localhost_ipv6); <ide><path>test/parallel/test-dgram-bind-default-address.js <ide> if (common.inFreeBSDJail) { <ide> return; <ide> } <ide> <del>dgram.createSocket('udp4').bind(common.PORT + 0, common.mustCall(function() { <del> assert.equal(this.address().port, common.PORT + 0); <add>dgram.createSocket('udp4').bind(0, common.mustCall(function() { <add> assert.strictEqual(typeof this.address().port, 'number'); <add> assert.ok(isFinite(this.address().port)); <add> assert.ok(this.address().port > 0); <ide> assert.equal(this.address().address, '0.0.0.0'); <ide> this.close(); <ide> })); <ide> if (!common.hasIPv6) { <ide> return; <ide> } <ide> <del>dgram.createSocket('udp6').bind(common.PORT + 1, common.mustCall(function() { <del> assert.equal(this.address().port, common.PORT + 1); <add>dgram.createSocket('udp6').bind(0, common.mustCall(function() { <add> assert.strictEqual(typeof this.address().port, 'number'); <add> assert.ok(isFinite(this.address().port)); <add> assert.ok(this.address().port > 0); <ide> var address = this.address().address; <ide> if (address === '::ffff:0.0.0.0') <ide> address = '::'; <ide><path>test/parallel/test-dgram-empty-packet.js <ide> if (process.platform === 'darwin') { <ide> <ide> client = dgram.createSocket('udp4'); <ide> <del>client.bind(common.PORT); <del> <del>function callback() { <del> callbacks++; <del> if (callbacks == 2) { <del> clearTimeout(timer); <del> client.close(); <del> } else if (callbacks > 2) { <del> throw new Error('the callbacks should be called only two times'); <add>client.bind(0, function() { <add> function callback() { <add> callbacks++; <add> if (callbacks == 2) { <add> clearTimeout(timer); <add> client.close(); <add> } else if (callbacks > 2) { <add> throw new Error('the callbacks should be called only two times'); <add> } <ide> } <del>} <del> <del>client.on('message', function(buffer, bytes) { <del> callback(); <del>}); <ide> <del>client.send( <del> Buffer.allocUnsafe(1), 0, 0, common.PORT, '127.0.0.1', (err, len) => { <add> client.on('message', function(buffer, bytes) { <ide> callback(); <ide> }); <ide> <del>timer = setTimeout(function() { <del> throw new Error('Timeout'); <del>}, 200); <add> const port = this.address().port; <add> client.send( <add> Buffer.allocUnsafe(1), 0, 0, port, '127.0.0.1', (err, len) => { <add> callback(); <add> }); <add> <add> timer = setTimeout(function() { <add> throw new Error('Timeout'); <add> }, 200); <add>}); <ide><path>test/parallel/test-dgram-error-message-address.js <ide> var socket_ipv4 = dgram.createSocket('udp4'); <ide> socket_ipv4.on('listening', common.fail); <ide> <ide> socket_ipv4.on('error', common.mustCall(function(e) { <del> assert.equal(e.message, 'bind EADDRNOTAVAIL 1.1.1.1:' + common.PORT); <add> assert.strictEqual(e.port, undefined); <add> assert.equal(e.message, 'bind EADDRNOTAVAIL 1.1.1.1'); <ide> assert.equal(e.address, '1.1.1.1'); <del> assert.equal(e.port, common.PORT); <ide> assert.equal(e.code, 'EADDRNOTAVAIL'); <ide> socket_ipv4.close(); <ide> })); <ide> <del>socket_ipv4.bind(common.PORT, '1.1.1.1'); <add>socket_ipv4.bind(0, '1.1.1.1'); <ide> <ide> // IPv6 Test <ide> var socket_ipv6 = dgram.createSocket('udp6'); <ide> socket_ipv6.on('error', common.mustCall(function(e) { <ide> // EAFNOSUPPORT or EPROTONOSUPPORT means IPv6 is disabled on this system. <ide> var allowed = ['EADDRNOTAVAIL', 'EAFNOSUPPORT', 'EPROTONOSUPPORT']; <ide> assert.notEqual(allowed.indexOf(e.code), -1); <del> assert.equal(e.message, 'bind ' + e.code + ' 111::1:' + common.PORT); <add> assert.strictEqual(e.port, undefined); <add> assert.equal(e.message, 'bind ' + e.code + ' 111::1'); <ide> assert.equal(e.address, '111::1'); <del> assert.equal(e.port, common.PORT); <ide> socket_ipv6.close(); <ide> })); <ide> <del>socket_ipv6.bind(common.PORT, '111::1'); <add>socket_ipv6.bind(0, '111::1'); <ide><path>test/parallel/test-dgram-implicit-bind.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var dgram = require('dgram'); <ide> <ide> target.on('message', function(buf) { <ide> <ide> target.on('listening', function() { <ide> // Second .send() call should not throw a bind error. <del> source.send(Buffer.from('abc'), 0, 3, common.PORT, '127.0.0.1'); <del> source.send(Buffer.from('def'), 0, 3, common.PORT, '127.0.0.1'); <add> const port = this.address().port; <add> source.send(Buffer.from('abc'), 0, 3, port, '127.0.0.1'); <add> source.send(Buffer.from('def'), 0, 3, port, '127.0.0.1'); <ide> }); <ide> <del>target.bind(common.PORT); <add>target.bind(0); <ide><path>test/parallel/test-dgram-multicast-setTTL.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> const socket = dgram.createSocket('udp4'); <ide> let thrown = false; <ide> <del>socket.bind(common.PORT); <add>socket.bind(0); <ide> socket.on('listening', function() { <ide> socket.setMulticastTTL(16); <ide> <ide><path>test/parallel/test-dgram-send-callback-multi-buffer.js <ide> const buf1 = Buffer.alloc(256, 'x'); <ide> const buf2 = Buffer.alloc(256, 'y'); <ide> <ide> client.on('listening', function() { <del> client.send([buf1, buf2], common.PORT, common.localhostIPv4, messageSent); <add> const port = this.address().port; <add> client.send([buf1, buf2], port, common.localhostIPv4, messageSent); <ide> }); <ide> <ide> client.on('message', common.mustCall(function onMessage(buf, info) { <ide> client.on('message', common.mustCall(function onMessage(buf, info) { <ide> client.close(); <ide> })); <ide> <del>client.bind(common.PORT); <add>client.bind(0); <ide><path>test/parallel/test-dgram-send-callback-recursive.js <ide> let received = 0; <ide> let sent = 0; <ide> const limit = 10; <ide> let async = false; <add>let port; <ide> <ide> function onsend() { <ide> if (sent++ < limit) { <del> client.send( <del> chunk, 0, chunk.length, common.PORT, common.localhostIPv4, onsend); <add> client.send(chunk, 0, chunk.length, port, common.localhostIPv4, onsend); <ide> } else { <ide> assert.strictEqual(async, true, 'Send should be asynchronous.'); <ide> } <ide> } <ide> <ide> client.on('listening', function() { <add> port = this.address().port; <add> <ide> setImmediate(function() { <ide> async = true; <ide> }); <ide> client.on('close', common.mustCall(function() { <ide> assert.equal(received, limit); <ide> })); <ide> <del>client.bind(common.PORT); <add>client.bind(0); <ide><path>test/parallel/test-dgram-send-default-host.js <ide> const toSend = [Buffer.alloc(256, 'x'), <ide> const received = []; <ide> <ide> client.on('listening', common.mustCall(() => { <del> client.send(toSend[0], 0, toSend[0].length, common.PORT); <del> client.send(toSend[1], common.PORT); <del> client.send([toSend[2]], common.PORT); <del> client.send(toSend[3], 0, toSend[3].length, common.PORT); <add> const port = client.address().port; <add> client.send(toSend[0], 0, toSend[0].length, port); <add> client.send(toSend[1], port); <add> client.send([toSend[2]], port); <add> client.send(toSend[3], 0, toSend[3].length, port); <ide> })); <ide> <ide> client.on('message', common.mustCall((buf, info) => { <ide> client.on('message', common.mustCall((buf, info) => { <ide> } <ide> }, toSend.length)); <ide> <del>client.bind(common.PORT); <add>client.bind(0); <ide><path>test/parallel/test-dgram-send-empty-array.js <ide> client.on('message', common.mustCall(function onMessage(buf, info) { <ide> })); <ide> <ide> client.on('listening', function() { <del> client.send([], common.PORT, common.localhostIPv4); <add> client.send([], this.address().port, common.localhostIPv4); <ide> }); <ide> <del>client.bind(common.PORT); <add>client.bind(0); <ide><path>test/parallel/test-dgram-send-empty-buffer.js <ide> if (process.platform === 'darwin') { <ide> <ide> const client = dgram.createSocket('udp4'); <ide> <del>client.bind(common.PORT); <add>client.bind(0, function() { <add> const port = this.address().port; <ide> <del>client.on('message', common.mustCall(function onMessage(buffer, bytes) { <del> clearTimeout(timer); <del> client.close(); <del>})); <add> client.on('message', common.mustCall(function onMessage(buffer, bytes) { <add> clearTimeout(timer); <add> client.close(); <add> })); <ide> <del>const buf = Buffer.alloc(0); <del>client.send(buf, 0, 0, common.PORT, '127.0.0.1', function(err, len) { }); <add> const buf = Buffer.alloc(0); <add> client.send(buf, 0, 0, port, '127.0.0.1', function(err, len) { }); <ide> <del>const timer = setTimeout(function() { <del> throw new Error('Timeout'); <del>}, common.platformTimeout(200)); <add> const timer = setTimeout(function() { <add> throw new Error('Timeout'); <add> }, common.platformTimeout(200)); <add>}); <ide><path>test/parallel/test-dgram-send-multi-buffer-copy.js <ide> const buf2 = Buffer.alloc(256, 'y'); <ide> <ide> client.on('listening', function() { <ide> const toSend = [buf1, buf2]; <del> client.send(toSend, common.PORT, common.localhostIPv4, onMessage); <add> client.send(toSend, this.address().port, common.localhostIPv4, onMessage); <ide> toSend.splice(0, 2); <ide> }); <ide> <ide> client.on('message', common.mustCall(function onMessage(buf, info) { <ide> client.close(); <ide> })); <ide> <del>client.bind(common.PORT); <add>client.bind(0); <ide><path>test/parallel/test-dgram-setBroadcast.js <ide> runTest((socket) => { socket.setBroadcast(true); }, /EBADF/); <ide> <ide> // Should not throw if broadcast set to false after binding. <ide> runTest((socket) => { <del> socket.bind(common.PORT, common.localhostIPv4, () => { <add> socket.bind(0, common.localhostIPv4, () => { <ide> socket.setBroadcast(false); <ide> }); <ide> }); <ide> <ide> // Should not throw if broadcast set to true after binding. <ide> runTest((socket) => { <del> socket.bind(common.PORT, common.localhostIPv4, () => { <add> socket.bind(0, common.localhostIPv4, () => { <ide> socket.setBroadcast(true); <ide> }); <ide> }); <ide><path>test/parallel/test-dgram-setTTL.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> const socket = dgram.createSocket('udp4'); <ide> <del>socket.bind(common.PORT); <add>socket.bind(0); <ide> socket.on('listening', function() { <ide> var result = socket.setTTL(16); <ide> assert.strictEqual(result, 16); <ide><path>test/parallel/test-dgram-udp4.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <del>const server_port = common.PORT; <ide> const message_to_send = 'A message to send'; <ide> <ide> const server = dgram.createSocket('udp4'); <ide> server.on('message', common.mustCall((msg, rinfo) => { <ide> })); <ide> server.on('listening', common.mustCall(() => { <ide> const client = dgram.createSocket('udp4'); <add> const port = server.address().port; <ide> client.on('message', common.mustCall((msg, rinfo) => { <ide> assert.strictEqual(rinfo.address, common.localhostIPv4); <del> assert.strictEqual(rinfo.port, server_port); <add> assert.strictEqual(rinfo.port, port); <ide> assert.strictEqual(msg.toString(), message_to_send.toString()); <ide> client.close(); <ide> server.close(); <ide> })); <ide> client.send(message_to_send, <ide> 0, <ide> message_to_send.length, <del> server_port, <add> port, <ide> 'localhost'); <ide> client.on('close', common.mustCall(() => {})); <ide> })); <ide> server.on('close', common.mustCall(() => {})); <del>server.bind(server_port); <del> <add>server.bind(0); <ide><path>test/parallel/test-dgram-udp6-send-default-host.js <ide> const toSend = [Buffer.alloc(256, 'x'), <ide> const received = []; <ide> <ide> client.on('listening', common.mustCall(() => { <del> client.send(toSend[0], 0, toSend[0].length, common.PORT); <del> client.send(toSend[1], common.PORT); <del> client.send([toSend[2]], common.PORT); <del> client.send(toSend[3], 0, toSend[3].length, common.PORT); <add> const port = client.address().port; <add> client.send(toSend[0], 0, toSend[0].length, port); <add> client.send(toSend[1], port); <add> client.send([toSend[2]], port); <add> client.send(toSend[3], 0, toSend[3].length, port); <ide> })); <ide> <ide> client.on('message', common.mustCall((buf, info) => { <ide> client.on('message', common.mustCall((buf, info) => { <ide> } <ide> }, toSend.length)); <ide> <del>client.bind(common.PORT); <add>client.bind(0); <ide><path>test/parallel/test-domain-abort-on-uncaught.js <ide> const tests = [ <ide> const server = net.createServer(function(conn) { <ide> conn.pipe(conn); <ide> }); <del> server.listen(common.PORT, common.localhostIPv4, function() { <del> const conn = net.connect(common.PORT, common.localhostIPv4); <add> server.listen(0, common.localhostIPv4, function() { <add> const conn = net.connect(this.address().port, common.localhostIPv4); <ide> conn.once('data', function() { <ide> throw new Error('ok'); <ide> }); <ide><path>test/parallel/test-domain-http-server.js <ide> 'use strict'; <add>require('../common'); <ide> var domain = require('domain'); <ide> var http = require('http'); <ide> var assert = require('assert'); <del>var common = require('../common'); <ide> <ide> var objects = { foo: 'bar', baz: {}, num: 42, arr: [1, 2, 3] }; <ide> objects.baz.asdf = objects; <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, next); <add>server.listen(0, next); <ide> <ide> function next() { <del> console.log('listening on localhost:%d', common.PORT); <add> const port = this.address().port; <add> console.log('listening on localhost:%d', port); <ide> <ide> var requests = 0; <ide> var responses = 0; <ide> function next() { <ide> req.socket.destroy(); <ide> }); <ide> <del> var req = http.get({ host: 'localhost', port: common.PORT, path: p }); <add> var req = http.get({ host: 'localhost', port: port, path: p }); <ide> dom.add(req); <ide> req.on('response', function(res) { <ide> responses++; <ide><path>test/parallel/test-domain-multi.js <ide> 'use strict'; <ide> // Tests of multiple domains happening at once. <ide> <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var domain = require('domain'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> throw new Error('this kills domain B, not A'); <ide> })); <ide> <del>}).listen(common.PORT); <add>}).listen(0, function() { <add> var c = domain.create(); <add> var req = http.get({ host: 'localhost', port: this.address().port }); <ide> <del>var c = domain.create(); <del>var req = http.get({ host: 'localhost', port: common.PORT }); <add> // add the request to the C domain <add> c.add(req); <ide> <del>// add the request to the C domain <del>c.add(req); <del> <del>req.on('response', function(res) { <del> console.error('got response'); <del> // add the response object to the C domain <del> c.add(res); <del> res.pipe(process.stdout); <del>}); <add> req.on('response', function(res) { <add> console.error('got response'); <add> // add the response object to the C domain <add> c.add(res); <add> res.pipe(process.stdout); <add> }); <ide> <del>c.on('error', function(er) { <del> caughtC = true; <del> console.error('Error on c', er.message); <add> c.on('error', function(er) { <add> caughtC = true; <add> console.error('Error on c', er.message); <add> }); <ide> }); <ide> <ide> process.on('exit', function() { <ide><path>test/parallel/test-handle-wrap-isrefed.js <ide> function makeAssert(message) { <ide> { <ide> const assert = makeAssert('hasRef() not working on tcp_wrap'); <ide> const net = require('net'); <del> const server = net.createServer(() => {}).listen(common.PORT); <add> const server = net.createServer(() => {}).listen(0); <ide> assert(Object.getPrototypeOf(server._handle).hasOwnProperty('hasRef'), true); <ide> assert(server._handle.hasRef(), true); <ide> assert(server._unref, false); <ide><path>test/parallel/test-http-1.0-keep-alive.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> <ide> check([{ <ide> <ide> function check(tests) { <ide> var test = tests[0]; <del> if (test) http.createServer(server).listen(common.PORT, '127.0.0.1', client); <add> var server; <add> if (test) { <add> server = http.createServer(serverHandler).listen(0, '127.0.0.1', client); <add> } <ide> var current = 0; <ide> <ide> function next() { <ide> check(tests.slice(1)); <ide> } <ide> <del> function server(req, res) { <add> function serverHandler(req, res) { <ide> if (current + 1 === test.responses.length) this.close(); <ide> var ctx = test.responses[current]; <ide> console.error('< SERVER SENDING RESPONSE', ctx); <ide> function check(tests) { <ide> <ide> function client() { <ide> if (current === test.requests.length) return next(); <del> var conn = net.createConnection(common.PORT, '127.0.0.1', connected); <add> const port = server.address().port; <add> var conn = net.createConnection(port, '127.0.0.1', connected); <ide> <ide> function connected() { <ide> var ctx = test.requests[current]; <ide><path>test/parallel/test-http-1.0.js <ide> var http = require('http'); <ide> <ide> var body = 'hello world\n'; <ide> <del>var common_port = common.PORT; <del> <ide> function test(handler, request_generator, response_validator) { <del> var port = common_port++; <ide> var server = http.createServer(handler); <ide> <ide> var client_got_eof = false; <ide> var server_response = ''; <ide> <del> server.listen(port); <add> server.listen(0); <ide> server.on('listening', function() { <del> var c = net.createConnection(port); <add> var c = net.createConnection(this.address().port); <ide> <ide> c.setEncoding('utf8'); <ide> <ide><path>test/parallel/test-http-abort-before-end.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> var assert = require('assert'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> assert(false); // should not be called <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var req = http.request({method: 'GET', host: '127.0.0.1', port: common.PORT}); <add>server.listen(0, function() { <add> var req = http.request({ <add> method: 'GET', <add> host: '127.0.0.1', <add> port: this.address().port <add> }); <ide> <ide> req.on('error', function(ex) { <ide> // https://github.com/joyent/node/issues/1399#issuecomment-2597359 <ide><path>test/parallel/test-http-abort-client.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> var assert = require('assert'); <ide> <ide> var server = http.Server(function(req, res) { <ide> <ide> var responseClose = false; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> http.get({ <del> port: common.PORT, <add> port: this.address().port, <ide> headers: { connection: 'keep-alive' } <del> <ide> }, function(res) { <ide> server.close(); <ide> <ide><path>test/parallel/test-http-abort-queued.js <ide> 'use strict'; <add>require('../common'); <ide> const assert = require('assert'); <del>const common = require('../common'); <ide> const http = require('http'); <ide> <ide> var complete; <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> console.log('listen', server.address().port); <ide> <ide> var agent = new http.Agent({maxSockets: 1}); <ide><path>test/parallel/test-http-after-connect.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> server.on('connect', function(req, socket, firstBodyChunk) { <ide> socket.end(); <ide> }); <ide> }); <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'CONNECT', <ide> path: 'google.com:80' <ide> }); <ide> server.listen(common.PORT, function() { <ide> <ide> function doRequest(i) { <ide> http.get({ <del> port: common.PORT, <add> port: server.address().port, <ide> path: '/request' + i <ide> }, function(res) { <ide> console.error('Client got GET response'); <ide><path>test/parallel/test-http-agent-destroyed-socket.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.end('Hello World\n'); <del>}).listen(common.PORT); <add>}).listen(0, function() { <add> var agent = new http.Agent({maxSockets: 1}); <ide> <del>var agent = new http.Agent({maxSockets: 1}); <del> <del>agent.on('free', function(socket, host, port) { <del> console.log('freeing socket. destroyed? ', socket.destroyed); <del>}); <add> agent.on('free', function(socket, host, port) { <add> console.log('freeing socket. destroyed? ', socket.destroyed); <add> }); <ide> <del>var requestOptions = { <del> agent: agent, <del> host: 'localhost', <del> port: common.PORT, <del> path: '/' <del>}; <add> var requestOptions = { <add> agent: agent, <add> host: 'localhost', <add> port: this.address().port, <add> path: '/' <add> }; <ide> <del>var request1 = http.get(requestOptions, function(response) { <del> // assert request2 is queued in the agent <del> var key = agent.getName(requestOptions); <del> assert(agent.requests[key].length === 1); <del> console.log('got response1'); <del> request1.socket.on('close', function() { <del> console.log('request1 socket closed'); <del> }); <del> response.pipe(process.stdout); <del> response.on('end', function() { <del> console.log('response1 done'); <del> ///////////////////////////////// <del> // <del> // THE IMPORTANT PART <del> // <del> // It is possible for the socket to get destroyed and other work <del> // to run before the 'close' event fires because it happens on <del> // nextTick. This example is contrived because it destroys the <del> // socket manually at just the right time, but at Voxer we have <del> // seen cases where the socket is destroyed by non-user code <del> // then handed out again by an agent *before* the 'close' event <del> // is triggered. <del> request1.socket.destroy(); <add> var request1 = http.get(requestOptions, function(response) { <add> // assert request2 is queued in the agent <add> var key = agent.getName(requestOptions); <add> assert(agent.requests[key].length === 1); <add> console.log('got response1'); <add> request1.socket.on('close', function() { <add> console.log('request1 socket closed'); <add> }); <add> response.pipe(process.stdout); <add> response.on('end', function() { <add> console.log('response1 done'); <add> ///////////////////////////////// <add> // <add> // THE IMPORTANT PART <add> // <add> // It is possible for the socket to get destroyed and other work <add> // to run before the 'close' event fires because it happens on <add> // nextTick. This example is contrived because it destroys the <add> // socket manually at just the right time, but at Voxer we have <add> // seen cases where the socket is destroyed by non-user code <add> // then handed out again by an agent *before* the 'close' event <add> // is triggered. <add> request1.socket.destroy(); <ide> <del> response.once('close', function() { <del> // assert request2 was removed from the queue <del> assert(!agent.requests[key]); <del> console.log("waiting for request2.onSocket's nextTick"); <del> process.nextTick(function() { <del> // assert that the same socket was not assigned to request2, <del> // since it was destroyed. <del> assert(request1.socket !== request2.socket); <del> assert(!request2.socket.destroyed, 'the socket is destroyed'); <add> response.once('close', function() { <add> // assert request2 was removed from the queue <add> assert(!agent.requests[key]); <add> console.log("waiting for request2.onSocket's nextTick"); <add> process.nextTick(function() { <add> // assert that the same socket was not assigned to request2, <add> // since it was destroyed. <add> assert(request1.socket !== request2.socket); <add> assert(!request2.socket.destroyed, 'the socket is destroyed'); <add> }); <ide> }); <ide> }); <ide> }); <del>}); <ide> <del>var request2 = http.get(requestOptions, function(response) { <del> assert(!request2.socket.destroyed); <del> assert(request1.socket.destroyed); <del> // assert not reusing the same socket, since it was destroyed. <del> assert(request1.socket !== request2.socket); <del> console.log('got response2'); <del> var gotClose = false; <del> var gotResponseEnd = false; <del> request2.socket.on('close', function() { <del> console.log('request2 socket closed'); <del> gotClose = true; <del> done(); <del> }); <del> response.pipe(process.stdout); <del> response.on('end', function() { <del> console.log('response2 done'); <del> gotResponseEnd = true; <del> done(); <del> }); <add> var request2 = http.get(requestOptions, function(response) { <add> assert(!request2.socket.destroyed); <add> assert(request1.socket.destroyed); <add> // assert not reusing the same socket, since it was destroyed. <add> assert(request1.socket !== request2.socket); <add> console.log('got response2'); <add> var gotClose = false; <add> var gotResponseEnd = false; <add> request2.socket.on('close', function() { <add> console.log('request2 socket closed'); <add> gotClose = true; <add> done(); <add> }); <add> response.pipe(process.stdout); <add> response.on('end', function() { <add> console.log('response2 done'); <add> gotResponseEnd = true; <add> done(); <add> }); <ide> <del> function done() { <del> if (gotResponseEnd && gotClose) <del> server.close(); <del> } <add> function done() { <add> if (gotResponseEnd && gotClose) <add> server.close(); <add> } <add> }); <ide> }); <ide><path>test/parallel/test-http-agent-error-on-idle.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var Agent = http.Agent; <ide> <del>var agent = new Agent({ <del> keepAlive: true, <add>var server = http.createServer(function(req, res) { <add> res.end('hello world'); <ide> }); <ide> <del>var requestParams = { <del> host: 'localhost', <del> port: common.PORT, <del> agent: agent, <del> path: '/' <del>}; <del> <del>var socketKey = agent.getName(requestParams); <add>server.listen(0, function() { <add> var agent = new Agent({ <add> keepAlive: true, <add> }); <ide> <del>function get(callback) { <del> return http.get(requestParams, callback); <del>} <add> var requestParams = { <add> host: 'localhost', <add> port: this.address().port, <add> agent: agent, <add> path: '/' <add> }; <ide> <del>var server = http.createServer(function(req, res) { <del> res.end('hello world'); <del>}); <add> var socketKey = agent.getName(requestParams); <ide> <del>server.listen(common.PORT, function() { <ide> get(function(res) { <ide> assert.equal(res.statusCode, 200); <ide> res.resume(); <ide> server.listen(common.PORT, function() { <ide> }); <ide> }); <ide> }); <del>}); <ide> <del>function done() { <del> assert.equal(Object.keys(agent.freeSockets).length, 0, <del> 'expect the freeSockets pool to be empty'); <add> function get(callback) { <add> return http.get(requestParams, callback); <add> } <ide> <del> agent.destroy(); <del> server.close(); <del> process.exit(0); <del>} <add> function done() { <add> assert.equal(Object.keys(agent.freeSockets).length, 0, <add> 'expect the freeSockets pool to be empty'); <add> <add> agent.destroy(); <add> server.close(); <add> process.exit(0); <add> } <add>}); <ide><path>test/parallel/test-http-agent-keepalive.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const Agent = require('_http_agent').Agent; <ide> <add>let name; <add> <ide> const agent = new Agent({ <ide> keepAlive: true, <ide> keepAliveMsecs: 1000, <ide> const server = http.createServer(function(req, res) { <ide> function get(path, callback) { <ide> return http.get({ <ide> host: 'localhost', <del> port: common.PORT, <add> port: server.address().port, <ide> agent: agent, <ide> path: path <ide> }, callback); <ide> } <ide> <del>const name = 'localhost:' + common.PORT + ':'; <del> <ide> function checkDataAndSockets(body) { <ide> assert.equal(body.toString(), 'hello world'); <ide> assert.equal(agent.sockets[name].length, 1); <ide> function done() { <ide> process.exit(0); <ide> } <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> name = `localhost:${server.address().port}:`; <ide> // request first, and keep alive <ide> get('/first', function(res) { <ide> assert.equal(res.statusCode, 200); <ide><path>test/parallel/test-http-agent-maxsockets-regress-4050.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> const server = http.createServer(function(req, res) { <ide> function get(path, callback) { <ide> return http.get({ <ide> host: 'localhost', <del> port: common.PORT, <add> port: server.address().port, <ide> agent: agent, <ide> path: path <ide> }, callback); <ide> } <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var finished = 0; <ide> const num_requests = 6; <ide> for (var i = 0; i < num_requests; i++) { <ide><path>test/parallel/test-http-agent-maxsockets.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> function get(path, callback) { <ide> return http.get({ <ide> host: 'localhost', <del> port: common.PORT, <add> port: server.address().port, <ide> agent: agent, <ide> path: path <ide> }, callback); <ide> function done() { <ide> server.close(); <ide> } <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> get('/1', function(res) { <ide> assert.equal(res.statusCode, 200); <ide> res.resume(); <ide><path>test/parallel/test-http-agent-no-protocol.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> process.on('exit', function() { <ide> var server = http.createServer(function(req, res) { <ide> res.end(); <ide> request++; <del>}).listen(common.PORT, '127.0.0.1', function() { <del> var opts = url.parse('http://127.0.0.1:' + common.PORT + '/'); <add>}).listen(0, '127.0.0.1', function() { <add> var opts = url.parse(`http://127.0.0.1:${this.address().port}/`); <ide> <ide> // remove the `protocol` field… the `http` module should fall back <ide> // to "http:", as defined by the global, default `http.Agent` instance. <ide><path>test/parallel/test-http-agent-null.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> process.on('exit', function() { <ide> var server = http.createServer(function(req, res) { <ide> request++; <ide> res.end(); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> var options = { <ide> agent: null, <ide> port: this.address().port <ide><path>test/parallel/test-http-agent.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var responses = 0; <ide> var N = 4; <ide> var M = 4; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> const port = this.address().port; <ide> for (var i = 0; i < N; i++) { <ide> setTimeout(function() { <ide> for (var j = 0; j < M; j++) { <del> http.get({ port: common.PORT, path: '/' }, function(res) { <add> http.get({ port: port, path: '/' }, function(res) { <ide> console.log('%d %d', responses, res.statusCode); <ide> if (++responses == N * M) { <ide> console.error('Received all responses, closing server'); <ide><path>test/parallel/test-http-allow-req-after-204-res.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> var assert = require('assert'); <ide> <ide> function nextRequest() { <ide> console.error('writing request: %s', method); <ide> <ide> var request = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> method: method, <ide> path: '/' <ide> }, function(response) { <ide> function nextRequest() { <ide> request.end(); <ide> } <ide> <del>server.listen(common.PORT, nextRequest); <add>server.listen(0, nextRequest); <ide><path>test/parallel/test-http-automatic-headers.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.setHeader('X-Content-Length', 'baz'); <ide> res.end(); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <del> var agent = new http.Agent({ port: common.PORT, maxSockets: 1 }); <add> var agent = new http.Agent({ port: this.address().port, maxSockets: 1 }); <ide> http.get({ <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/hello', <ide> agent: agent <ide> }, function(res) { <ide><path>test/parallel/test-http-bind-twice.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> function dontCall() { <ide> } <ide> <ide> var server1 = http.createServer(dontCall); <del>server1.listen(common.PORT, '127.0.0.1', function() {}); <add>server1.listen(0, '127.0.0.1', function() { <add> var server2 = http.createServer(dontCall); <add> server2.listen(this.address().port, '127.0.0.1', dontCall); <ide> <del>var server2 = http.createServer(dontCall); <del>server2.listen(common.PORT, '127.0.0.1', dontCall); <del> <del>server2.on('error', function(e) { <del> assert.equal(e.code, 'EADDRINUSE'); <del> server1.close(); <del> gotError = true; <add> server2.on('error', function(e) { <add> assert.equal(e.code, 'EADDRINUSE'); <add> server1.close(); <add> gotError = true; <add> }); <ide> }); <del> <ide><path>test/parallel/test-http-blank-header.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <del> var c = net.createConnection(common.PORT); <add>server.listen(0, function() { <add> var c = net.createConnection(this.address().port); <ide> <ide> c.on('connect', function() { <ide> c.write('GET /blah HTTP/1.1\r\n' + <ide><path>test/parallel/test-http-buffer-sanity.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var web = http.Server(function(req, res) { <ide> <ide> var gotThanks = false; <ide> <del>web.listen(common.PORT, function() { <add>web.listen(0, function() { <ide> console.log('Making request'); <ide> <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'GET', <ide> path: '/', <ide> headers: { 'content-length': buffer.length } <ide><path>test/parallel/test-http-byteswritten.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var httpServer = http.createServer(function(req, res) { <ide> res.end(body); <ide> }); <ide> <del>httpServer.listen(common.PORT, function() { <del> http.get({ port: common.PORT }); <add>httpServer.listen(0, function() { <add> http.get({ port: this.address().port }); <ide> }); <ide><path>test/parallel/test-http-catch-uncaughtexception.js <ide> process.on('uncaughtException', uncaughtCallback); <ide> const server = http.createServer(function(req, res) { <ide> res.writeHead(200, { 'Content-Type': 'text/plain' }); <ide> res.end('bye'); <del>}).listen(common.PORT, function() { <del> http.get({ port: common.PORT }, function(res) { <add>}).listen(0, function() { <add> http.get({ port: this.address().port }, function(res) { <ide> res.resume(); <ide> throw new Error('get did fail'); <ide> }).on('close', function() { <ide><path>test/parallel/test-http-chunk-problem.js <ide> if (!common.hasCrypto) { <ide> if (process.argv[2] === 'request') { <ide> const http = require('http'); <ide> const options = { <del> port: common.PORT, <add> port: +process.argv[3], <ide> path: '/' <ide> }; <ide> <ide> const http = require('http'); <ide> const cp = require('child_process'); <ide> <ide> const filename = require('path').join(common.tmpDir, 'big'); <add>let server; <ide> <ide> function executeRequest(cb) { <ide> cp.exec([process.execPath, <ide> __filename, <ide> 'request', <add> server.address().port, <ide> '|', <ide> process.execPath, <ide> __filename, <ide> const ddcmd = common.ddCommand(filename, 10240); <ide> <ide> cp.exec(ddcmd, function(err, stdout, stderr) { <ide> if (err) throw err; <del> const server = http.createServer(function(req, res) { <add> server = http.createServer(function(req, res) { <ide> res.writeHead(200); <ide> <ide> // Create the subprocess <ide> cp.exec(ddcmd, function(err, stdout, stderr) { <ide> <ide> }); <ide> <del> server.listen(common.PORT, () => { <add> server.listen(0, () => { <ide> executeRequest(() => server.close()); <ide> }); <ide> }); <ide><path>test/parallel/test-http-chunked-304.js <ide> function test(statusCode, next) { <ide> server.close(); <ide> }); <ide> <del> server.listen(common.PORT, function() { <del> var conn = net.createConnection(common.PORT, function() { <add> server.listen(0, function() { <add> var conn = net.createConnection(this.address().port, function() { <ide> conn.write('GET / HTTP/1.1\r\n\r\n'); <ide> <ide> var resp = ''; <ide><path>test/parallel/test-http-chunked.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'}); <ide> res.end(UTF8_STRING, 'utf8'); <ide> }); <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var data = ''; <ide> var get = http.get({ <ide> path: '/', <ide> host: 'localhost', <del> port: common.PORT <add> port: this.address().port <ide> }, function(x) { <ide> x.setEncoding('utf8'); <ide> x.on('data', function(c) {data += c;}); <ide><path>test/parallel/test-http-client-abort-event.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <del>var common = require('../common'); <ide> var server = http.createServer(function(req, res) { <ide> res.end(); <ide> }); <ide> var count = 0; <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var req = http.request({ <del> port: common.PORT <add> port: this.address().port <ide> }, function() { <ide> assert(false, 'should not receive data'); <ide> }); <ide><path>test/parallel/test-http-client-abort.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> var responses = 0; <ide> const N = 8; <ide> const requests = []; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> console.log('Server listening.'); <ide> <ide> for (var i = 0; i < N; i++) { <ide> console.log('Making client ' + i); <del> var options = { port: common.PORT, path: '/?id=' + i }; <add> var options = { port: this.address().port, path: '/?id=' + i }; <ide> var req = http.get(options, function(res) { <ide> console.log('Client response code ' + res.statusCode); <ide> <ide><path>test/parallel/test-http-client-abort2.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.end('Hello'); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var req = http.get({port: common.PORT}, function(res) { <add>server.listen(0, function() { <add> var req = http.get({port: this.address().port}, function(res) { <ide> res.on('data', function(data) { <ide> req.abort(); <ide> server.close(); <ide><path>test/parallel/test-http-client-agent.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <del>var name = http.globalAgent.getName({ port: common.PORT }); <add>var name; <ide> var max = 3; <ide> var count = 0; <ide> <ide> var server = http.Server(function(req, res) { <ide> res.end('Hello, World!'); <ide> } <ide> }); <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> name = http.globalAgent.getName({ port: this.address().port }); <ide> for (var i = 0; i < max; ++i) { <ide> request(i); <ide> } <ide> }); <ide> <ide> function request(i) { <ide> var req = http.get({ <del> port: common.PORT, <add> port: server.address().port, <ide> path: '/' + i <ide> }, function(res) { <ide> var socket = req.socket; <ide><path>test/parallel/test-http-client-default-headers-exist.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> expectedMethods.forEach(function(method) { <ide> http.request({ <ide> method: method, <del> port: common.PORT <add> port: server.address().port <ide> }).end(); <ide> }); <ide> }); <ide><path>test/parallel/test-http-client-encoding.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> <ide> var http = require('http'); <ide> <ide> http.createServer(function(req, res) { <ide> res.end('ok\n'); <ide> this.close(); <del>}).listen(common.PORT, test); <add>}).listen(0, test); <ide> <ide> function test() { <ide> http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> encoding: 'utf8' <ide> }, function(res) { <ide> res.pipe(process.stdout); <ide><path>test/parallel/test-http-client-get-url.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> seen_req = true; <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> http.get('http://127.0.0.1:' + common.PORT + '/foo?bar'); <add>server.listen(0, function() { <add> http.get(`http://127.0.0.1:${this.address().port}/foo?bar`); <ide> }); <ide> <ide> process.on('exit', function() { <ide><path>test/parallel/test-http-client-parse-error.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> net.createServer(function(c) { <ide> c.end('bad http - should trigger parse error\r\n'); <ide> this.close(); <ide> } <del>}).listen(common.PORT, '127.0.0.1', function() { <add>}).listen(0, '127.0.0.1', function() { <ide> for (var i = 0; i < 2; i++) { <ide> http.request({ <ide> host: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'GET', <ide> path: '/' <ide> }).on('error', function(e) { <ide><path>test/parallel/test-http-client-race-2.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> var server = http.createServer(function(req, res) { <ide> {'Content-Type': 'text/plain', 'Content-Length': body.length}); <ide> res.end(body); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> var body1 = ''; <ide> var body2 = ''; <ide> var body3 = ''; <ide> <ide> server.on('listening', function() { <del> var client = http.createClient(common.PORT); <add> var client = http.createClient(this.address().port); <ide> <ide> // <ide> // Client #1 is assigned Parser #1 <ide> server.on('listening', function() { <ide> // parser that previously belonged to Client #1. But we're not finished <ide> // with Client #1 yet! <ide> // <del> var client2 = http.createClient(common.PORT); <add> var client2 = http.createClient(server.address().port); <ide> <ide> // <ide> // At this point, the bug would manifest itself and crash because the <ide><path>test/parallel/test-http-client-race.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> var server = http.createServer(function(req, res) { <ide> {'Content-Type': 'text/plain', 'Content-Length': body.length}); <ide> res.end(body); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> var body1 = ''; <ide> var body2 = ''; <ide> <ide> server.on('listening', function() { <del> var req1 = http.request({ port: common.PORT, path: '/1' }); <add> var req1 = http.request({ port: this.address().port, path: '/1' }); <ide> req1.end(); <ide> req1.on('response', function(res1) { <ide> res1.setEncoding('utf8'); <ide> server.on('listening', function() { <ide> }); <ide> <ide> res1.on('end', function() { <del> var req2 = http.request({ port: common.PORT, path: '/2' }); <add> var req2 = http.request({ port: server.address().port, path: '/2' }); <ide> req2.end(); <ide> req2.on('response', function(res2) { <ide> res2.setEncoding('utf8'); <ide><path>test/parallel/test-http-client-reject-chunked-with-content-length.js <ide> const server = net.createServer((socket) => { <ide> socket.write(reqstr); <ide> }); <ide> <del>server.listen(common.PORT, () => { <add>server.listen(0, () => { <ide> // The callback should not be called because the server is sending <ide> // both a Content-Length header and a Transfer-Encoding: chunked <ide> // header, which is a violation of the HTTP spec. <del> const req = http.get({port: common.PORT}, (res) => { <add> const req = http.get({port: server.address().port}, (res) => { <ide> assert.fail(null, null, 'callback should not be called'); <ide> }); <ide> req.on('error', common.mustCall((err) => { <ide><path>test/parallel/test-http-client-reject-cr-no-lf.js <ide> const server = net.createServer((socket) => { <ide> socket.write(reqstr); <ide> }); <ide> <del>server.listen(common.PORT, () => { <add>server.listen(0, () => { <ide> // The callback should not be called because the server is sending a <ide> // header field that ends only in \r with no following \n <del> const req = http.get({port: common.PORT}, (res) => { <add> const req = http.get({port: server.address().port}, (res) => { <ide> assert.fail(null, null, 'callback should not be called'); <ide> }); <ide> req.on('error', common.mustCall((err) => { <ide><path>test/parallel/test-http-client-timeout-agent.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var requests_sent = 0; <ide> var requests_done = 0; <ide> var options = { <ide> method: 'GET', <del> port: common.PORT, <add> port: undefined, <ide> host: '127.0.0.1', <ide> }; <ide> <ide> var server = http.createServer(function(req, res) { <ide> request_number += 1; <ide> }); <ide> <del>server.listen(options.port, options.host, function() { <add>server.listen(0, options.host, function() { <add> options.port = this.address().port; <ide> var req; <ide> <ide> for (requests_sent = 0; requests_sent < 30; requests_sent += 1) { <ide><path>test/parallel/test-http-client-timeout-event.js <ide> var http = require('http'); <ide> <ide> var options = { <ide> method: 'GET', <del> port: common.PORT, <add> port: undefined, <ide> host: '127.0.0.1', <ide> path: '/' <ide> }; <ide> var server = http.createServer(function(req, res) { <ide> // this space intentionally left blank <ide> }); <ide> <del>server.listen(options.port, options.host, function() { <add>server.listen(0, options.host, function() { <add> options.port = this.address().port; <ide> var req = http.request(options, function(res) { <ide> // this space intentionally left blank <ide> }); <ide><path>test/parallel/test-http-client-timeout-with-data.js <ide> process.on('exit', function() { <ide> <ide> const options = { <ide> method: 'GET', <del> port: common.PORT, <add> port: undefined, <ide> host: '127.0.0.1', <ide> path: '/' <ide> }; <ide> const server = http.createServer(function(req, res) { <ide> setTimeout(function() { res.end('*'); }, common.platformTimeout(100)); <ide> }); <ide> <del>server.listen(options.port, options.host, function() { <add>server.listen(0, options.host, function() { <add> options.port = this.address().port; <ide> const req = http.request(options, onresponse); <ide> req.end(); <ide> <ide><path>test/parallel/test-http-client-timeout.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var options = { <ide> method: 'GET', <del> port: common.PORT, <add> port: undefined, <ide> host: '127.0.0.1', <ide> path: '/' <ide> }; <ide> var server = http.createServer(function(req, res) { <ide> // this space intentionally left blank <ide> }); <ide> <del>server.listen(options.port, options.host, function() { <add>server.listen(0, options.host, function() { <add> options.port = this.address().port; <ide> var req = http.request(options, function(res) { <ide> // this space intentionally left blank <ide> }); <ide><path>test/parallel/test-http-client-upload-buf.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.end(); <ide> }); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'POST', <ide> path: '/' <ide> }, function(res) { <ide><path>test/parallel/test-http-client-upload.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.end(); <ide> }); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'POST', <ide> path: '/' <ide> }, function(res) { <ide><path>test/parallel/test-http-conn-reset.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> var caughtError = false; <ide> <ide> var options = { <ide> host: '127.0.0.1', <del> port: common.PORT <add> port: undefined <ide> }; <ide> <ide> // start a tcp server that closes incoming connections immediately <ide> var server = net.createServer(function(client) { <ide> client.destroy(); <ide> server.close(); <ide> }); <del>server.listen(options.port, options.host, onListen); <add>server.listen(0, options.host, onListen); <ide> <ide> // do a GET request, expect it to fail <ide> function onListen() { <add> options.port = this.address().port; <ide> var req = http.request(options, function(res) { <ide> assert.ok(false, 'this should never run'); <ide> }); <ide><path>test/parallel/test-http-connect-req-res.js <ide> server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) { <ide> socket.end(data); <ide> }); <ide> })); <del>server.listen(common.PORT, common.mustCall(function() { <add>server.listen(0, common.mustCall(function() { <ide> const req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'CONNECT', <ide> path: 'example.com:443' <ide> }, function(res) { <ide> server.listen(common.PORT, common.mustCall(function() { <ide> console.error('Client got CONNECT request'); <ide> <ide> // Make sure this request got removed from the pool. <del> const name = 'localhost:' + common.PORT; <add> const name = 'localhost:' + server.address().port; <ide> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <ide> assert(!http.globalAgent.requests.hasOwnProperty(name)); <ide> <ide><path>test/parallel/test-http-connect.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> server.on('connect', function(req, socket, firstBodyChunk) { <ide> socket.end(data); <ide> }); <ide> }); <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'CONNECT', <ide> path: 'google.com:443' <ide> }, function(res) { <ide> server.listen(common.PORT, function() { <ide> clientGotConnect = true; <ide> <ide> // Make sure this request got removed from the pool. <del> var name = 'localhost:' + common.PORT; <add> var name = 'localhost:' + server.address().port; <ide> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <ide> assert(!http.globalAgent.requests.hasOwnProperty(name)); <ide> <ide><path>test/parallel/test-http-content-length.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> if (totalRequests === receivedRequests) server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var req; <ide> <ide> req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'POST', <ide> path: '/multiple-writes' <ide> }); <ide> server.listen(common.PORT, function() { <ide> }); <ide> <ide> req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'POST', <ide> path: '/end-with-data' <ide> }); <ide> server.listen(common.PORT, function() { <ide> }); <ide> <ide> req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'POST', <ide> path: '/empty' <ide> }); <ide><path>test/parallel/test-http-contentLength0.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> <ide> // Simple test of Node's HTTP Client choking on a response <ide> var s = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Length': '0 '}); <ide> res.end(); <ide> }); <del>s.listen(common.PORT, function() { <add>s.listen(0, function() { <ide> <del> var request = http.request({ port: common.PORT }, function(response) { <add> var request = http.request({ port: this.address().port }, function(response) { <ide> console.log('STATUS: ' + response.statusCode); <ide> s.close(); <ide> response.resume(); <ide><path>test/parallel/test-http-createConnection.js <ide> const assert = require('assert'); <ide> <ide> const server = http.createServer(common.mustCall(function(req, res) { <ide> res.end(); <del>}, 4)).listen(common.PORT, '127.0.0.1', function() { <add>}, 4)).listen(0, '127.0.0.1', function() { <ide> let fn = common.mustCall(createConnection); <ide> http.get({ createConnection: fn }, function(res) { <ide> res.resume(); <ide> const server = http.createServer(common.mustCall(function(req, res) { <ide> }); <ide> <ide> function createConnection() { <del> return net.createConnection(common.PORT, '127.0.0.1'); <add> return net.createConnection(server.address().port, '127.0.0.1'); <ide> } <ide> <ide> function createConnectionAsync(options, cb) { <ide> setImmediate(function() { <del> cb(null, net.createConnection(common.PORT, '127.0.0.1')); <add> cb(null, net.createConnection(server.address().port, '127.0.0.1')); <ide> }); <ide> } <ide> <ide> function createConnectionBoth1(options, cb) { <del> const socket = net.createConnection(common.PORT, '127.0.0.1'); <add> const socket = net.createConnection(server.address().port, '127.0.0.1'); <ide> setImmediate(function() { <ide> cb(null, socket); <ide> }); <ide> return socket; <ide> } <ide> <ide> function createConnectionBoth2(options, cb) { <del> const socket = net.createConnection(common.PORT, '127.0.0.1'); <add> const socket = net.createConnection(server.address().port, '127.0.0.1'); <ide> cb(null, socket); <ide> return socket; <ide> } <ide><path>test/parallel/test-http-date-header.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> res.end(testResBody); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> <ide> server.addListener('listening', function() { <ide> var options = { <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET' <ide> }; <ide><path>test/parallel/test-http-default-encoding.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.Server(function(req, res) { <ide> <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'POST' <ide> }, function(res) { <ide><path>test/parallel/test-http-default-port.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const http = require('http'); <del>const PORT = common.PORT; <del>const SSLPORT = common.PORT + 1; <ide> const assert = require('assert'); <ide> const hostExpect = 'localhost'; <ide> const fs = require('fs'); <ide> process.on('exit', function() { <ide> console.log('ok'); <ide> }); <ide> <del>http.globalAgent.defaultPort = PORT; <ide> http.createServer(function(req, res) { <ide> assert.equal(req.headers.host, hostExpect); <del> assert.equal(req.headers['x-port'], PORT); <add> assert.equal(req.headers['x-port'], this.address().port); <ide> res.writeHead(200); <ide> res.end('ok'); <ide> this.close(); <del>}).listen(PORT, function() { <add>}).listen(0, function() { <add> http.globalAgent.defaultPort = this.address().port; <ide> http.get({ <ide> host: 'localhost', <ide> headers: { <del> 'x-port': PORT <add> 'x-port': this.address().port <ide> } <ide> }, function(res) { <ide> gotHttpResp = true; <ide> http.createServer(function(req, res) { <ide> }); <ide> <ide> if (common.hasCrypto) { <del> https.globalAgent.defaultPort = SSLPORT; <ide> https.createServer(options, function(req, res) { <ide> assert.equal(req.headers.host, hostExpect); <del> assert.equal(req.headers['x-port'], SSLPORT); <add> assert.equal(req.headers['x-port'], this.address().port); <ide> res.writeHead(200); <ide> res.end('ok'); <ide> this.close(); <del> }).listen(SSLPORT, function() { <add> }).listen(0, function() { <add> https.globalAgent.defaultPort = this.address().port; <ide> https.get({ <ide> host: 'localhost', <ide> rejectUnauthorized: false, <ide> headers: { <del> 'x-port': SSLPORT <add> 'x-port': this.address().port <ide> } <ide> }, function(res) { <ide> gotHttpsResp = true; <ide><path>test/parallel/test-http-destroyed-socket-write2.js <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'POST' <ide> }); <ide><path>test/parallel/test-http-double-content-length.js <ide> server.on('clientError', common.mustCall((err, socket) => { <ide> socket.destroy(); <ide> })); <ide> <del>server.listen(common.PORT, () => { <add>server.listen(0, () => { <ide> const req = http.get({ <del> port: common.PORT, <add> port: server.address().port, <ide> // Send two content-length header values. <ide> headers: {'Content-Length': [1, 2]}}, <ide> (res) => { <ide><path>test/parallel/test-http-end-throw-socket-handling.js <ide> const server = http.createServer((req, res) => { <ide> res.end('ok'); <ide> }); <ide> <del>server.listen(common.PORT, common.mustCall(() => { <add>server.listen(0, common.mustCall(() => { <ide> for (let i = 0; i < 10; i++) { <del> const options = { port: common.PORT }; <add> const options = { port: server.address().port }; <ide> const req = http.request(options, (res) => { <ide> res.resume(); <ide> res.on('end', common.mustCall(() => { <ide><path>test/parallel/test-http-eof-on-connect.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> <ide> var http = require('http'); <ide> // reproduceable on the first packet on the first connection to a server. <ide> <ide> var server = http.createServer(function(req, res) {}); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <del> net.createConnection(common.PORT).on('connect', function() { <add> net.createConnection(this.address().port).on('connect', function() { <ide> this.destroy(); <ide> }).on('close', function() { <ide> server.close(); <ide><path>test/parallel/test-http-exceptions.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> var server = http.createServer(function(req, res) { <ide> res.end(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> for (var i = 0; i < 4; i += 1) { <del> http.get({ port: common.PORT, path: '/busy/' + i }); <add> http.get({ port: this.address().port, path: '/busy/' + i }); <ide> } <ide> }); <ide> <ide><path>test/parallel/test-http-expect-continue.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> server.on('checkContinue', function(req, res) { <ide> handler(req, res); <ide> }, 100); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> <ide> server.on('listening', function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'POST', <ide> path: '/world', <ide> headers: { 'Expect': '100-continue' } <ide><path>test/parallel/test-http-expect-handling.js <ide> const s = http.createServer(function(req, res) { <ide> throw new Error('this should never be executed'); <ide> }); <ide> <del>s.listen(common.PORT, nextTest); <add>s.listen(0, nextTest); <ide> <ide> function nextTest() { <ide> const options = { <del> port: common.PORT, <add> port: s.address().port, <ide> headers: { 'Expect': 'meoww' } <ide> }; <ide> <ide><path>test/parallel/test-http-extra-response.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> var server = net.createServer(function(socket) { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <del> http.get({ port: common.PORT }, function(res) { <add>server.listen(0, function() { <add> http.get({ port: this.address().port }, function(res) { <ide> var buffer = ''; <ide> console.log('Got res code: ' + res.statusCode); <ide> <ide><path>test/parallel/test-http-flush-headers.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> server.on('request', function(req, res) { <ide> res.end('ok'); <ide> server.close(); <ide> }); <del>server.listen(common.PORT, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', function() { <ide> const req = http.request({ <ide> method: 'GET', <ide> host: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> }); <ide> req.setHeader('foo', 'bar'); <ide> req.flushHeaders(); <ide><path>test/parallel/test-http-flush-response-headers.js <ide> server.on('request', function(req, res) { <ide> res.flushHeaders(); <ide> res.flushHeaders(); // Should be idempotent. <ide> }); <del>server.listen(common.PORT, common.localhostIPv4, function() { <add>server.listen(0, common.localhostIPv4, function() { <ide> var req = http.request({ <ide> method: 'GET', <ide> host: common.localhostIPv4, <del> port: common.PORT, <add> port: this.address().port, <ide> }, onResponse); <ide> <ide> req.end(); <ide><path>test/parallel/test-http-flush.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> <ide> http.createServer(function(req, res) { <ide> res.end('ok'); <ide> this.close(); <del>}).listen(common.PORT, '127.0.0.1', function() { <add>}).listen(0, '127.0.0.1', function() { <ide> var req = http.request({ <ide> method: 'POST', <ide> host: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> }); <ide> req.flush(); // Flush the request headers. <ide> req.flush(); // Should be idempotent. <ide><path>test/parallel/test-http-full-response.js <ide> var server = http.createServer(function(req, res) { <ide> var runs = 0; <ide> <ide> function runAb(opts, callback) { <del> var command = 'ab ' + opts + ' http://127.0.0.1:' + common.PORT + '/'; <add> var command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; <ide> exec(command, function(err, stdout, stderr) { <ide> if (err) { <ide> if (/ab|apr/mi.test(stderr)) { <ide> function runAb(opts, callback) { <ide> }); <ide> } <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> runAb('-c 1 -n 10', function() { <ide> console.log('-c 1 -n 10 okay'); <ide> <ide><path>test/parallel/test-http-get-pipeline-problem.js <ide> var server = http.Server(function(req, res) { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> for (var i = 0; i < total; i++) { <ide> (function() { <ide> var x = i; <ide> <ide> var opts = { <del> port: common.PORT, <add> port: server.address().port, <ide> headers: { connection: 'close' } <ide> }; <ide> <ide><path>test/parallel/test-http-head-request.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <del> <ide> var body = 'hello world\n'; <del>var id = 0; <ide> <ide> function test(headers) { <del> var port = common.PORT + id++; <del> <ide> var server = http.createServer(function(req, res) { <ide> console.error('req: %s headers: %j', req.method, headers); <ide> res.writeHead(200, headers); <ide> function test(headers) { <ide> <ide> var gotEnd = false; <ide> <del> server.listen(port, function() { <add> server.listen(0, function() { <ide> var request = http.request({ <del> port: port, <add> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <ide> }, function(response) { <ide><path>test/parallel/test-http-head-response-has-no-body-end.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200); <ide> res.end('FAIL'); // broken: sends FAIL from hot path. <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> var responseComplete = false; <ide> <ide> server.on('listening', function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <ide> }, function(res) { <ide><path>test/parallel/test-http-head-response-has-no-body.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200); // broken: defaults to TE chunked <ide> res.end(); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> var responseComplete = false; <ide> <ide> server.on('listening', function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <ide> }, function(res) { <ide><path>test/parallel/test-http-header-obstext.js <ide> const assert = require('assert'); <ide> const server = http.createServer(common.mustCall((req, res) => { <ide> res.end('ok'); <ide> })); <del>server.listen(common.PORT, () => { <add>server.listen(0, () => { <ide> http.get({ <del> port: common.PORT, <add> port: server.address().port, <ide> headers: {'Test': 'Düsseldorf'} <ide> }, common.mustCall((res) => { <ide> assert.equal(res.statusCode, 200); <ide><path>test/parallel/test-http-header-read.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var s = http.createServer(function(req, res) { <ide> ); <ide> }); <ide> <del>s.listen(common.PORT, runTest); <add>s.listen(0, runTest); <ide> <ide> function runTest() { <del> http.get({ port: common.PORT }, function(response) { <add> http.get({ port: this.address().port }, function(response) { <ide> response.on('end', function() { <ide> s.close(); <ide> }); <ide><path>test/parallel/test-http-hex-write.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> http.createServer(function(q, s) { <ide> s.write('utf8\n'); <ide> s.end(); <ide> this.close(); <del>}).listen(common.PORT, function() { <del> http.request({ port: common.PORT }).on('response', function(res) { <add>}).listen(0, function() { <add> http.request({ port: this.address().port }).on('response', function(res) { <ide> res.setEncoding('ascii'); <ide> res.on('data', function(c) { <ide> data += c; <ide><path>test/parallel/test-http-host-header-ipv6-fail.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> const hostname = '::1'; <del>const port = common.PORT; <ide> <ide> function httpreq() { <ide> var req = http.request({ <ide> host: hostname, <del> port: port, <add> port: server.address().port, <ide> path: '/', <ide> method: 'GET' <ide> }); <ide> const server = http.createServer(common.mustCall(function(req, res) { <ide> server.close(true); <ide> })); <ide> <del>server.listen(port, hostname, () => httpreq()); <add>server.listen(0, hostname, () => httpreq()); <ide><path>test/parallel/test-http-host-headers.js <ide> 'use strict'; <add>require('../common'); <ide> const http = require('http'); <del>const common = require('../common'); <ide> const assert = require('assert'); <ide> const httpServer = http.createServer(reqHandler); <ide> <ide> function reqHandler(req, res) { <ide> if (req.url === '/setHostFalse5') { <ide> assert.equal(req.headers.host, undefined); <ide> } else { <del> assert.equal(req.headers.host, 'localhost:' + common.PORT, <add> assert.equal(req.headers.host, `localhost:${this.address().port}`, <ide> 'Wrong host header for req[' + req.url + ']: ' + <ide> req.headers.host); <ide> } <ide> testHttp(); <ide> <ide> function testHttp() { <ide> <del> console.log('testing http on port ' + common.PORT); <del> <ide> var counter = 0; <ide> <ide> function cb(res) { <ide> function testHttp() { <ide> res.resume(); <ide> } <ide> <del> httpServer.listen(common.PORT, function(er) { <del> console.error('listening on ' + common.PORT); <add> httpServer.listen(0, function(er) { <add> console.error(`test http server listening on ${this.address().port}`); <ide> <ide> if (er) throw er; <ide> <ide> function testHttp() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower); <ide> <ide> function testHttp() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> <ide> function testHttp() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> <ide> function testHttp() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> <ide> function testHttp() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> }); <ide><path>test/parallel/test-http-incoming-pipelined-socket-destroy.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> <ide> var http = require('http'); <ide> var net = require('net'); <ide> var server = http.createServer(function(req, res) { <ide> function generator(seeds) { <ide> return seeds.map(function(r) { <ide> return 'GET /' + r + ' HTTP/1.1\r\n' + <del> 'Host: localhost:' + common.PORT + '\r\n' + <add> `Host: localhost:${server.address().port}\r\n` + <ide> '\r\n' + <ide> '\r\n'; <ide> }).join(''); <ide> } <ide> <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var seeds = [ 3, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 ]; <del> var client = net.connect({ port: common.PORT }); <add> var client = net.connect({ port: this.address().port }); <ide> var done = 0; <ide> server.on('requestDone', function() { <ide> if (++done == seeds.length) { <ide><path>test/parallel/test-http-invalidheaderfield.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const EventEmitter = require('events'); <ide> const http = require('http'); <ide> const server = http.createServer(function(req, res) { <ide> }, TypeError); <ide> res.end(''); <ide> }); <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> <del> http.get({port: common.PORT}, function() { <add> http.get({port: this.address().port}, function() { <ide> ee.emit('done'); <ide> }); <ide> <ide> assert.throws( <ide> function() { <ide> var options = { <del> port: common.PORT, <add> port: server.address().port, <ide> headers: {'testing 123': 123} <ide> }; <ide> http.get(options, function() {}); <ide> server.listen(common.PORT, function() { <ide> assert.doesNotThrow( <ide> function() { <ide> var options = { <del> port: common.PORT, <add> port: server.address().port, <ide> headers: {'testing_123': 123} <ide> }; <ide> http.get(options, function() { <ide><path>test/parallel/test-http-keep-alive-close-on-header.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> var connectCount = 0; <ide> <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var agent = new http.Agent({ maxSockets: 1 }); <del> var name = agent.getName({ port: common.PORT }); <add> var name = agent.getName({ port: this.address().port }); <ide> var request = http.request({ <ide> method: 'GET', <ide> path: '/', <ide> headers: headers, <del> port: common.PORT, <add> port: this.address().port, <ide> agent: agent <ide> }, function(res) { <ide> assert.equal(1, agent.sockets[name].length); <ide> server.listen(common.PORT, function() { <ide> method: 'GET', <ide> path: '/', <ide> headers: headers, <del> port: common.PORT, <add> port: this.address().port, <ide> agent: agent <ide> }, function(res) { <ide> assert.equal(1, agent.sockets[name].length); <ide> server.listen(common.PORT, function() { <ide> method: 'GET', <ide> path: '/', <ide> headers: headers, <del> port: common.PORT, <add> port: this.address().port, <ide> agent: agent <ide> }, function(response) { <ide> response.on('end', function() { <ide><path>test/parallel/test-http-keep-alive.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> <ide> var agent = new http.Agent({maxSockets: 1}); <ide> var headers = {'connection': 'keep-alive'}; <del>var name = agent.getName({ port: common.PORT }); <add>var name; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> name = agent.getName({ port: this.address().port }); <ide> http.get({ <del> path: '/', headers: headers, port: common.PORT, agent: agent <add> path: '/', headers: headers, port: this.address().port, agent: agent <ide> }, function(response) { <ide> assert.equal(agent.sockets[name].length, 1); <ide> assert.equal(agent.requests[name].length, 2); <ide> response.resume(); <ide> }); <ide> <ide> http.get({ <del> path: '/', headers: headers, port: common.PORT, agent: agent <add> path: '/', headers: headers, port: this.address().port, agent: agent <ide> }, function(response) { <ide> assert.equal(agent.sockets[name].length, 1); <ide> assert.equal(agent.requests[name].length, 1); <ide> response.resume(); <ide> }); <ide> <ide> http.get({ <del> path: '/', headers: headers, port: common.PORT, agent: agent <add> path: '/', headers: headers, port: this.address().port, agent: agent <ide> }, function(response) { <ide> response.on('end', function() { <ide> assert.equal(agent.sockets[name].length, 1); <ide><path>test/parallel/test-http-keepalive-client.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> <ide> res.end(req.url); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0, function() { <add> makeRequest(expectRequests); <add>}); <ide> <ide> var agent = http.Agent({ keepAlive: true }); <ide> <ide> var expectRequests = 10; <ide> var actualRequests = 0; <ide> <ide> <del>makeRequest(expectRequests); <ide> function makeRequest(n) { <ide> if (n === 0) { <ide> server.close(); <ide> function makeRequest(n) { <ide> } <ide> <ide> var req = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> agent: agent, <ide> path: '/' + n <ide> }); <ide><path>test/parallel/test-http-keepalive-maxsockets.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> } <ide> res.end(req.url); <ide> }); <del>server.listen(common.PORT); <del> <del>var agent = http.Agent({ <del> keepAlive: true, <del> maxSockets: 5, <del> maxFreeSockets: 2 <del>}); <del> <del>// make 10 requests in parallel, <del>// then 10 more when they all finish. <del>function makeReqs(n, cb) { <del> for (var i = 0; i < n; i++) <del> makeReq(i, then); <del> <del> function then(er) { <del> if (er) <del> return cb(er); <del> else if (--n === 0) <del> setTimeout(cb, 100); <del> } <del>} <del> <del>function makeReq(i, cb) { <del> http.request({ <del> port: common.PORT, <del> path: '/' + i, <del> agent: agent <del> }, function(res) { <del> var data = ''; <del> res.setEncoding('ascii'); <del> res.on('data', function(c) { <del> data += c; <del> }); <del> res.on('end', function() { <del> assert.equal(data, '/' + i); <del> cb(); <del> }); <del> }).end(); <del>} <del> <del>var closed = false; <del>makeReqs(10, function(er) { <del> assert.ifError(er); <del> assert.equal(count(agent.freeSockets), 2); <del> assert.equal(count(agent.sockets), 0); <del> assert.equal(serverSockets.length, 5); <add>server.listen(0, function() { <add> var agent = http.Agent({ <add> keepAlive: true, <add> maxSockets: 5, <add> maxFreeSockets: 2 <add> }); <ide> <del> // now make 10 more reqs. <del> // should use the 2 free reqs from the pool first. <add> var closed = false; <ide> makeReqs(10, function(er) { <ide> assert.ifError(er); <ide> assert.equal(count(agent.freeSockets), 2); <ide> assert.equal(count(agent.sockets), 0); <del> assert.equal(serverSockets.length, 8); <add> assert.equal(serverSockets.length, 5); <ide> <del> agent.destroy(); <del> server.close(function() { <del> closed = true; <add> // now make 10 more reqs. <add> // should use the 2 free reqs from the pool first. <add> makeReqs(10, function(er) { <add> assert.ifError(er); <add> assert.equal(count(agent.freeSockets), 2); <add> assert.equal(count(agent.sockets), 0); <add> assert.equal(serverSockets.length, 8); <add> <add> agent.destroy(); <add> server.close(function() { <add> closed = true; <add> }); <ide> }); <ide> }); <del>}); <ide> <del>function count(sockets) { <del> return Object.keys(sockets).reduce(function(n, name) { <del> return n + sockets[name].length; <del> }, 0); <del>} <add> process.on('exit', function() { <add> assert(closed); <add> console.log('ok'); <add> }); <add> <add> // make 10 requests in parallel, <add> // then 10 more when they all finish. <add> function makeReqs(n, cb) { <add> for (var i = 0; i < n; i++) <add> makeReq(i, then); <add> <add> function then(er) { <add> if (er) <add> return cb(er); <add> else if (--n === 0) <add> setTimeout(cb, 100); <add> } <add> } <add> <add> function makeReq(i, cb) { <add> http.request({ <add> port: server.address().port, <add> path: '/' + i, <add> agent: agent <add> }, function(res) { <add> var data = ''; <add> res.setEncoding('ascii'); <add> res.on('data', function(c) { <add> data += c; <add> }); <add> res.on('end', function() { <add> assert.equal(data, '/' + i); <add> cb(); <add> }); <add> }).end(); <add> } <ide> <del>process.on('exit', function() { <del> assert(closed); <del> console.log('ok'); <add> function count(sockets) { <add> return Object.keys(sockets).reduce(function(n, name) { <add> return n + sockets[name].length; <add> }, 0); <add> } <ide> }); <add> <ide><path>test/parallel/test-http-keepalive-request.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> <ide> res.end(req.url); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0, function() { <add> makeRequest(expectRequests); <add>}); <ide> <ide> var agent = http.Agent({ keepAlive: true }); <ide> <ide> var expectRequests = 10; <ide> var actualRequests = 0; <ide> <ide> <del>makeRequest(expectRequests); <ide> function makeRequest(n) { <ide> if (n === 0) { <ide> server.close(); <ide> function makeRequest(n) { <ide> } <ide> <ide> var req = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> path: '/' + n, <ide> agent: agent <ide> }); <ide><path>test/parallel/test-http-legacy.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> var server = http.createServer(function(req, res) { <ide> req.resume(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var client = http.createClient(common.PORT); <add>server.listen(0, function() { <add> var client = http.createClient(this.address().port); <ide> var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'}); <ide> setTimeout(function() { <ide> req.end(); <ide><path>test/parallel/test-http-listening.js <ide> const server = http.createServer(); <ide> <ide> assert.strictEqual(server.listening, false); <ide> <del>server.listen(common.PORT, common.mustCall(() => { <add>server.listen(0, common.mustCall(() => { <ide> assert.strictEqual(server.listening, true); <ide> <ide> server.close(common.mustCall(() => { <ide><path>test/parallel/test-http-localaddress-bind-error.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> req.resume(); <ide> }); <ide> <del>server.listen(common.PORT, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', function() { <ide> http.request({ <ide> host: 'localhost', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET', <ide> localAddress: invalidLocalAddress <ide><path>test/parallel/test-http-localaddress.js <ide> var server = http.createServer(function(req, res) { <ide> req.resume(); <ide> }); <ide> <del>server.listen(common.PORT, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', function() { <ide> var options = { host: 'localhost', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET', <ide> localAddress: '127.0.0.2' }; <ide><path>test/parallel/test-http-malformed-request.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> <ide> if (++nrequests_completed == nrequests_expected) server.close(); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <del> var c = net.createConnection(common.PORT); <add> var c = net.createConnection(this.address().port); <ide> c.on('connect', function() { <ide> c.write('GET /hello?foo=%99bar HTTP/1.1\r\n\r\n'); <ide> c.end(); <ide><path>test/parallel/test-http-many-ended-pipelines.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> <ide> // no warnings should happen! <ide> var trace = console.trace; <ide> var server = http.createServer(function(req, res) { <ide> req.socket.destroy(); <ide> }); <ide> <del>server.listen(common.PORT); <del> <del>var client = net.connect({ port: common.PORT, allowHalfOpen: true }); <del>for (var i = 0; i < numRequests; i++) { <del> client.write('GET / HTTP/1.1\r\n' + <del> 'Host: some.host.name\r\n' + <del> '\r\n\r\n'); <del>} <del>client.end(); <del>client.pipe(process.stdout); <add>server.listen(0, function() { <add> var client = net.connect({ port: this.address().port, allowHalfOpen: true }); <add> for (var i = 0; i < numRequests; i++) { <add> client.write('GET / HTTP/1.1\r\n' + <add> 'Host: some.host.name\r\n' + <add> '\r\n\r\n'); <add> } <add> client.end(); <add> client.pipe(process.stdout); <add>}); <ide><path>test/parallel/test-http-max-headers-count.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> server.maxHeadersCount = max; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var maxAndExpected = [ // for client <ide> [20, 20], <ide> [1200, 1200], <ide> server.listen(common.PORT, function() { <ide> var max = maxAndExpected[responses][0]; <ide> var expected = maxAndExpected[responses][1]; <ide> var req = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> headers: headers <ide> }, function(res) { <ide> assert.equal(Object.keys(res.headers).length, expected); <ide><path>test/parallel/test-http-multi-line-headers.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var server = net.createServer(function(conn) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> http.get({host: '127.0.0.1', port: common.PORT}, function(res) { <add>server.listen(0, function() { <add> http.get({host: '127.0.0.1', port: this.address().port}, function(res) { <ide> assert.equal(res.headers['content-type'], <ide> 'text/plain; x-unix-mode=0600; name="hello.txt"'); <ide> gotResponse = true; <ide><path>test/parallel/test-http-mutable-headers.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var s = http.createServer(function(req, res) { <ide> res.end(content); <ide> }); <ide> <del>s.listen(common.PORT, nextTest); <add>s.listen(0, nextTest); <ide> <ide> <ide> function nextTest() { <ide> function nextTest() { <ide> <ide> var bufferedResponse = ''; <ide> <del> http.get({ port: common.PORT }, function(response) { <add> http.get({ port: s.address().port }, function(response) { <ide> console.log('TEST: ' + test); <ide> console.log('STATUS: ' + response.statusCode); <ide> console.log('HEADERS: '); <ide><path>test/parallel/test-http-no-content-length.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> var body = ''; <ide> var server = net.createServer(function(socket) { <ide> // Neither Content-Length nor Connection <ide> socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); <del>}).listen(common.PORT, function() { <del> http.get({port: common.PORT}, function(res) { <add>}).listen(0, function() { <add> http.get({port: this.address().port}, function(res) { <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { <ide> body += chunk; <ide><path>test/parallel/test-http-outgoing-finish.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> http.createServer(function(req, res) { <ide> write(res); <ide> }); <ide> this.close(); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'PUT' <ide> }); <ide> write(req); <ide><path>test/parallel/test-http-parser-free.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var N = 100; <ide> var server = http.createServer(function(req, res) { <ide> res.end('Hello'); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> http.globalAgent.maxSockets = 1; <ide> var parser; <ide> for (var i = 0; i < N; ++i) { <ide> (function makeRequest(i) { <del> var req = http.get({port: common.PORT}, function(res) { <add> var req = http.get({port: server.address().port}, function(res) { <ide> if (!parser) { <ide> parser = req.parser; <ide> } else { <ide><path>test/parallel/test-http-pause-resume-one-end.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.Server(function(req, res) { <ide> <ide> var dataCount = 0, endCount = 0; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var opts = { <del> port: common.PORT, <add> port: this.address().port, <ide> headers: { connection: 'close' } <ide> }; <ide> <ide><path>test/parallel/test-http-pause.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> }, 100); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'POST' <ide> }, function(res) { <ide><path>test/parallel/test-http-pipe-fs.js <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200); <ide> res.end(); <ide> }); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> http.globalAgent.maxSockets = 1; <ide> <ide> for (var i = 0; i < 2; ++i) { <ide> (function(i) { <ide> var req = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> method: 'POST', <ide> headers: { <ide> 'Content-Length': 5 <ide><path>test/parallel/test-http-pipeline-flood.js <ide> function parent() { <ide> connections++; <ide> }); <ide> <del> server.listen(common.PORT, function() { <add> server.listen(0, function() { <ide> const spawn = require('child_process').spawn; <del> const args = [__filename, 'child']; <add> const args = [__filename, 'child', this.address().port]; <ide> const child = spawn(process.execPath, args, { stdio: 'inherit' }); <ide> child.on('close', common.mustCall(function() { <ide> server.close(); <ide> function parent() { <ide> function child() { <ide> const net = require('net'); <ide> <del> const conn = net.connect({ port: common.PORT }); <add> const port = +process.argv[3]; <add> const conn = net.connect({ port: port }); <ide> <del> var req = 'GET / HTTP/1.1\r\nHost: localhost:' + <del> common.PORT + '\r\nAccept: */*\r\n\r\n'; <add> var req = `GET / HTTP/1.1\r\nHost: localhost:${port}\r\nAccept: */*\r\n\r\n`; <ide> <ide> req = new Array(10241).join(req); <ide> <ide><path>test/parallel/test-http-pipeline-regr-2639.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> var server = http.createServer(function(req, res) { <ide> setTimeout(function() { <ide> res.end(); <ide> }, (Math.random() * 100) | 0); <del>}).listen(common.PORT, function() { <del> const s = net.connect(common.PORT); <add>}).listen(0, function() { <add> const s = net.connect(this.address().port); <ide> <ide> var big = 'GET / HTTP/1.0\r\n\r\n'.repeat(COUNT); <ide> <ide><path>test/parallel/test-http-pipeline-regr-3332.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> const server = http.createServer(function(req, res) { <ide> client.end(); <ide> } <ide> }); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> var req = new Array(COUNT + 1).join('GET / HTTP/1.1\r\n\r\n'); <del> client = net.connect(common.PORT, function() { <add> client = net.connect(this.address().port, function() { <ide> client.write(req); <ide> }); <ide> <ide><path>test/parallel/test-http-pipeline-regr-3508.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> socket.end(); <ide> }); <ide> first.end('hello'); <del>}).listen(common.PORT, function() { <del> var s = net.connect(common.PORT); <add>}).listen(0, function() { <add> var s = net.connect(this.address().port); <ide> more = function() { <ide> s.write('GET / HTTP/1.1\r\n\r\n'); <ide> }; <ide><path>test/parallel/test-http-proxy.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <del>var PROXY_PORT = common.PORT; <del>var BACKEND_PORT = common.PORT + 1; <del> <ide> var cookies = [ <ide> 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', <ide> 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' <ide> var backend = http.createServer(function(req, res) { <ide> var proxy = http.createServer(function(req, res) { <ide> console.error('proxy req headers: ' + JSON.stringify(req.headers)); <ide> http.get({ <del> port: BACKEND_PORT, <add> port: backend.address().port, <ide> path: url.parse(req.url).pathname <ide> }, function(proxy_res) { <ide> <ide> function startReq() { <ide> if (nlistening < 2) return; <ide> <ide> http.get({ <del> port: PROXY_PORT, <add> port: proxy.address().port, <ide> path: '/test' <ide> }, function(res) { <ide> console.error('got res'); <ide> function startReq() { <ide> } <ide> <ide> console.error('listen proxy'); <del>proxy.listen(PROXY_PORT, startReq); <add>proxy.listen(0, startReq); <ide> <ide> console.error('listen backend'); <del>backend.listen(BACKEND_PORT, startReq); <add>backend.listen(0, startReq); <ide> <ide> process.on('exit', function() { <ide> assert.equal(body, 'hello world\n'); <ide><path>test/parallel/test-http-raw-headers.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> <ide> http.createServer(function(req, res) { <del> this.close(); <ide> var expectRawHeaders = [ <ide> 'Host', <del> 'localhost:' + common.PORT, <add> `localhost:${this.address().port}`, <ide> 'transfer-ENCODING', <ide> 'CHUNKED', <ide> 'x-BaR', <ide> http.createServer(function(req, res) { <ide> 'close' <ide> ]; <ide> var expectHeaders = { <del> host: 'localhost:' + common.PORT, <add> host: `localhost:${this.address().port}`, <ide> 'transfer-encoding': 'CHUNKED', <ide> 'x-bar': 'yoyoyo', <ide> connection: 'close' <ide> }; <del> <ide> var expectRawTrailers = [ <ide> 'x-bAr', <ide> 'yOyOyOy', <ide> http.createServer(function(req, res) { <ide> 'X-baR', <ide> 'OyOyOyO' <ide> ]; <del> <ide> var expectTrailers = { 'x-bar': 'yOyOyOy, OyOyOyO, yOyOyOy, OyOyOyO' }; <ide> <add> this.close(); <add> <ide> assert.deepStrictEqual(req.rawHeaders, expectRawHeaders); <ide> assert.deepStrictEqual(req.headers, expectHeaders); <ide> <ide> http.createServer(function(req, res) { <ide> ['X-foO', 'OxOxOxO'] <ide> ]); <ide> res.end('x f o o'); <del>}).listen(common.PORT, function() { <del> var req = http.request({ port: common.PORT, path: '/' }); <add>}).listen(0, function() { <add> var req = http.request({ port: this.address().port, path: '/' }); <ide> req.addTrailers([ <ide> ['x-bAr', 'yOyOyOy'], <ide> ['x-baR', 'OyOyOyO'], <ide><path>test/parallel/test-http-regr-gh-2821.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const http = require('http'); <ide> <ide> const server = http.createServer(function(req, res) { <ide> const server = http.createServer(function(req, res) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> <ide> const req = http.request({ <ide> method: 'POST', <del> port: common.PORT <add> port: this.address().port <ide> }); <ide> <ide> const payload = Buffer.alloc(16390, 'Й'); <ide><path>test/parallel/test-http-remove-header-stays-removed.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> process.on('exit', function() { <ide> console.log('ok'); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> http.get({ port: common.PORT }, function(res) { <add>server.listen(0, function() { <add> http.get({ port: this.address().port }, function(res) { <ide> assert.equal(200, res.statusCode); <ide> assert.deepStrictEqual(res.headers, { date: 'coffee o clock' }); <ide> <ide><path>test/parallel/test-http-request-dont-override-options.js <ide> http.createServer(function(req, res) { <ide> res.end('ok'); <ide> <ide> requests++; <del>}).listen(common.PORT).unref(); <del> <del>var agent = new http.Agent(); <del>agent.defaultPort = common.PORT; <del> <del>// options marked as explicitly undefined for readability <del>// in this test, they should STAY undefined as options should not <del>// be mutable / modified <del>var options = { <del> host: undefined, <del> hostname: common.localhostIPv4, <del> port: undefined, <del> defaultPort: undefined, <del> path: undefined, <del> method: undefined, <del> agent: agent <del>}; <del> <del>http.request(options, function(res) { <del> res.resume(); <del>}).end(); <del> <del>process.on('exit', function() { <del> assert.equal(requests, 1); <del> <del> assert.strictEqual(options.host, undefined); <del> assert.strictEqual(options.hostname, common.localhostIPv4); <del> assert.strictEqual(options.port, undefined); <del> assert.strictEqual(options.defaultPort, undefined); <del> assert.strictEqual(options.path, undefined); <del> assert.strictEqual(options.method, undefined); <del>}); <add>}).listen(0, function() { <add> var agent = new http.Agent(); <add> agent.defaultPort = this.address().port; <add> <add> // options marked as explicitly undefined for readability <add> // in this test, they should STAY undefined as options should not <add> // be mutable / modified <add> var options = { <add> host: undefined, <add> hostname: common.localhostIPv4, <add> port: undefined, <add> defaultPort: undefined, <add> path: undefined, <add> method: undefined, <add> agent: agent <add> }; <add> <add> http.request(options, function(res) { <add> res.resume(); <add> }).end(); <add> <add> process.on('exit', function() { <add> assert.equal(requests, 1); <add> <add> assert.strictEqual(options.host, undefined); <add> assert.strictEqual(options.hostname, common.localhostIPv4); <add> assert.strictEqual(options.port, undefined); <add> assert.strictEqual(options.defaultPort, undefined); <add> assert.strictEqual(options.path, undefined); <add> assert.strictEqual(options.method, undefined); <add> }); <add>}).unref(); <add> <ide><path>test/parallel/test-http-request-end-twice.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.Server(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.end('hello world\n'); <ide> }); <del>server.listen(common.PORT, function() { <del> var req = http.get({port: common.PORT}, function(res) { <add>server.listen(0, function() { <add> var req = http.get({port: this.address().port}, function(res) { <ide> res.on('end', function() { <ide> assert.ok(!req.end()); <ide> server.close(); <ide><path>test/parallel/test-http-request-end.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.Server(function(req, res) { <ide> <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'POST' <ide> }, function(res) { <ide><path>test/parallel/test-http-request-methods.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> <ide> // Test that the DELETE, PATCH and PURGE verbs get passed through correctly <ide> <ide> ['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) { <del> var port = common.PORT + index; <del> <ide> var server_response = ''; <ide> var received_method = null; <ide> <ide> var http = require('http'); <ide> res.write('world\n'); <ide> res.end(); <ide> }); <del> server.listen(port); <add> server.listen(0); <ide> <ide> server.on('listening', function() { <del> var c = net.createConnection(port); <add> var c = net.createConnection(this.address().port); <ide> <ide> c.setEncoding('utf8'); <ide> <ide><path>test/parallel/test-http-res-write-after-end.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.Server(function(req, res) { <ide> assert.equal(r, true, 'write after end should return true'); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> http.get({port: common.PORT}, function(res) { <add>server.listen(0, function() { <add> http.get({port: this.address().port}, function(res) { <ide> server.close(); <ide> }); <ide> }); <ide><path>test/parallel/test-http-res-write-end-dont-take-array.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> } <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> // just make a request, other tests handle responses <del> http.get({port: common.PORT}, function(res) { <add> http.get({port: this.address().port}, function(res) { <ide> res.resume(); <ide> // lazy serial test, because we can only call end once per request <ide> test += 1; <ide> // do it again to test .end(Buffer); <del> http.get({port: common.PORT}, function(res) { <add> http.get({port: server.address().port}, function(res) { <ide> res.resume(); <ide> server.close(); <ide> }); <ide><path>test/parallel/test-http-response-close.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> responseGotEnd = true; <ide> }); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <ide> console.error('make req'); <ide> http.get({ <del> port: common.PORT <add> port: this.address().port <ide> }, function(res) { <ide> console.error('got res'); <ide> res.on('data', function(data) { <ide><path>test/parallel/test-http-response-multi-content-length.js <ide> const server = http.createServer((req, res) => { <ide> <ide> var count = 0; <ide> <del>server.listen(common.PORT, common.mustCall(() => { <add>server.listen(0, common.mustCall(() => { <ide> for (let n = 1; n <= MAX_COUNT ; n++) { <ide> // This runs twice, the first time, the server will use <ide> // setHeader, the second time it uses writeHead. In either <ide> // case, the error handler must be called because the client <ide> // is not allowed to accept multiple content-length headers. <ide> http.get( <del> {port: common.PORT, headers: {'x-num': n}}, <add> {port: server.address().port, headers: {'x-num': n}}, <ide> (res) => { <ide> assert(false, 'client allowed multiple content-length headers.'); <ide> } <ide><path>test/parallel/test-http-response-multiheaders.js <ide> const server = http.createServer(function(req, res) { <ide> res.end('ok'); <ide> }); <ide> <del>server.listen(common.PORT, common.mustCall(function() { <add>server.listen(0, common.mustCall(function() { <ide> var count = 0; <ide> for (let n = 1; n <= 2 ; n++) { <ide> // this runs twice, the first time, the server will use <ide> server.listen(common.PORT, common.mustCall(function() { <ide> // value should be reported for the header fields listed <ide> // in the norepeat array. <ide> http.get( <del> {port: common.PORT, headers: {'x-num': n}}, <add> {port: this.address().port, headers: {'x-num': n}}, <ide> common.mustCall(function(res) { <ide> if (++count === 2) server.close(); <ide> for (const name of norepeat) { <ide><path>test/parallel/test-http-response-no-headers.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> function test(httpVersion, callback) { <ide> conn.end(reply); <ide> }); <ide> <del> server.listen(common.PORT, '127.0.0.1', function() { <add> server.listen(0, '127.0.0.1', function() { <ide> var options = { <ide> host: '127.0.0.1', <del> port: common.PORT <add> port: this.address().port <ide> }; <ide> <ide> var req = http.get(options, function(res) { <ide><path>test/parallel/test-http-response-readable.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var testServer = new http.Server(function(req, res) { <ide> res.end('Hello world'); <ide> }); <ide> <del>testServer.listen(common.PORT, function() { <del> http.get({ port: common.PORT }, function(res) { <add>testServer.listen(0, function() { <add> http.get({ port: this.address().port }, function(res) { <ide> assert.equal(res.readable, true, 'res.readable initially true'); <ide> res.on('end', function() { <ide> assert.equal(res.readable, false, 'res.readable set to false after end'); <ide><path>test/parallel/test-http-response-splitting.js <ide> const server = http.createServer((req, res) => { <ide> server.close(); <ide> res.end('ok'); <ide> }); <del>server.listen(common.PORT, () => { <add>server.listen(0, () => { <ide> const end = 'HTTP/1.1\r\n\r\n'; <del> const client = net.connect({port: common.PORT}, () => { <add> const client = net.connect({port: server.address().port}, () => { <ide> client.write(`GET ${str} ${end}`); <ide> client.write(`GET / ${end}`); <ide> client.write(`GET / ${end}`); <ide><path>test/parallel/test-http-response-status-message.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> var server = net.createServer(function(connection) { <ide> var runTest = function(testCaseIndex) { <ide> var testCase = testCases[testCaseIndex]; <ide> <del> http.get({ port: common.PORT, path: testCase.path }, function(response) { <add> http.get({ <add> port: server.address().port, <add> path: testCase.path <add> }, function(response) { <ide> console.log('client: expected status message: ' + testCase.statusMessage); <ide> console.log('client: actual status message: ' + response.statusMessage); <ide> assert.equal(testCase.statusMessage, response.statusMessage); <ide> var runTest = function(testCaseIndex) { <ide> }); <ide> }; <ide> <del>server.listen(common.PORT, function() { runTest(0); }); <add>server.listen(0, function() { runTest(0); }); <ide> <ide> process.on('exit', function() { <ide> assert.equal(testCases.length, testsComplete); <ide><path>test/parallel/test-http-server-client-error.js <ide> server.on('clientError', common.mustCall(function(err, socket) { <ide> server.close(); <ide> })); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> function next() { <ide> // Invalid request <del> const client = net.connect(common.PORT); <add> const client = net.connect(server.address().port); <ide> client.end('Oopsie-doopsie\r\n'); <ide> <ide> var chunks = ''; <ide> server.listen(common.PORT, function() { <ide> } <ide> <ide> // Normal request <del> http.get({ port: common.PORT, path: '/' }, function(res) { <add> http.get({ port: this.address().port, path: '/' }, function(res) { <ide> assert.equal(res.statusCode, 200); <ide> res.resume(); <ide> res.once('end', next); <ide><path>test/parallel/test-http-server-consumed-timeout.js <ide> const server = http.createServer((req, res) => { <ide> })); <ide> }); <ide> <del>server.listen(common.PORT, common.mustCall(() => { <add>server.listen(0, common.mustCall(() => { <ide> const req = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> method: 'POST' <ide> }, (res) => { <ide> const interval = setInterval(() => { <ide><path>test/parallel/test-http-server-multiheaders.js <ide> // of the same header as per RFC2616: joining the handful of fields by ', ' <ide> // that support it, and dropping duplicates for other fields. <ide> <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var srv = http.createServer(function(req, res) { <ide> srv.close(); <ide> }); <ide> <del>srv.listen(common.PORT, function() { <add>srv.listen(0, function() { <ide> http.get({ <ide> host: 'localhost', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> headers: [ <ide> ['accept', 'abc'], <ide><path>test/parallel/test-http-server-multiheaders2.js <ide> // of the same header as per RFC2616: joining the handful of fields by ', ' <ide> // that support it, and dropping duplicates for other fields. <ide> <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var headers = [] <ide> .concat(multipleAllowed.map(makeHeader('bar'))) <ide> .concat(multipleForbidden.map(makeHeader('bar'))); <ide> <del>srv.listen(common.PORT, function() { <add>srv.listen(0, function() { <ide> http.get({ <ide> host: 'localhost', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> headers: headers, <ide> }); <ide><path>test/parallel/test-http-server-reject-chunked-with-content-length.js <ide> server.on('clientError', common.mustCall((err) => { <ide> assert.equal(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); <ide> server.close(); <ide> })); <del>server.listen(common.PORT, () => { <del> const client = net.connect({port: common.PORT}, () => { <add>server.listen(0, () => { <add> const client = net.connect({port: server.address().port}, () => { <ide> client.write(reqstr); <ide> client.end(); <ide> }); <ide><path>test/parallel/test-http-server-reject-cr-no-lf.js <ide> server.on('clientError', common.mustCall((err) => { <ide> assert.equal(err.code, 'HPE_LF_EXPECTED'); <ide> server.close(); <ide> })); <del>server.listen(common.PORT, () => { <del> const client = net.connect({port: common.PORT}, () => { <add>server.listen(0, () => { <add> const client = net.connect({port: server.address().port}, () => { <ide> client.on('data', (chunk) => { <ide> assert.fail(null, null, 'this should not be called'); <ide> }); <ide><path>test/parallel/test-http-server-stale-close.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> var util = require('util'); <ide> var fork = require('child_process').fork; <ide> <del>if (process.env.NODE_TEST_FORK) { <add>if (process.env.NODE_TEST_FORK_PORT) { <ide> var req = http.request({ <ide> headers: {'Content-Length': '42'}, <ide> method: 'POST', <ide> host: '127.0.0.1', <del> port: common.PORT, <add> port: +process.env.NODE_TEST_FORK_PORT, <ide> }, process.exit); <ide> req.write('BAM'); <ide> req.end(); <ide> else { <ide> res.end(); <ide> }); <ide> }); <del> server.listen(common.PORT, function() { <add> server.listen(0, function() { <ide> fork(__filename, { <del> env: util._extend(process.env, {NODE_TEST_FORK: '1'}) <add> env: util._extend(process.env, {NODE_TEST_FORK_PORT: this.address().port}) <ide> }); <ide> }); <ide> } <ide><path>test/parallel/test-http-server-unconsume.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> server.close(); <del>}).listen(common.PORT, function() { <del> var socket = net.connect(common.PORT, function() { <add>}).listen(0, function() { <add> var socket = net.connect(this.address().port, function() { <ide> socket.write('PUT / HTTP/1.1\r\n\r\n'); <ide> <ide> socket.once('data', function() { <ide><path>test/parallel/test-http-server.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> }, 1); <ide> <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.httpAllowHalfOpen = true; <ide> <ide> server.on('listening', function() { <del> var c = net.createConnection(common.PORT); <add> var c = net.createConnection(this.address().port); <ide> <ide> c.setEncoding('utf8'); <ide> <ide><path>test/parallel/test-http-set-cookies.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.end('two\n'); <ide> } <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <ide> // <ide> // one set-cookie header <ide> // <del> http.get({ port: common.PORT, path: '/one' }, function(res) { <add> http.get({ port: this.address().port, path: '/one' }, function(res) { <ide> // set-cookie headers are always return in an array. <ide> // even if there is only one. <ide> assert.deepStrictEqual(['A'], res.headers['set-cookie']); <ide> server.on('listening', function() { <ide> <ide> // two set-cookie headers <ide> <del> http.get({ port: common.PORT, path: '/two' }, function(res) { <add> http.get({ port: this.address().port, path: '/two' }, function(res) { <ide> assert.deepStrictEqual(['A', 'B'], res.headers['set-cookie']); <ide> assert.equal('text/plain', res.headers['content-type']); <ide> <ide><path>test/parallel/test-http-set-timeout.js <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); <add>server.listen(0, function() { <add> console.log(`Server running at http://127.0.0.1:${this.address().port}/`); <ide> <ide> var errorTimer = setTimeout(function() { <ide> throw new Error('Timeout was not successful'); <ide> }, common.platformTimeout(2000)); <ide> <del> var x = http.get({port: common.PORT, path: '/'}); <add> var x = http.get({port: this.address().port, path: '/'}); <ide> x.on('error', function() { <ide> clearTimeout(errorTimer); <ide> console.log('HTTP REQUEST COMPLETE (this is good)'); <ide><path>test/parallel/test-http-set-trailers.js <ide> var server = http.createServer(function(req, res) { <ide> res.addTrailers({'x-foo': 'bar'}); <ide> res.end('stuff' + '\n'); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> <ide> // first, we test an HTTP/1.0 request. <ide> server.on('listening', function() { <del> var c = net.createConnection(common.PORT); <add> var c = net.createConnection(this.address().port); <ide> var res_buffer = ''; <ide> <ide> c.setEncoding('utf8'); <ide> server.on('listening', function() { <ide> <ide> // now, we test an HTTP/1.1 request. <ide> server.on('listening', function() { <del> var c = net.createConnection(common.PORT); <add> var c = net.createConnection(this.address().port); <ide> var res_buffer = ''; <ide> var tid; <ide> <ide> server.on('listening', function() { <ide> <ide> // now, see if the client sees the trailers. <ide> server.on('listening', function() { <del> http.get({ port: common.PORT, path: '/hello', headers: {} }, function(res) { <add> http.get({ <add> port: this.address().port, <add> path: '/hello', <add> headers: {} <add> }, function(res) { <ide> res.on('end', function() { <ide> //console.log(res.trailers); <ide> assert.ok('x-foo' in res.trailers, 'Client doesn\'t see trailers.'); <ide><path>test/parallel/test-http-should-keep-alive.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> http.globalAgent.maxSockets = 5; <ide> var server = net.createServer(function(socket) { <ide> socket.write(SERVER_RESPONSES[requests]); <ide> ++requests; <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> function makeRequest() { <del> var req = http.get({port: common.PORT}, function(res) { <add> var req = http.get({port: server.address().port}, function(res) { <ide> assert.equal(req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], <ide> SERVER_RESPONSES[responses] + ' should ' + <ide> (SHOULD_KEEP_ALIVE[responses] ? '' : 'not ') + <ide><path>test/parallel/test-http-status-code.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var s = http.createServer(function(req, res) { <ide> res.end('hello world\n'); <ide> }); <ide> <del>s.listen(common.PORT, nextTest); <add>s.listen(0, nextTest); <ide> <ide> <ide> function nextTest() { <ide> function nextTest() { <ide> } <ide> var test = tests[testIdx]; <ide> <del> http.get({ port: common.PORT }, function(response) { <add> http.get({ port: s.address().port }, function(response) { <ide> console.log('client: expected status: ' + test); <ide> console.log('client: statusCode: ' + response.statusCode); <ide> assert.equal(response.statusCode, test); <ide><path>test/parallel/test-http-status-message.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> var s = http.createServer(function(req, res) { <ide> res.end(''); <ide> }); <ide> <del>s.listen(common.PORT, test); <add>s.listen(0, test); <ide> <ide> <ide> function test() { <ide> var bufs = []; <del> var client = net.connect(common.PORT, function() { <add> var client = net.connect(this.address().port, function() { <ide> client.write('GET / HTTP/1.1\r\nConnection: close\r\n\r\n'); <ide> }); <ide> client.on('data', function(chunk) { <ide><path>test/parallel/test-http-timeout-overflow.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> <del>var port = common.PORT; <ide> var serverRequests = 0; <ide> var clientRequests = 0; <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.end('OK'); <ide> }); <ide> <del>server.listen(port, function() { <add>server.listen(0, function() { <ide> function callback() {} <ide> <ide> var req = http.request({ <del> port: port, <add> port: this.address().port, <ide> path: '/', <ide> agent: false <ide> }, function(res) { <ide><path>test/parallel/test-http-timeout.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> <ide> var http = require('http'); <ide> <del>var port = common.PORT; <del> <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.end('OK'); <ide> }); <ide> <ide> var agent = new http.Agent({maxSockets: 1}); <ide> <del>server.listen(port, function() { <add>server.listen(0, function() { <ide> <ide> for (var i = 0; i < 11; ++i) { <ide> createRequest().end(); <ide> server.listen(port, function() { <ide> <ide> function createRequest() { <ide> const req = http.request( <del> {port: port, path: '/', agent: agent}, <add> {port: server.address().port, path: '/', agent: agent}, <ide> function(res) { <ide> req.clearTimeout(callback); <ide> <ide><path>test/parallel/test-http-upgrade-advertise.js <ide> function fire() { <ide> }); <ide> <ide> const req = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> path: '/', <ide> headers: test.headers <ide> }, function onResponse(res) { <ide> const server = http.createServer(function(req, res) { <ide> 'Connection: upgrade\r\n' + <ide> 'Upgrade: h2c\r\n\r\n' + <ide> 'ohai'); <del>}).listen(common.PORT, fire); <add>}).listen(0, fire); <ide><path>test/parallel/test-http-upgrade-agent.js <ide> var srv = net.createServer(function(c) { <ide> <ide> var gotUpgrade = false; <ide> <del>srv.listen(common.PORT, '127.0.0.1', function() { <add>srv.listen(0, '127.0.0.1', function() { <ide> <ide> var options = { <del> port: common.PORT, <add> port: this.address().port, <ide> host: '127.0.0.1', <ide> headers: { <ide> 'connection': 'upgrade', <ide><path>test/parallel/test-http-upgrade-client.js <ide> var srv = net.createServer(function(c) { <ide> <ide> var gotUpgrade = false; <ide> <del>srv.listen(common.PORT, '127.0.0.1', function() { <add>srv.listen(0, '127.0.0.1', function() { <ide> <ide> var req = http.get({ <del> port: common.PORT, <add> port: this.address().port, <ide> headers: { <ide> connection: 'upgrade', <ide> upgrade: 'websocket' <ide><path>test/parallel/test-http-upgrade-client2.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> server.on('upgrade', function(req, socket, head) { <ide> <ide> var successCount = 0; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> <ide> function upgradeRequest(fn) { <ide> console.log('req'); <ide> var header = { 'Connection': 'Upgrade', 'Upgrade': 'Test' }; <del> var request = http.request({ port: common.PORT, headers: header }); <add> var request = http.request({ <add> port: server.address().port, <add> headers: header <add> }); <ide> var wasUpgrade = false; <ide> <ide> function onUpgrade(res, socket, head) { <ide><path>test/parallel/test-http-upgrade-server.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var util = require('util'); <ide> function createTestServer() { <ide> } <ide> <ide> function testServer() { <del> var server = this; <del> http.Server.call(server, function() {}); <add> http.Server.call(this, function() {}); <ide> <del> server.on('connection', function() { <add> this.on('connection', function() { <ide> requests_recv++; <ide> }); <ide> <del> server.on('request', function(req, res) { <add> this.on('request', function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.write('okay'); <ide> res.end(); <ide> }); <ide> <del> server.on('upgrade', function(req, socket, upgradeHead) { <add> this.on('upgrade', function(req, socket, upgradeHead) { <ide> socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + <ide> 'Upgrade: WebSocket\r\n' + <ide> 'Connection: Upgrade\r\n' + <ide> function writeReq(socket, data, encoding) { <ide> /*----------------------------------------------- <ide> connection: Upgrade with listener <ide> -----------------------------------------------*/ <del>function test_upgrade_with_listener(_server) { <del> var conn = net.createConnection(common.PORT); <add>function test_upgrade_with_listener() { <add> var conn = net.createConnection(server.address().port); <ide> conn.setEncoding('utf8'); <ide> var state = 0; <ide> <ide> function test_upgrade_with_listener(_server) { <ide> conn.on('end', function() { <ide> assert.equal(2, state); <ide> conn.end(); <del> _server.removeAllListeners('upgrade'); <add> server.removeAllListeners('upgrade'); <ide> test_upgrade_no_listener(); <ide> }); <ide> } <ide> function test_upgrade_with_listener(_server) { <ide> var test_upgrade_no_listener_ended = false; <ide> <ide> function test_upgrade_no_listener() { <del> var conn = net.createConnection(common.PORT); <add> var conn = net.createConnection(server.address().port); <ide> conn.setEncoding('utf8'); <ide> <ide> conn.on('connect', function() { <ide> function test_upgrade_no_listener() { <ide> connection: normal <ide> -----------------------------------------------*/ <ide> function test_standard_http() { <del> var conn = net.createConnection(common.PORT); <add> var conn = net.createConnection(server.address().port); <ide> conn.setEncoding('utf8'); <ide> <ide> conn.on('connect', function() { <ide> function test_standard_http() { <ide> <ide> var server = createTestServer(); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> // All tests get chained after this: <del> test_upgrade_with_listener(server); <add> test_upgrade_with_listener(); <ide> }); <ide> <ide> <ide><path>test/parallel/test-http-upgrade-server2.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> process.on('uncaughtException', function(e) { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <del> var c = net.createConnection(common.PORT); <add>server.listen(0, function() { <add> var c = net.createConnection(this.address().port); <ide> <ide> c.on('connect', function() { <ide> c.write('GET /blah HTTP/1.1\r\n' + <ide><path>test/parallel/test-http-url.parse-auth-with-header-in-request.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <del>var testURL = url.parse('http://asdf:qwer@localhost:' + common.PORT); <del>// the test here is if you set a specific authorization header in the <del>// request we should not override that with basic auth <del>testURL.headers = { <del> Authorization: 'NoAuthForYOU' <del>}; <del> <ide> function check(request) { <ide> // the correct authorization header is be passed <ide> assert.strictEqual(request.headers.authorization, 'NoAuthForYOU'); <ide> var server = http.createServer(function(request, response) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> var testURL = url.parse(`http://asdf:qwer@localhost:${this.address().port}`); <add> // the test here is if you set a specific authorization header in the <add> // request we should not override that with basic auth <add> testURL.headers = { <add> Authorization: 'NoAuthForYOU' <add> }; <add> <ide> // make the request <ide> http.request(testURL).end(); <ide> }); <ide><path>test/parallel/test-http-url.parse-auth.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <del>// username = "user", password = "pass:" <del>var testURL = url.parse('http://user:pass%3A@localhost:' + common.PORT); <del> <ide> function check(request) { <ide> // the correct authorization header is be passed <ide> assert.strictEqual(request.headers.authorization, 'Basic dXNlcjpwYXNzOg=='); <ide> var server = http.createServer(function(request, response) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> const port = this.address().port; <add> // username = "user", password = "pass:" <add> var testURL = url.parse(`http://user:pass%3A@localhost:${port}`); <add> <ide> // make the request <ide> http.request(testURL).end(); <ide> }); <ide><path>test/parallel/test-http-url.parse-basic.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <del>var testURL = url.parse('http://localhost:' + common.PORT); <add>var testURL; <ide> <ide> // make sure the basics work <ide> function check(request) { <ide> var server = http.createServer(function(request, response) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> testURL = url.parse(`http://localhost:${this.address().port}`); <add> <ide> // make the request <ide> var clientRequest = http.request(testURL); <ide> // since there is a little magic with the agent <ide><path>test/parallel/test-http-url.parse-https.request.js <ide> var httpsOptions = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }; <ide> <del>var testURL = url.parse('https://localhost:' + common.PORT); <del>testURL.rejectUnauthorized = false; <del> <ide> function check(request) { <ide> // assert that I'm https <ide> assert.ok(request.socket._secureEstablished); <ide> var server = https.createServer(httpsOptions, function(request, response) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> var testURL = url.parse(`https://localhost:${this.address().port}`); <add> testURL.rejectUnauthorized = false; <add> <ide> // make the request <ide> var clientRequest = https.request(testURL); <ide> // since there is a little magic with the agent <ide><path>test/parallel/test-http-url.parse-path.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <del>var testURL = url.parse('http://localhost:' + common.PORT + '/asdf'); <del> <ide> function check(request) { <ide> // a path should come over <ide> assert.strictEqual(request.url, '/asdf'); <ide> var server = http.createServer(function(request, response) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> var testURL = url.parse(`http://localhost:${this.address().port}/asdf`); <add> <ide> // make the request <ide> http.request(testURL).end(); <ide> }); <ide><path>test/parallel/test-http-url.parse-post.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <del>var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); <del>testURL.method = 'POST'; <add>var testURL; <ide> <ide> function check(request) { <ide> //url.parse should not mess with the method <ide> var server = http.createServer(function(request, response) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> testURL = url.parse(`http://localhost:${this.address().port}/asdf?qwer=zxcv`); <add> testURL.method = 'POST'; <add> <ide> // make the request <ide> http.request(testURL).end(); <ide> }); <ide><path>test/parallel/test-http-url.parse-search.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <del>var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); <del> <ide> function check(request) { <ide> // a path should come over with params <ide> assert.strictEqual(request.url, '/asdf?qwer=zxcv'); <ide> var server = http.createServer(function(request, response) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <add> const port = this.address().port; <add> var testURL = url.parse(`http://localhost:${port}/asdf?qwer=zxcv`); <add> <ide> // make the request <ide> http.request(testURL).end(); <ide> }); <ide><path>test/parallel/test-http-wget.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> res.write('world\n'); <ide> res.end(); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <del> var c = net.createConnection(common.PORT); <add> var c = net.createConnection(this.address().port); <ide> <ide> c.setEncoding('utf8'); <ide> <ide><path>test/parallel/test-http-write-callbacks.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> server.on('checkContinue', function(req, res) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> method: 'PUT', <ide> headers: { 'expect': '100-continue' } <ide> }); <ide><path>test/parallel/test-http-write-empty-string.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> process.on('exit', function() { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <del> http.get({ port: common.PORT }, function(res) { <add>server.listen(0, function() { <add> http.get({ port: this.address().port }, function(res) { <ide> assert.equal(200, res.statusCode); <ide> res.setEncoding('ascii'); <ide> res.on('data', function(chunk) { <ide><path>test/parallel/test-http-write-head.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var s = http.createServer(function(req, res) { <ide> res.end(); <ide> }); <ide> <del>s.listen(common.PORT, runTest); <add>s.listen(0, runTest); <ide> <ide> function runTest() { <del> http.get({ port: common.PORT }, function(response) { <add> http.get({ port: this.address().port }, function(response) { <ide> response.on('end', function() { <ide> assert.equal(response.headers['test'], '2'); <ide> assert(response.rawHeaders.indexOf('Test') !== -1); <ide><path>test/parallel/test-http-zero-length-write.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var req = http.request({ port: common.PORT, method: 'POST' }); <add>server.listen(0, function() { <add> var req = http.request({ port: this.address().port, method: 'POST' }); <ide> var actual = ''; <ide> req.on('response', function(res) { <ide> res.setEncoding('utf8'); <ide><path>test/parallel/test-http.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> var server = http.Server(function(req, res) { <ide> <ide> //assert.equal('127.0.0.1', res.connection.remoteAddress); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <del> var agent = new http.Agent({ port: common.PORT, maxSockets: 1 }); <add> var agent = new http.Agent({ port: this.address().port, maxSockets: 1 }); <ide> http.get({ <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/hello', <ide> headers: {'Accept': '*/*', 'Foo': 'bar'}, <ide> agent: agent <ide> server.on('listening', function() { <ide> <ide> setTimeout(function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> method: 'POST', <ide> path: '/world', <ide> agent: agent <ide><path>test/parallel/test-https-agent-disable-session-reuse.js <ide> const agent = new https.Agent({ <ide> const server = https.createServer(options, function(req, res) { <ide> serverRequests++; <ide> res.end('ok'); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> var waiting = TOTAL_REQS; <ide> function request() { <ide> const options = { <ide> agent: agent, <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: false <ide> }; <ide> <ide><path>test/parallel/test-https-agent-servername.js <ide> var server = https.Server(options, function(req, res) { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> https.get({ <ide> path: '/', <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: true, <ide> servername: 'agent1', <ide> ca: options.ca <ide><path>test/parallel/test-https-agent-session-eviction.js <ide> const options = { <ide> // Create TLS1.2 server <ide> https.createServer(options, function(req, res) { <ide> res.end('ohai'); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> first(this); <ide> }); <ide> <ide> // Do request and let agent cache the session <ide> function first(server) { <add> const port = server.address().port; <ide> const req = https.request({ <del> port: common.PORT, <add> port: port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> res.resume(); <ide> <ide> server.close(function() { <del> faultyServer(); <add> faultyServer(port); <ide> }); <ide> }); <ide> req.end(); <ide> } <ide> <ide> // Create TLS1 server <del>function faultyServer() { <add>function faultyServer(port) { <ide> options.secureProtocol = 'TLSv1_method'; <ide> https.createServer(options, function(req, res) { <ide> res.end('hello faulty'); <del> }).listen(common.PORT, function() { <add> }).listen(port, function() { <ide> second(this); <ide> }); <ide> } <ide> <ide> // Attempt to request using cached session <ide> function second(server, session) { <ide> const req = https.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> res.resume(); <ide> function second(server, session) { <ide> req.end(); <ide> } <ide> <del>// Try on more time - session should be evicted! <add>// Try one more time - session should be evicted! <ide> function third(server) { <ide> const req = https.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> res.resume(); <ide><path>test/parallel/test-https-agent-session-reuse.js <ide> var server = https.createServer(options, function(req, res) { <ide> <ide> serverRequests++; <ide> res.end('ok'); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> var queue = [ <ide> { <ide> name: 'first', <ide> var server = https.createServer(options, function(req, res) { <ide> path: '/', <ide> servername: 'agent1', <ide> ca: ca, <del> port: common.PORT <add> port: this.address().port <ide> }, <ide> { <ide> name: 'first-reuse', <ide> var server = https.createServer(options, function(req, res) { <ide> path: '/', <ide> servername: 'agent1', <ide> ca: ca, <del> port: common.PORT <add> port: this.address().port <ide> }, <ide> { <ide> name: 'cipher-change', <ide> var server = https.createServer(options, function(req, res) { <ide> // Choose different cipher to use different cache entry <ide> ciphers: 'AES256-SHA', <ide> ca: ca, <del> port: common.PORT <add> port: this.address().port <ide> }, <ide> // Change the ticket key to ensure session is updated in cache <ide> { <ide> var server = https.createServer(options, function(req, res) { <ide> path: '/drop-key', <ide> servername: 'agent1', <ide> ca: ca, <del> port: common.PORT <add> port: this.address().port <ide> }, <ide> <ide> // Ticket will be updated starting from this <ide> var server = https.createServer(options, function(req, res) { <ide> path: '/', <ide> servername: 'agent1', <ide> ca: ca, <del> port: common.PORT <add> port: this.address().port <ide> }, <ide> { <ide> name: 'after-drop-reuse', <ide> var server = https.createServer(options, function(req, res) { <ide> path: '/', <ide> servername: 'agent1', <ide> ca: ca, <del> port: common.PORT <add> port: this.address().port <ide> } <ide> ]; <ide> <ide><path>test/parallel/test-https-agent-sni.js <ide> const server = https.Server(options, function(req, res) { <ide> res.end('hello world'); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> function expectResponse(id) { <ide> return common.mustCall(function(res) { <ide> res.resume(); <ide> server.listen(common.PORT, function() { <ide> agent: agent, <ide> <ide> path: '/', <del> port: common.PORT, <add> port: this.address().port, <ide> host: '127.0.0.1', <ide> servername: 'sni.' + j, <ide> rejectUnauthorized: false <ide><path>test/parallel/test-https-agent.js <ide> var responses = 0; <ide> var N = 4; <ide> var M = 4; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> for (var i = 0; i < N; i++) { <ide> setTimeout(function() { <ide> for (var j = 0; j < M; j++) { <ide> https.get({ <ide> path: '/', <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> res.resume(); <ide><path>test/parallel/test-https-byteswritten.js <ide> var httpsServer = https.createServer(options, function(req, res) { <ide> res.end(body); <ide> }); <ide> <del>httpsServer.listen(common.PORT, function() { <add>httpsServer.listen(0, function() { <ide> https.get({ <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }); <ide> }); <ide><path>test/parallel/test-https-client-checkServerIdentity.js <ide> var server = https.createServer(options, function(req, res) { <ide> res.writeHead(200); <ide> res.end(); <ide> req.resume(); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> authorized(); <ide> }); <ide> <ide> function authorized() { <ide> var req = https.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: true, <ide> ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))] <ide> }, function(res) { <ide> function authorized() { <ide> <ide> function override() { <ide> var options = { <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: true, <ide> ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))], <ide> checkServerIdentity: function(host, cert) { <ide><path>test/parallel/test-https-client-get-url.js <ide> var server = https.createServer(options, function(req, res) { <ide> seen_req = true; <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> https.get('https://127.0.0.1:' + common.PORT + '/foo?bar'); <add>server.listen(0, function() { <add> https.get(`https://127.0.0.1:${this.address().port}/foo?bar`); <ide> }); <ide> <ide> process.on('exit', function() { <ide><path>test/parallel/test-https-client-reject.js <ide> var server = https.createServer(options, function(req, res) { <ide> res.writeHead(200); <ide> res.end(); <ide> req.resume(); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> unauthorized(); <ide> }); <ide> <ide> function unauthorized() { <ide> var req = https.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> assert(!req.socket.authorized); <ide> function unauthorized() { <ide> <ide> function rejectUnauthorized() { <ide> var options = { <del> port: common.PORT <add> port: server.address().port <ide> }; <ide> options.agent = new https.Agent(options); <ide> var req = https.request(options, function(res) { <ide> function rejectUnauthorized() { <ide> <ide> function authorized() { <ide> var options = { <del> port: common.PORT, <add> port: server.address().port, <ide> ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] <ide> }; <ide> options.agent = new https.Agent(options); <ide><path>test/parallel/test-https-client-resume.js <ide> var server = https.createServer(options, function(req, res) { <ide> }); <ide> <ide> // start listening <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> <ide> var session1 = null; <ide> var client1 = tls.connect({ <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function() { <ide> console.log('connect1'); <ide> server.listen(common.PORT, function() { <ide> console.log('close1'); <ide> <ide> var opts = { <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: false, <ide> session: session1 <ide> }; <ide><path>test/parallel/test-https-close.js <ide> function shutdown() { <ide> } <ide> } <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var requestOptions = { <ide> hostname: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET', <ide> rejectUnauthorized: false <ide><path>test/parallel/test-https-connecting-to-http.js <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <del> var req = https.get({ port: common.PORT }, function(res) { <add>server.listen(0, function() { <add> var req = https.get({ port: this.address().port }, function(res) { <ide> resCount++; <ide> }); <ide> <ide><path>test/parallel/test-https-drain.js <ide> var server = https.createServer(options, function(req, res) { <ide> req.pipe(res); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var resumed = false; <ide> var req = https.request({ <ide> method: 'POST', <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> var timer; <ide><path>test/parallel/test-https-eof-for-eom.js <ide> var gotHeaders = false; <ide> var gotEnd = false; <ide> var bodyBuffer = ''; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> console.log('1) Making Request'); <ide> https.get({ <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> server.close(); <ide><path>test/parallel/test-https-foafssl.js <ide> var server = https.createServer(options, function(req, res) { <ide> res.end(body); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var args = ['s_client', <ide> '-quiet', <del> '-connect', '127.0.0.1:' + common.PORT, <add> '-connect', `127.0.0.1:${this.address().port}`, <ide> '-cert', join(common.fixturesDir, 'foafssl.crt'), <ide> '-key', join(common.fixturesDir, 'foafssl.key')]; <ide> <ide><path>test/parallel/test-https-host-headers.js <ide> function reqHandler(req, res) { <ide> if (req.url === '/setHostFalse5') { <ide> assert.equal(req.headers.host, undefined); <ide> } else { <del> assert.equal(req.headers.host, 'localhost:' + common.PORT, <add> assert.equal(req.headers.host, `localhost:${this.address().port}`, <ide> 'Wrong host header for req[' + req.url + ']: ' + <ide> req.headers.host); <ide> } <ide> testHttps(); <ide> <ide> function testHttps() { <ide> <del> console.log('testing https on port ' + common.PORT); <del> <ide> var counter = 0; <ide> <ide> function cb(res) { <ide> function testHttps() { <ide> res.resume(); <ide> } <ide> <del> httpsServer.listen(common.PORT, function(er) { <add> httpsServer.listen(0, function(er) { <add> console.log(`test https server listening on port ${this.address().port}`); <add> <ide> if (er) throw er; <ide> <ide> https.get({ <ide> method: 'GET', <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower); <ide> <ide> function testHttps() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> <ide> function testHttps() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> <ide> function testHttps() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> <ide> function testHttps() { <ide> path: '/' + (counter++), <ide> host: 'localhost', <ide> //agent: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> <ide> function testHttps() { <ide> path: '/setHostFalse' + (counter++), <ide> host: 'localhost', <ide> setHost: false, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, cb).on('error', thrower).end(); <ide> }); <ide><path>test/parallel/test-https-localaddress-bind-error.js <ide> var server = https.createServer(options, function(req, res) { <ide> req.resume(); <ide> }); <ide> <del>server.listen(common.PORT, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', function() { <ide> https.request({ <ide> host: 'localhost', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET', <ide> localAddress: invalidLocalAddress <ide><path>test/parallel/test-https-localaddress.js <ide> var server = https.createServer(options, function(req, res) { <ide> req.resume(); <ide> }); <ide> <del>server.listen(common.PORT, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', function() { <ide> var options = { <ide> host: 'localhost', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET', <ide> localAddress: '127.0.0.2', <ide><path>test/parallel/test-https-pfx.js <ide> var pfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); <ide> <ide> var options = { <ide> host: '127.0.0.1', <del> port: common.PORT, <add> port: undefined, <ide> path: '/', <ide> pfx: pfx, <ide> passphrase: 'sample', <ide> var server = https.createServer(options, function(req, res) { <ide> res.end('OK'); <ide> }); <ide> <del>server.listen(options.port, options.host, function() { <add>server.listen(0, options.host, function() { <add> options.port = this.address().port; <ide> var data = ''; <ide> <ide> https.get(options, function(res) { <ide><path>test/parallel/test-https-req-split.js <ide> server.on('upgrade', function(req, socket, upgrade) { <ide> seen_req = true; <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var req = https.request({ <ide> host: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> agent: false, <ide> headers: { <ide> Connection: 'Upgrade', <ide><path>test/parallel/test-https-resume-after-renew.js <ide> server._sharedCreds.context.onticketkeycallback = function(name, iv, enc) { <ide> return [ 1, hmac, aes, newName, newIV ]; <ide> }; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var addr = this.address(); <ide> <ide> function doReq(callback) { <ide><path>test/parallel/test-https-set-timeout-server.js <ide> test(function serverTimeout(cb) { <ide> var server = https.createServer(serverOptions, function(req, res) { <ide> // just do nothing, we should get a timeout event. <ide> }); <del> server.listen(common.PORT); <del> var s = server.setTimeout(50, function(socket) { <del> caughtTimeout = true; <del> socket.destroy(); <del> server.close(); <del> cb(); <add> server.listen(0, function() { <add> var s = server.setTimeout(50, function(socket) { <add> caughtTimeout = true; <add> socket.destroy(); <add> server.close(); <add> cb(); <add> }); <add> assert.ok(s instanceof https.Server); <add> https.get({ <add> port: this.address().port, <add> rejectUnauthorized: false <add> }).on('error', function() {}); <ide> }); <del> assert.ok(s instanceof https.Server); <del> https.get({ <del> port: common.PORT, <del> rejectUnauthorized: false <del> }).on('error', function() {}); <ide> }); <ide> <ide> test(function serverRequestTimeout(cb) { <ide> test(function serverRequestTimeout(cb) { <ide> cb(); <ide> }); <ide> }); <del> server.listen(common.PORT); <del> var req = https.request({ <del> port: common.PORT, <del> method: 'POST', <del> rejectUnauthorized: false <add> server.listen(0, function() { <add> var req = https.request({ <add> port: this.address().port, <add> method: 'POST', <add> rejectUnauthorized: false <add> }); <add> req.on('error', function() {}); <add> req.write('Hello'); <add> // req is in progress <ide> }); <del> req.on('error', function() {}); <del> req.write('Hello'); <del> // req is in progress <ide> }); <ide> <ide> test(function serverResponseTimeout(cb) { <ide> test(function serverResponseTimeout(cb) { <ide> cb(); <ide> }); <ide> }); <del> server.listen(common.PORT); <del> https.get({ <del> port: common.PORT, <del> rejectUnauthorized: false <del> }).on('error', function() {}); <add> server.listen(0, function() { <add> https.get({ <add> port: this.address().port, <add> rejectUnauthorized: false <add> }).on('error', function() {}); <add> }); <ide> }); <ide> <ide> test(function serverRequestNotTimeoutAfterEnd(cb) { <ide> test(function serverRequestNotTimeoutAfterEnd(cb) { <ide> server.close(); <ide> cb(); <ide> }); <del> server.listen(common.PORT); <del> https.get({ <del> port: common.PORT, <del> rejectUnauthorized: false <del> }).on('error', function() {}); <add> server.listen(0, function() { <add> https.get({ <add> port: this.address().port, <add> rejectUnauthorized: false <add> }).on('error', function() {}); <add> }); <ide> }); <ide> <ide> test(function serverResponseTimeoutWithPipeline(cb) { <ide> test(function serverResponseTimeoutWithPipeline(cb) { <ide> server.close(); <ide> cb(); <ide> }); <del> server.listen(common.PORT); <del> var options = { <del> port: common.PORT, <del> allowHalfOpen: true, <del> rejectUnauthorized: false <del> }; <del> var c = tls.connect(options, function() { <del> c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <del> c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <del> c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> server.listen(0, function() { <add> var options = { <add> port: this.address().port, <add> allowHalfOpen: true, <add> rejectUnauthorized: false <add> }; <add> var c = tls.connect(options, function() { <add> c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> }); <ide> }); <ide> }); <ide> <ide> test(function idleTimeout(cb) { <ide> server.close(); <ide> cb(); <ide> }); <del> server.listen(common.PORT); <del> var options = { <del> port: common.PORT, <del> allowHalfOpen: true, <del> rejectUnauthorized: false <del> }; <del> tls.connect(options, function() { <del> this.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <del> // Keep-Alive <add> server.listen(0, function() { <add> var options = { <add> port: this.address().port, <add> allowHalfOpen: true, <add> rejectUnauthorized: false <add> }; <add> tls.connect(options, function() { <add> this.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); <add> // Keep-Alive <add> }); <ide> }); <ide> }); <ide><path>test/parallel/test-https-simple.js <ide> const serverCallback = common.mustCall(function(req, res) { <ide> <ide> const server = https.createServer(options, serverCallback); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> // Do a request ignoring the unauthorized server certs <ide> const noCertCheckOptions = { <ide> hostname: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET', <ide> rejectUnauthorized: false <ide> server.listen(common.PORT, function() { <ide> // Do a request that throws error due to the invalid server certs <ide> const checkCertOptions = { <ide> hostname: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET' <ide> }; <ide><path>test/parallel/test-https-socket-options.js <ide> var server_http = http.createServer(function(req, res) { <ide> }); <ide> <ide> <del>server_http.listen(common.PORT, function() { <add>server_http.listen(0, function() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> server_http.close(); <ide> var server_https = https.createServer(options, function(req, res) { <ide> res.end(body); <ide> }); <ide> <del>server_https.listen(common.PORT + 1, function() { <add>server_https.listen(0, function() { <ide> var req = https.request({ <del> port: common.PORT + 1, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> server_https.close(); <ide><path>test/parallel/test-https-strict.js <ide> function makeReq(path, port, error, host, ca) { <ide> <ide> function allListening() { <ide> // ok, ready to start the tests! <del> <ide> const port1 = server1.address().port; <ide> const port2 = server2.address().port; <ide> const port3 = server3.address().port; <ide><path>test/parallel/test-https-timeout-server-2.js <ide> server.on('secureConnection', function(cleartext) { <ide> assert.ok(s instanceof tls.TLSSocket); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> tls.connect({ <ide> host: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }); <ide> }); <ide><path>test/parallel/test-https-timeout-server.js <ide> server.on('clientError', function(err, conn) { <ide> conn.destroy(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> net.connect({ host: '127.0.0.1', port: common.PORT }); <add>server.listen(0, function() { <add> net.connect({ host: '127.0.0.1', port: this.address().port }); <ide> }); <ide><path>test/parallel/test-https-timeout.js <ide> var options = { <ide> // a server that never replies <ide> var server = https.createServer(options, function() { <ide> console.log('Got request. Doing nothing.'); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> var req = https.request({ <ide> host: 'localhost', <del> port: common.PORT, <add> port: this.address().port, <ide> path: '/', <ide> method: 'GET', <ide> rejectUnauthorized: false <ide><path>test/parallel/test-https-truncate.js <ide> var fs = require('fs'); <ide> var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); <ide> var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); <ide> <del>var PORT = common.PORT; <del> <ide> // number of bytes discovered empirically to trigger the bug <ide> var data = Buffer.allocUnsafe(1024 * 32 + 1); <ide> <ide> function httpsTest() { <ide> server.close(); <ide> }); <ide> <del> server.listen(PORT, function() { <del> var opts = { port: PORT, rejectUnauthorized: false }; <add> server.listen(0, function() { <add> var opts = { port: this.address().port, rejectUnauthorized: false }; <ide> https.get(opts).on('response', function(res) { <ide> test(res); <ide> }); <ide><path>test/parallel/test-listen-fd-cluster.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <del>var PORT = common.PORT; <ide> var cluster = require('cluster'); <ide> <ide> console.error('Cluster listen fd test', process.argv[2] || 'runner'); <ide> process.on('exit', function() { <ide> // server handles to stdio fd's is NOT a good or reliable way to do <ide> // concurrency in HTTP servers! Use the cluster module, or if you want <ide> // a more low-level approach, use child process IPC manually. <del>test(function(parent) { <add>test(function(parent, port) { <ide> // now make sure that we can request to the worker, then kill it. <ide> http.get({ <ide> server: 'localhost', <del> port: PORT, <add> port: port, <ide> path: '/', <ide> }).on('response', function(res) { <ide> var s = ''; <ide> function test(cb) { <ide> var server = net.createServer(function(conn) { <ide> console.error('connection on parent'); <ide> conn.end('hello from parent\n'); <del> }).listen(PORT, function() { <del> console.error('server listening on %d', PORT); <add> }).listen(0, function() { <add> const port = this.address().port; <add> console.error('server listening on %d', port); <ide> <ide> var spawn = require('child_process').spawn; <ide> var master = spawn(process.execPath, [__filename, 'master'], { <ide> function test(cb) { <ide> console.error('master spawned'); <ide> master.on('message', function(msg) { <ide> if (msg === 'started worker') { <del> cb(master); <add> cb(master, port); <ide> } <ide> }); <ide> }); <ide><path>test/parallel/test-listen-fd-detached-inherit.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <del>var PORT = common.PORT; <ide> var spawn = require('child_process').spawn; <ide> <ide> if (common.isWindows) { <ide> function test() { <ide> // now make sure that we can request to the child, then kill it. <ide> http.get({ <ide> server: 'localhost', <del> port: PORT, <add> port: child.port, <ide> path: '/', <ide> }).on('response', function(res) { <ide> var s = ''; <ide> function test() { <ide> } <ide> } <ide> <del>// Listen on PORT, and then pass the handle to the detached child. <add>// Listen on port, and then pass the handle to the detached child. <ide> // Then output the child's pid, and immediately exit. <ide> function parent() { <ide> var server = net.createServer(function(conn) { <ide> conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n'); <ide> throw new Error('Should not see connections on parent'); <del> }).listen(PORT, function() { <del> console.error('server listening on %d', PORT); <add> }).listen(0, function() { <add> console.error('server listening on %d', this.address().port); <ide> <ide> var child = spawn(process.execPath, [__filename, 'child'], { <ide> stdio: [ 0, 1, 2, server._handle ], <ide> detached: true <ide> }); <ide> <del> console.log('%j\n', { pid: child.pid }); <add> console.log('%j\n', { pid: child.pid, port: this.address().port }); <ide> <ide> // Now close the parent, so that the child is the only thing <ide> // referencing that handle. Note that connections will still <ide><path>test/parallel/test-listen-fd-detached.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <del>var PORT = common.PORT; <ide> var spawn = require('child_process').spawn; <ide> <ide> if (common.isWindows) { <ide> function test() { <ide> // now make sure that we can request to the child, then kill it. <ide> http.get({ <ide> server: 'localhost', <del> port: PORT, <add> port: child.port, <ide> path: '/', <ide> }).on('response', function(res) { <ide> var s = ''; <ide> function parent() { <ide> var server = net.createServer(function(conn) { <ide> console.error('connection on parent'); <ide> conn.end('hello from parent\n'); <del> }).listen(PORT, function() { <del> console.error('server listening on %d', PORT); <add> }).listen(0, function() { <add> console.error('server listening on %d', this.address().port); <ide> <ide> var spawn = require('child_process').spawn; <ide> var child = spawn(process.execPath, [__filename, 'child'], { <ide> stdio: [ 'ignore', 'ignore', 'ignore', server._handle ], <ide> detached: true <ide> }); <ide> <del> console.log('%j\n', { pid: child.pid }); <add> console.log('%j\n', { pid: child.pid, port: this.address().port }); <ide> <ide> // Now close the parent, so that the child is the only thing <ide> // referencing that handle. Note that connections will still <ide><path>test/parallel/test-listen-fd-server.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <del>var PORT = common.PORT; <ide> <ide> if (common.isWindows) { <ide> common.skip('This test is disabled on windows.'); <ide> process.on('exit', function() { <ide> // server handles to stdio fd's is NOT a good or reliable way to do <ide> // concurrency in HTTP servers! Use the cluster module, or if you want <ide> // a more low-level approach, use child process IPC manually. <del>test(function(child) { <add>test(function(child, port) { <ide> // now make sure that we can request to the child, then kill it. <ide> http.get({ <ide> server: 'localhost', <del> port: PORT, <add> port: port, <ide> path: '/', <ide> }).on('response', function(res) { <ide> var s = ''; <ide> function test(cb) { <ide> var server = net.createServer(function(conn) { <ide> console.error('connection on parent'); <ide> conn.end('hello from parent\n'); <del> }).listen(PORT, function() { <del> console.error('server listening on %d', PORT); <add> }).listen(0, function() { <add> const port = this.address().port; <add> console.error('server listening on %d', port); <ide> <ide> var spawn = require('child_process').spawn; <ide> var child = spawn(process.execPath, [__filename, 'child'], { <ide> function test(cb) { <ide> <ide> child.on('message', function(msg) { <ide> if (msg === 'listening') { <del> cb(child); <add> cb(child, port); <ide> } <ide> }); <ide> }); <ide><path>test/parallel/test-net-after-close.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var closed = false; <ide> var server = net.createServer(function(s) { <ide> s.end(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var c = net.createConnection(common.PORT); <add>server.listen(0, function() { <add> var c = net.createConnection(this.address().port); <ide> c.on('close', function() { <ide> console.error('connection closed'); <ide> assert.strictEqual(c._handle, null); <ide><path>test/parallel/test-net-binary.js <ide> /* eslint-disable strict */ <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var echoServer = net.Server(function(connection) { <ide> connection.end(); <ide> }); <ide> }); <del>echoServer.listen(common.PORT); <add>echoServer.listen(0); <ide> <ide> var recv = ''; <ide> <ide> echoServer.on('listening', function() { <ide> var j = 0; <ide> var c = net.createConnection({ <del> port: common.PORT <add> port: this.address().port <ide> }); <ide> <ide> c.setEncoding('latin1'); <ide><path>test/parallel/test-net-bind-twice.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> function dontCall() { <ide> } <ide> <ide> var server1 = net.createServer(dontCall); <del>server1.listen(common.PORT, '127.0.0.1', function() {}); <add>server1.listen(0, '127.0.0.1', function() { <add> var server2 = net.createServer(dontCall); <add> server2.listen(this.address().port, '127.0.0.1', dontCall); <ide> <del>var server2 = net.createServer(dontCall); <del>server2.listen(common.PORT, '127.0.0.1', dontCall); <del> <del>server2.on('error', function(e) { <del> assert.equal(e.code, 'EADDRINUSE'); <del> server1.close(); <del> gotError = true; <add> server2.on('error', function(e) { <add> assert.equal(e.code, 'EADDRINUSE'); <add> server1.close(); <add> gotError = true; <add> }); <ide> }); <ide><path>test/parallel/test-net-buffersize.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(function(socket) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var client = net.connect(common.PORT); <add>server.listen(0, function() { <add> var client = net.connect(this.address().port); <ide> <ide> client.on('finish', function() { <ide> assert.strictEqual(client.bufferSize, 0); <ide><path>test/parallel/test-net-bytes-read.js <ide> const big = Buffer.alloc(1024 * 1024); <ide> const server = net.createServer((socket) => { <ide> socket.end(big); <ide> server.close(); <del>}).listen(common.PORT, () => { <add>}).listen(0, () => { <ide> let prev = 0; <ide> <ide> function checkRaise(value) { <ide> assert(value > prev); <ide> prev = value; <ide> } <ide> <del> const socket = net.connect(common.PORT, () => { <add> const socket = net.connect(server.address().port, () => { <ide> socket.on('data', (chunk) => { <ide> checkRaise(socket.bytesRead); <ide> }); <ide><path>test/parallel/test-net-bytes-stats.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <del>var tcpPort = common.PORT; <ide> var bytesRead = 0; <ide> var bytesWritten = 0; <ide> var count = 0; <ide> var tcp = net.Server(function(s) { <ide> }); <ide> }); <ide> <del>tcp.listen(common.PORT, function doTest() { <add>tcp.listen(0, function doTest() { <ide> console.error('listening'); <del> var socket = net.createConnection(tcpPort); <add> var socket = net.createConnection(this.address().port); <ide> <ide> socket.on('connect', function() { <ide> count++; <ide> tcp.listen(common.PORT, function doTest() { <ide> console.log('Bytes written: ' + bytesWritten); <ide> if (count < 2) { <ide> console.error('RECONNECTING'); <del> socket.connect(tcpPort); <add> socket.connect(tcp.address().port); <ide> } else { <ide> tcp.close(); <ide> } <ide><path>test/parallel/test-net-can-reset-timeout.js <ide> 'use strict'; <add>require('../common'); <ide> var net = require('net'); <del>var common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var timeoutCount = 0; <ide> var server = net.createServer(function(stream) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var c = net.createConnection(common.PORT); <add>server.listen(0, function() { <add> var c = net.createConnection(this.address().port); <ide> <ide> c.on('data', function() { <ide> c.end(); <ide><path>test/parallel/test-net-connect-buffer.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <del>var tcpPort = common.PORT; <ide> var dataWritten = false; <ide> var connectHappened = false; <ide> <ide> var tcp = net.Server(function(s) { <ide> }); <ide> }); <ide> <del>tcp.listen(common.PORT, function() { <add>tcp.listen(0, function() { <ide> var socket = net.Stream({ highWaterMark: 0 }); <ide> <ide> console.log('Connecting to socket '); <ide> <del> socket.connect(tcpPort, function() { <add> socket.connect(this.address().port, function() { <ide> console.log('socket connected'); <ide> connectHappened = true; <ide> }); <ide><path>test/parallel/test-net-connect-options-ipv6.js <ide> const server = net.createServer({allowHalfOpen: true}, function(socket) { <ide> socket.end(); <ide> }); <ide> <del>server.listen(common.PORT, '::1', tryConnect); <add>server.listen(0, '::1', tryConnect); <ide> <ide> function tryConnect() { <ide> const client = net.connect({ <ide> host: host, <del> port: common.PORT, <add> port: server.address().port, <ide> family: 6, <ide> allowHalfOpen: true <ide> }, function() { <ide><path>test/parallel/test-net-connect-options.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer({allowHalfOpen: true}, function(socket) { <ide> socket.end(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var client = net.connect({ <ide> host: '127.0.0.1', <del> port: common.PORT, <add> port: this.address().port, <ide> allowHalfOpen: true <ide> }, function() { <ide> console.error('client connect cb'); <ide><path>test/parallel/test-net-connect-paused-connection.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <del>var common = require('../common'); <ide> <ide> var net = require('net'); <ide> <ide> net.createServer(function(conn) { <ide> conn.unref(); <del>}).listen(common.PORT).unref(); <add>}).listen(0, function() { <add> net.connect(this.address().port, 'localhost').pause(); <ide> <del>net.connect(common.PORT, 'localhost').pause(); <del> <del>setTimeout(function() { <del> assert.fail(null, null, 'expected to exit'); <del>}, 1000).unref(); <add> setTimeout(function() { <add> assert.fail(null, null, 'expected to exit'); <add> }, 1000).unref(); <add>}).unref(); <ide><path>test/parallel/test-net-create-connection.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const dns = require('dns'); <ide> const net = require('net'); <ide> <del>const tcpPort = common.PORT; <ide> const expectedConnections = 7; <ide> var clientConnected = 0; <ide> var serverConnected = 0; <ide> const server = net.createServer(function(socket) { <ide> } <ide> }); <ide> <del>server.listen(tcpPort, 'localhost', function() { <add>server.listen(0, 'localhost', function() { <ide> function cb() { <ide> ++clientConnected; <ide> } <ide> server.listen(tcpPort, 'localhost', function() { <ide> }); <ide> } <ide> <del> net.createConnection(tcpPort).on('connect', cb); <del> net.createConnection(tcpPort, 'localhost').on('connect', cb); <del> net.createConnection(tcpPort, cb); <del> net.createConnection(tcpPort, 'localhost', cb); <del> net.createConnection(tcpPort + '', 'localhost', cb); <del> net.createConnection({port: tcpPort + ''}).on('connect', cb); <del> net.createConnection({port: '0x' + tcpPort.toString(16)}, cb); <add> net.createConnection(this.address().port).on('connect', cb); <add> net.createConnection(this.address().port, 'localhost').on('connect', cb); <add> net.createConnection(this.address().port, cb); <add> net.createConnection(this.address().port, 'localhost', cb); <add> net.createConnection(this.address().port + '', 'localhost', cb); <add> net.createConnection({port: this.address().port + ''}).on('connect', cb); <add> net.createConnection({port: '0x' + this.address().port.toString(16)}, cb); <ide> <ide> fail({ <ide> port: true <ide><path>test/parallel/test-net-dns-custom-lookup.js <ide> function check(addressType, cb) { <ide> }); <ide> <ide> var address = addressType === 4 ? common.localhostIPv4 : '::1'; <del> server.listen(common.PORT, address, function() { <add> server.listen(0, address, function() { <ide> net.connect({ <del> port: common.PORT, <add> port: this.address().port, <ide> host: 'localhost', <ide> family: addressType, <ide> lookup: lookup <ide><path>test/parallel/test-net-dns-lookup-skip.js <ide> function check(addressType) { <ide> }); <ide> <ide> var address = addressType === 4 ? '127.0.0.1' : '::1'; <del> server.listen(common.PORT, address, function() { <del> net.connect(common.PORT, address).on('lookup', common.fail); <add> server.listen(0, address, function() { <add> net.connect(this.address().port, address).on('lookup', common.fail); <ide> }); <ide> } <ide> <ide><path>test/parallel/test-net-dns-lookup.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var ok = false; <ide> var server = net.createServer(function(client) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT, '127.0.0.1', function() { <del> net.connect(common.PORT, 'localhost') <add>server.listen(0, '127.0.0.1', function() { <add> net.connect(this.address().port, 'localhost') <ide> .on('lookup', function(err, ip, type, host) { <ide> assert.equal(err, null); <ide> assert.equal(ip, '127.0.0.1'); <ide><path>test/parallel/test-net-during-close.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var accessedProperties = false; <ide> var server = net.createServer(function(socket) { <ide> socket.end(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var client = net.createConnection(common.PORT); <add>server.listen(0, function() { <add> var client = net.createConnection(this.address().port); <ide> server.close(); <ide> // server connection event has not yet fired <ide> // client is still attempting to connect <ide><path>test/parallel/test-net-eaddrinuse.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server1 = net.createServer(function(socket) { <ide> }); <ide> var server2 = net.createServer(function(socket) { <ide> }); <del>server1.listen(common.PORT); <del>server2.on('error', function(error) { <del> assert.equal(true, error.message.indexOf('EADDRINUSE') >= 0); <del> server1.close(); <add>server1.listen(0, function() { <add> server2.on('error', function(error) { <add> assert.equal(true, error.message.indexOf('EADDRINUSE') >= 0); <add> server1.close(); <add> }); <add> server2.listen(this.address().port); <ide> }); <del>server2.listen(common.PORT); <ide><path>test/parallel/test-net-error-twice.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> var srv = net.createServer(function onConnection(conn) { <ide> }); <ide> serverSocket = conn; <ide> ready(); <del>}).listen(common.PORT, function() { <del> var client = net.connect({ port: common.PORT }); <add>}).listen(0, function() { <add> var client = net.connect({ port: this.address().port }); <ide> <ide> client.on('connect', function() { <ide> clientSocket = client; <ide><path>test/parallel/test-net-keepalive.js <ide> var echoServer = net.createServer(function(connection) { <ide> connection.end(); <ide> }); <ide> }); <del>echoServer.listen(common.PORT); <add>echoServer.listen(0); <ide> <ide> echoServer.on('listening', function() { <del> clientConnection = net.createConnection(common.PORT); <add> clientConnection = net.createConnection(this.address().port); <ide> clientConnection.setTimeout(0); <ide> }); <ide><path>test/parallel/test-net-large-string.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(function(socket) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var client = net.createConnection(common.PORT); <add>server.listen(0, function() { <add> var client = net.createConnection(this.address().port); <ide> client.on('end', function() { <ide> server.close(); <ide> }); <ide><path>test/parallel/test-net-listen-close-server-callback-is-not-function.js <ide> 'use strict'; <add>require('../common'); <ide> var assert = require('assert'); <del>var common = require('../common'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(assert.fail); <ide> server.on('close', function() { <ide> ++closeEvents; <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> assert(false); <ide> }); <ide> <ide><path>test/parallel/test-net-listen-close-server.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(function(socket) { <ide> }); <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> assert(false); <ide> }); <ide> server.on('error', function(error) { <ide><path>test/parallel/test-net-listening.js <ide> const server = net.createServer(); <ide> <ide> assert.strictEqual(server.listening, false); <ide> <del>server.listen(common.PORT, common.mustCall(() => { <add>server.listen(0, common.mustCall(() => { <ide> assert.strictEqual(server.listening, true); <ide> <ide> server.close(common.mustCall(() => { <ide><path>test/parallel/test-net-local-address-port.js <ide> var conns = 0; <ide> <ide> var server = net.createServer(function(socket) { <ide> conns++; <del> assert.equal(common.localhostIPv4, socket.localAddress); <del> assert.equal(socket.localPort, common.PORT); <add> assert.equal(socket.localAddress, common.localhostIPv4); <add> assert.equal(socket.localPort, this.address().port); <ide> socket.on('end', function() { <ide> server.close(); <ide> }); <ide> socket.resume(); <ide> }); <ide> <del>server.listen(common.PORT, common.localhostIPv4, function() { <del> var client = net.createConnection(common.PORT, common.localhostIPv4); <add>server.listen(0, common.localhostIPv4, function() { <add> var client = net.createConnection(this.address().port, common.localhostIPv4); <ide> client.on('connect', function() { <ide> client.end(); <ide> }); <ide><path>test/parallel/test-net-localport.js <ide> var net = require('net'); <ide> <ide> var server = net.createServer(function(socket) { <ide> console.log(socket.remotePort); <del> assert.strictEqual(socket.remotePort, common.PORT + 1); <add> assert.strictEqual(socket.remotePort, common.PORT); <ide> socket.end(); <ide> socket.on('close', function() { <ide> server.close(); <ide> }); <del>}).listen(common.PORT).on('listening', function() { <add>}).listen(0).on('listening', function() { <ide> var client = net.connect({ <ide> host: '127.0.0.1', <del> port: common.PORT, <del> localPort: common.PORT + 1, <add> port: this.address().port, <add> localPort: common.PORT, <ide> }).on('connect', function() { <del> assert.strictEqual(client.localPort, common.PORT + 1); <add> assert.strictEqual(client.localPort, common.PORT); <ide> }); <ide> }); <ide><path>test/parallel/test-net-pause-resume-connecting.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> var server = net.createServer(function(conn) { <ide> server.close(); <ide> }); <ide> <del>server.listen(common.PORT); <add>server.listen(0, function() { <add> // Client 1 <add> conn = require('net').createConnection(this.address().port, 'localhost'); <add> conn.resume(); <add> conn.on('data', onDataOk); <ide> <ide> <del>// Client 1 <del>conn = require('net').createConnection(common.PORT, 'localhost'); <del>conn.resume(); <del>conn.on('data', onDataOk); <add> // Client 2 <add> conn = require('net').createConnection(this.address().port, 'localhost'); <add> conn.pause(); <add> conn.resume(); <add> conn.on('data', onDataOk); <ide> <ide> <del>// Client 2 <del>conn = require('net').createConnection(common.PORT, 'localhost'); <del>conn.pause(); <del>conn.resume(); <del>conn.on('data', onDataOk); <add> // Client 3 <add> conn = require('net').createConnection(this.address().port, 'localhost'); <add> conn.pause(); <add> conn.on('data', onDataError); <add> scheduleTearDown(conn); <ide> <ide> <del>// Client 3 <del>conn = require('net').createConnection(common.PORT, 'localhost'); <del>conn.pause(); <del>conn.on('data', onDataError); <del>scheduleTearDown(conn); <add> // Client 4 <add> conn = require('net').createConnection(this.address().port, 'localhost'); <add> conn.resume(); <add> conn.pause(); <add> conn.resume(); <add> conn.on('data', onDataOk); <ide> <ide> <del>// Client 4 <del>conn = require('net').createConnection(common.PORT, 'localhost'); <del>conn.resume(); <del>conn.pause(); <del>conn.resume(); <del>conn.on('data', onDataOk); <add> // Client 5 <add> conn = require('net').createConnection(this.address().port, 'localhost'); <add> conn.resume(); <add> conn.resume(); <add> conn.pause(); <add> conn.on('data', onDataError); <add> scheduleTearDown(conn); <ide> <ide> <del>// Client 5 <del>conn = require('net').createConnection(common.PORT, 'localhost'); <del>conn.resume(); <del>conn.resume(); <del>conn.pause(); <del>conn.on('data', onDataError); <del>scheduleTearDown(conn); <add> // Client helper functions <add> function onDataError() { <add> assert(false); <add> } <ide> <add> function onDataOk() { <add> dataEvents++; <add> } <ide> <del>// Client helper functions <del>function onDataError() { <del> assert(false); <del>} <del> <del>function onDataOk() { <del> dataEvents++; <del>} <del> <del>function scheduleTearDown(conn) { <del> setTimeout(function() { <del> conn.removeAllListeners('data'); <del> conn.resume(); <del> }, 100); <del>} <add> function scheduleTearDown(conn) { <add> setTimeout(function() { <add> conn.removeAllListeners('data'); <add> conn.resume(); <add> }, 100); <add> } <add>}); <ide> <ide> <ide> // Exit sanity checks <ide><path>test/parallel/test-net-persistent-keepalive.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var echoServer = net.createServer(function(connection) { <ide> connection.end(); <ide> }); <ide> }); <del>echoServer.listen(common.PORT); <add>echoServer.listen(0); <ide> <ide> echoServer.on('listening', function() { <ide> clientConnection = new net.Socket(); <ide> // send a keepalive packet after 1000 ms <ide> // and make sure it persists <ide> var s = clientConnection.setKeepAlive(true, 400); <ide> assert.ok(s instanceof net.Socket); <del> clientConnection.connect(common.PORT); <add> clientConnection.connect(this.address().port); <ide> clientConnection.setTimeout(0); <ide> }); <ide><path>test/parallel/test-net-persistent-nodelay.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var TCPWrap = process.binding('tcp_wrap').TCP; <ide> <ide> var echoServer = net.createServer(function(connection) { <ide> connection.end(); <ide> }); <del>echoServer.listen(common.PORT); <add>echoServer.listen(0); <ide> <ide> var callCount = 0; <ide> <ide> echoServer.on('listening', function() { <ide> <ide> var s = sock1.setNoDelay(); <ide> assert.ok(s instanceof net.Socket); <del> sock1.connect(common.PORT); <add> sock1.connect(this.address().port); <ide> sock1.on('end', function() { <ide> assert.equal(callCount, 1); <ide> echoServer.close(); <ide><path>test/parallel/test-net-persistent-ref-unref.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var TCPWrap = process.binding('tcp_wrap').TCP; <ide> TCPWrap.prototype.unref = function() { <ide> assert.equal(refCount, -1); <ide> }; <ide> <del>echoServer.listen(common.PORT); <add>echoServer.listen(0); <ide> <ide> echoServer.on('listening', function() { <ide> var sock = new net.Socket(); <ide> sock.unref(); <ide> sock.ref(); <del> sock.connect(common.PORT); <add> sock.connect(this.address().port); <ide> sock.on('end', function() { <ide> assert.equal(refCount, 0); <ide> echoServer.close(); <ide><path>test/parallel/test-net-pingpong.js <ide> function pingPongTest(port, host) { <ide> }); <ide> <ide> socket.on('close', function() { <del> console.log('server socket.endd'); <add> console.log('server socket.end'); <ide> assert.equal(false, socket.writable); <ide> assert.equal(false, socket.readable); <ide> socket.server.close(); <ide> function pingPongTest(port, host) { <ide> <ide> <ide> server.listen(port, host, function() { <del> console.log('server listening on ' + port + ' ' + host); <add> if (this.address().port) <add> port = this.address().port; <add> console.log(`server listening on ${port} ${host}`); <ide> <ide> var client = net.createConnection(port, host); <ide> <ide> function pingPongTest(port, host) { <ide> /* All are run at once, so run on different ports */ <ide> common.refreshTmpDir(); <ide> pingPongTest(common.PIPE); <del>pingPongTest(common.PORT); <del>pingPongTest(common.PORT + 1, 'localhost'); <add>pingPongTest(0); <add>pingPongTest(0, 'localhost'); <ide> if (common.hasIPv6) <del> pingPongTest(common.PORT + 2, '::1'); <add> pingPongTest(0, '::1'); <ide> <ide> process.on('exit', function() { <ide> if (common.hasIPv6) <ide><path>test/parallel/test-net-reconnect.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var net = require('net'); <ide> var server = net.createServer(function(socket) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> console.log('SERVER listening'); <del> var client = net.createConnection(common.PORT); <add> var client = net.createConnection(this.address().port); <ide> <ide> client.setEncoding('UTF8'); <ide> <ide> server.listen(common.PORT, function() { <ide> console.log('CLIENT disconnect'); <ide> assert.equal(false, had_error); <ide> if (disconnect_count++ < N) <del> client.connect(common.PORT); // reconnect <add> client.connect(server.address().port); // reconnect <ide> else <ide> server.close(); <ide> }); <ide><path>test/parallel/test-net-remote-address-port.js <ide> var server = net.createServer(function(socket) { <ide> assert.notEqual(-1, remoteAddrCandidates.indexOf(socket.remoteAddress)); <ide> assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); <ide> assert.ok(socket.remotePort); <del> assert.notEqual(socket.remotePort, common.PORT); <add> assert.notEqual(socket.remotePort, this.address().port); <ide> socket.on('end', function() { <ide> if (++conns_closed == 2) server.close(); <ide> }); <ide> var server = net.createServer(function(socket) { <ide> socket.resume(); <ide> }); <ide> <del>server.listen(common.PORT, 'localhost', function() { <del> var client = net.createConnection(common.PORT, 'localhost'); <del> var client2 = net.createConnection(common.PORT); <add>server.listen(0, 'localhost', function() { <add> var client = net.createConnection(this.address().port, 'localhost'); <add> var client2 = net.createConnection(this.address().port); <ide> client.on('connect', function() { <ide> assert.notEqual(-1, remoteAddrCandidates.indexOf(client.remoteAddress)); <ide> assert.notEqual(-1, remoteFamilyCandidates.indexOf(client.remoteFamily)); <del> assert.equal(common.PORT, client.remotePort); <add> assert.equal(client.remotePort, server.address().port); <ide> client.end(); <ide> }); <ide> client.on('close', function() { <ide> server.listen(common.PORT, 'localhost', function() { <ide> client2.on('connect', function() { <ide> assert.notEqual(-1, remoteAddrCandidates.indexOf(client2.remoteAddress)); <ide> assert.notEqual(-1, remoteFamilyCandidates.indexOf(client2.remoteFamily)); <del> assert.equal(common.PORT, client2.remotePort); <add> assert.equal(client2.remotePort, server.address().port); <ide> client2.end(); <ide> }); <ide> client2.on('close', function() { <ide><path>test/parallel/test-net-server-close.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> server.on('close', function() { <ide> events.push('server'); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> net.createConnection(common.PORT); <del> net.createConnection(common.PORT); <add>server.listen(0, function() { <add> net.createConnection(this.address().port); <add> net.createConnection(this.address().port); <ide> }); <ide><path>test/parallel/test-net-server-listen-remove-callback.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> server.on('close', function() { <ide> assert.equal(0, listeners.length); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> server.close(); <ide> }); <ide> <ide> server.once('close', function() { <del> server.listen(common.PORT + 1, function() { <add> server.listen(0, function() { <ide> server.close(); <ide> }); <ide> }); <ide><path>test/parallel/test-net-server-max-connections-close-makes-more-available.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var net = require('net'); <ide> var createConnection = function(index) { <ide> console.error('creating connection ' + index); <ide> <ide> return new Promise(function(resolve, reject) { <del> var connection = net.createConnection(common.PORT, function() { <add> var connection = net.createConnection(server.address().port, function() { <ide> var msg = '' + index; <ide> console.error('sending message: ' + msg); <ide> this.write(msg); <ide> var server = net.createServer(function(socket) { <ide> <ide> server.maxConnections = 1; <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> createConnection(0) <ide> .then(createConnection.bind(null, 1)) <ide> .then(closeConnection.bind(null, 0)) <ide><path>test/parallel/test-net-server-max-connections.js <ide> var server = net.createServer(function(connection) { <ide> waits.push(function() { connection.end(); }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> makeConnection(0); <ide> }); <ide> <ide> console.error('server.maxConnections = %d', server.maxConnections); <ide> <ide> <ide> function makeConnection(index) { <del> var c = net.createConnection(common.PORT); <add> var c = net.createConnection(server.address().port); <ide> var gotData = false; <ide> <ide> c.on('connect', function() { <ide> function makeConnection(index) { <ide> // Retry if SmartOS and ECONNREFUSED. See <ide> // https://github.com/nodejs/node/issues/2663. <ide> if (common.isSunOS && (e.code === 'ECONNREFUSED')) { <del> c.connect(common.PORT); <add> c.connect(server.address().port); <ide> } <ide> console.error('error %d: %s', index, e); <ide> }); <ide><path>test/parallel/test-net-server-options.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> assert.throws(function() { net.createServer('path'); }, TypeError); <del>assert.throws(function() { net.createServer(common.PORT); }, TypeError); <add>assert.throws(function() { net.createServer(0); }, TypeError); <ide><path>test/parallel/test-net-server-pause-on-connect.js <ide> const server2ConnHandler = function(socket) { <ide> <ide> const server2 = net.createServer({pauseOnConnect: false}, server2ConnHandler); <ide> <del>server1.listen(common.PORT, function() { <add>server1.listen(0, function() { <ide> const clientHandler = common.mustCall(function() { <del> server2.listen(common.PORT + 1, function() { <del> net.createConnection({port: common.PORT + 1}).write(msg); <add> server2.listen(0, function() { <add> net.createConnection({port: this.address().port}).write(msg); <ide> }); <ide> }); <del> net.createConnection({port: common.PORT}).write(msg, clientHandler); <add> net.createConnection({port: this.address().port}).write(msg, clientHandler); <ide> }); <ide> <ide> process.on('exit', function() { <ide><path>test/parallel/test-net-server-try-ports.js <ide> 'use strict'; <ide> // This tests binds to one port, then attempts to start a server on that <ide> // port. It should be EADDRINUSE but be able to then bind to another port. <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> server2.on('error', function(e) { <ide> server2eaddrinuse = true; <ide> } <ide> <del> server2.listen(common.PORT + 1, function() { <add> server2.listen(0, function() { <ide> console.error('server2 listening'); <ide> server2listening = true; <ide> <ide> server2.on('error', function(e) { <ide> }); <ide> <ide> <del>server1.listen(common.PORT, function() { <add>server1.listen(0, function() { <ide> console.error('server1 listening'); <ide> server1listening = true; <ide> // This should make server2 emit EADDRINUSE <del> server2.listen(common.PORT); <add> server2.listen(this.address().port); <ide> }); <ide> <ide> <ide><path>test/parallel/test-net-server-unref.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var net = require('net'); <ide> var closed = false; <ide> <ide> var s = net.createServer(); <del>s.listen(common.PORT); <add>s.listen(0); <ide> s.unref(); <ide> <ide> setTimeout(function() { <ide><path>test/parallel/test-net-settimeout.js <ide> const server = net.createServer(common.mustCall((c) => { <ide> c.write('hello'); <ide> })); <ide> <del>server.listen(common.PORT); <del> <del>const socket = net.createConnection(common.PORT, 'localhost'); <del> <del>const s = socket.setTimeout(T, () => { <del> common.fail('Socket timeout event is not expected to fire'); <add>server.listen(0, function() { <add> const socket = net.createConnection(this.address().port, 'localhost'); <add> <add> const s = socket.setTimeout(T, () => { <add> common.fail('Socket timeout event is not expected to fire'); <add> }); <add> assert.ok(s instanceof net.Socket); <add> <add> socket.on('data', common.mustCall(() => { <add> setTimeout(function() { <add> socket.destroy(); <add> server.close(); <add> }, T * 2); <add> })); <add> <add> socket.setTimeout(0); <ide> }); <del>assert.ok(s instanceof net.Socket); <del> <del>socket.on('data', common.mustCall(() => { <del> setTimeout(function() { <del> socket.destroy(); <del> server.close(); <del> }, T * 2); <del>})); <del> <del>socket.setTimeout(0); <ide><path>test/parallel/test-net-socket-connecting.js <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> const server = net.createServer((conn) => { <ide> conn.end(); <ide> server.close(); <del>}).listen(common.PORT, () => { <del> const client = net.connect(common.PORT, () => { <add>}).listen(0, () => { <add> const client = net.connect(server.address().port, () => { <ide> assert.strictEqual(client.connecting, false); <ide> <ide> // Legacy getter <ide><path>test/parallel/test-net-socket-local-address.js <ide> server.on('close', common.mustCall(() => { <ide> assert.strictEqual(2, conns); <ide> })); <ide> <del>server.listen(common.PORT, common.localhostIPv4, connect); <add>server.listen(0, common.localhostIPv4, connect); <ide> <ide> function connect() { <ide> if (conns === 2) { <ide> function connect() { <ide> <ide> conns++; <ide> client.once('close', connect); <del> client.connect(common.PORT, common.localhostIPv4, () => { <add> client.connect(server.address().port, common.localhostIPv4, () => { <ide> clientLocalPorts.push(client.localPort); <ide> }); <ide> } <ide><path>test/parallel/test-net-socket-timeout-unref.js <ide> const server = net.createServer(function(c) { <ide> c.write('hello'); <ide> c.unref(); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> server.unref(); <ide> <ide> var connections = 0; <ide> const sockets = []; <ide> const delays = [8, 5, 3, 6, 2, 4]; <ide> <ide> delays.forEach(function(T) { <del> const socket = net.createConnection(common.PORT, 'localhost'); <add> const socket = net.createConnection(server.address().port, 'localhost'); <ide> socket.on('connect', common.mustCall(function() { <ide> if (++connections === delays.length) { <ide> sockets.forEach(function(s) { <ide><path>test/parallel/test-net-socket-timeout.js <ide> for (let i = 0; i < validDelays.length; i++) { <ide> var timedout = false; <ide> <ide> var server = net.Server(); <del>server.listen(common.PORT, function() { <del> var socket = net.createConnection(common.PORT); <add>server.listen(0, function() { <add> var socket = net.createConnection(this.address().port); <ide> socket.setTimeout(100, function() { <ide> timedout = true; <ide> socket.destroy(); <ide><path>test/parallel/test-net-socket-write-error.js <ide> 'use strict'; <ide> <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <del>const server = net.createServer().listen(common.PORT, connectToServer); <add>const server = net.createServer().listen(0, connectToServer); <ide> <ide> function connectToServer() { <del> const client = net.createConnection(common.PORT, () => { <add> const client = net.createConnection(this.address().port, () => { <ide> assert.throws(() => { <ide> client.write(1337); <ide> }, /Invalid data, chunk must be a string or buffer, not number/); <ide><path>test/parallel/test-net-stream.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <del> <ide> var net = require('net'); <ide> <ide> var s = new net.Stream(); <ide> var server = net.createServer(function(socket) { <ide> } <ide> socket.end(); <ide> <del>}).listen(common.PORT, function() { <del> var conn = net.connect(common.PORT); <add>}).listen(0, function() { <add> var conn = net.connect(this.address().port); <ide> conn.on('data', function(buf) { <ide> conn.pause(); <ide> setTimeout(function() { <ide><path>test/parallel/test-net-sync-cork.js <ide> 'use strict'; <ide> <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> const server = net.createServer(handle); <ide> const N = 100; <ide> const buf = Buffer.alloc(2, 'a'); <ide> <del>server.listen(common.PORT, function() { <del> const conn = net.connect(common.PORT); <add>server.listen(0, function() { <add> const conn = net.connect(this.address().port); <ide> <ide> conn.on('connect', () => { <ide> let res = true; <ide><path>test/parallel/test-net-write-after-close.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(function(socket) { <ide> }, 250); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> var client = net.connect(common.PORT, function() { <add>server.listen(0, function() { <add> var client = net.connect(this.address().port, function() { <ide> client.end(); <ide> }); <ide> }); <ide><path>test/parallel/test-net-write-connect-write.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var received = ''; <ide> <ide> var server = net.createServer(function(socket) { <ide> socket.pipe(socket); <del>}).listen(common.PORT, function() { <del> var conn = net.connect(common.PORT); <add>}).listen(0, function() { <add> var conn = net.connect(this.address().port); <ide> conn.setEncoding('utf8'); <ide> conn.write('before'); <ide> conn.on('connect', function() { <ide><path>test/parallel/test-net-write-slow.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(function(socket) { <ide> } <ide> socket.end(); <ide> <del>}).listen(common.PORT, function() { <del> var conn = net.connect(common.PORT); <add>}).listen(0, function() { <add> var conn = net.connect(this.address().port); <ide> conn.on('data', function(buf) { <ide> received += buf.length; <ide> conn.pause(); <ide><path>test/parallel/test-pipe-file-to-http.js <ide> var server = http.createServer(function(req, res) { <ide> res.end(); <ide> }); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0); <ide> <ide> server.on('listening', function() { <ide> var cmd = common.ddCommand(filename, 10240); <ide> server.on('listening', function() { <ide> <ide> function makeRequest() { <ide> var req = http.request({ <del> port: common.PORT, <add> port: server.address().port, <ide> path: '/', <ide> method: 'POST' <ide> }); <ide><path>test/parallel/test-process-getactivehandles.js <ide> 'use strict'; <ide> <del>const common = require('../common'); <add>require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> const NUM = 8; <ide> var clients_counter = 0; <ide> <ide> const server = net.createServer(function listener(c) { <ide> connections.push(c); <del>}).listen(common.PORT, makeConnection); <add>}).listen(0, makeConnection); <ide> <ide> <ide> function makeConnection() { <ide> if (clients_counter >= NUM) return; <del> net.connect(common.PORT, function connected() { <add> net.connect(server.address().port, function connected() { <ide> clientConnected(this); <ide> makeConnection(); <ide> }); <ide><path>test/parallel/test-regress-GH-1531.js <ide> var server = https.createServer(options, function(req, res) { <ide> res.end('hello world\n'); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> console.error('listening'); <ide> https.get({ <ide> agent: false, <ide> path: '/', <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function(res) { <ide> console.error(res.statusCode, res.headers); <ide><path>test/parallel/test-regress-GH-4948.js <ide> 'use strict'; <ide> // https://github.com/joyent/node/issues/4948 <ide> <del>var common = require('../common'); <add>require('../common'); <ide> var http = require('http'); <ide> <ide> var reqCount = 0; <ide> var server = http.createServer(function(serverReq, serverRes) { <ide> // normally the use case would be to call an external site <ide> // does not require connecting locally or to itself to fail <ide> var r = http.request({hostname: 'localhost', <del> port: common.PORT}, function(res) { <add> port: this.address().port}, function(res) { <ide> // required, just needs to be in the client response somewhere <ide> serverRes.end(); <ide> <ide> var server = http.createServer(function(serverReq, serverRes) { <ide> r.end(); <ide> <ide> serverRes.write('some data'); <del>}).listen(common.PORT); <add>}).listen(0, function() { <add> // simulate a client request that closes early <add> var net = require('net'); <ide> <del>// simulate a client request that closes early <del>var net = require('net'); <add> var sock = new net.Socket(); <add> sock.connect(this.address().port, 'localhost'); <ide> <del>var sock = new net.Socket(); <del>sock.connect(common.PORT, 'localhost'); <del> <del>sock.on('connect', function() { <del> sock.write('GET / HTTP/1.1\r\n\r\n'); <del> sock.end(); <add> sock.on('connect', function() { <add> sock.write('GET / HTTP/1.1\r\n\r\n'); <add> sock.end(); <add> }); <ide> }); <ide><path>test/parallel/test-regress-GH-746.js <ide> // Just test that destroying stdin doesn't mess up listening on a server. <ide> // This is a regression test for GH-746. <ide> <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(function(socket) { <ide> }); <ide> <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> console.log('listening...'); <ide> <del> net.createConnection(common.PORT); <add> net.createConnection(this.address().port); <ide> }); <ide> <ide> <ide><path>test/parallel/test-repl-require.js <ide> const server = net.createServer((conn) => { <ide> }); <ide> <ide> const host = common.localhostIPv4; <del>const port = common.PORT; <add>const port = 0; <ide> const options = { host, port }; <ide> <ide> var answer = ''; <ide> server.listen(options, function() { <add> options.port = this.address().port; <ide> const conn = net.connect(options); <ide> conn.setEncoding('utf8'); <ide> conn.on('data', (data) => answer += data); <ide><path>test/parallel/test-repl.js <ide> function tcp_test() { <ide> repl.start(prompt_tcp, socket); <ide> }); <ide> <del> server_tcp.listen(common.PORT, function() { <add> server_tcp.listen(0, function() { <ide> var read_buffer = ''; <ide> <del> client_tcp = net.createConnection(common.PORT); <add> client_tcp = net.createConnection(this.address().port); <ide> <ide> client_tcp.on('connect', function() { <ide> assert.equal(true, client_tcp.readable); <ide><path>test/parallel/test-socket-write-after-fin-error.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> // This is similar to simple/test-socket-write-after-fin, except that <ide> var server = net.createServer(function(sock) { <ide> }); <ide> server.close(); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0, function() { <add> var sock = net.connect(this.address().port); <add> sock.setEncoding('utf8'); <add> sock.on('data', function(c) { <add> clientData += c; <add> }); <ide> <del>var sock = net.connect(common.PORT); <del>sock.setEncoding('utf8'); <del>sock.on('data', function(c) { <del> clientData += c; <del>}); <add> sock.on('end', function() { <add> gotClientEnd = true; <add> }); <ide> <del>sock.on('end', function() { <del> gotClientEnd = true; <del>}); <add> process.on('exit', function() { <add> assert.equal(clientData, ''); <add> assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); <add> assert(gotClientEnd); <add> assert(gotServerEnd); <add> assert(gotServerError); <add> assert.equal(gotServerError.code, 'EPIPE'); <add> assert.notEqual(gotServerError.message, 'write after end'); <add> console.log('ok'); <add> }); <ide> <del>process.on('exit', function() { <del> assert.equal(clientData, ''); <del> assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); <del> assert(gotClientEnd); <del> assert(gotServerEnd); <del> assert(gotServerError); <del> assert.equal(gotServerError.code, 'EPIPE'); <del> assert.notEqual(gotServerError.message, 'write after end'); <del> console.log('ok'); <add> sock.write('hello1'); <add> sock.write('hello2'); <add> sock.write('hello3\n'); <add> sock.end('THUNDERMUSCLE!'); <ide> }); <del> <del>sock.write('hello1'); <del>sock.write('hello2'); <del>sock.write('hello3\n'); <del>sock.end('THUNDERMUSCLE!'); <ide><path>test/parallel/test-socket-write-after-fin.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var serverData = ''; <ide> var server = net.createServer({ allowHalfOpen: true }, function(sock) { <ide> server.close(); <ide> }); <ide> }); <del>server.listen(common.PORT); <add>server.listen(0, function() { <add> var sock = net.connect(this.address().port); <add> sock.setEncoding('utf8'); <add> sock.on('data', function(c) { <add> clientData += c; <add> }); <ide> <del>var sock = net.connect(common.PORT); <del>sock.setEncoding('utf8'); <del>sock.on('data', function(c) { <del> clientData += c; <del>}); <add> sock.on('end', function() { <add> gotClientEnd = true; <add> }); <ide> <del>sock.on('end', function() { <del> gotClientEnd = true; <del>}); <add> process.on('exit', function() { <add> assert.equal(serverData, clientData); <add> assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); <add> assert(gotClientEnd); <add> assert(gotServerEnd); <add> console.log('ok'); <add> }); <ide> <del>process.on('exit', function() { <del> assert.equal(serverData, clientData); <del> assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); <del> assert(gotClientEnd); <del> assert(gotServerEnd); <del> console.log('ok'); <add> sock.write('hello1'); <add> sock.write('hello2'); <add> sock.write('hello3\n'); <add> sock.end('THUNDERMUSCLE!'); <ide> }); <del> <del>sock.write('hello1'); <del>sock.write('hello2'); <del>sock.write('hello3\n'); <del>sock.end('THUNDERMUSCLE!'); <ide><path>test/parallel/test-stream-base-no-abort.js <ide> const checkTLS = common.mustCall(function checkTLS() { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') <ide> }; <ide> const server = tls.createServer(options, () => {}) <del> .listen(common.PORT, function() { <del> tls.connect(common.PORT, { rejectUnauthorized: false }, function() { <add> .listen(0, function() { <add> const connectOpts = { rejectUnauthorized: false }; <add> tls.connect(this.address().port, connectOpts, function() { <ide> this.destroy(); <ide> server.close(); <ide> }); <ide> }); <ide> }); <ide> <ide> const checkTCP = common.mustCall(function checkTCP() { <del> net.createServer(() => {}).listen(common.PORT, function() { <add> net.createServer(() => {}).listen(0, function() { <ide> this.close(checkTLS); <ide> }); <ide> }); <ide><path>test/parallel/test-stream2-httpclient-response-end.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var msg = 'Hello'; <ide> var end_event = false; <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.end(msg); <del>}).listen(common.PORT, function() { <del> http.get({port: common.PORT}, function(res) { <add>}).listen(0, function() { <add> http.get({port: this.address().port}, function(res) { <ide> var data = ''; <ide> res.on('readable', function() { <ide> console.log('readable event'); <ide><path>test/parallel/test-tcp-wrap-connect.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> var TCP = process.binding('tcp_wrap').TCP; <ide> var TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; <ide> function makeConnection() { <ide> var client = new TCP(); <ide> <ide> var req = new TCPConnectWrap(); <del> var err = client.connect(req, '127.0.0.1', common.PORT); <add> var err = client.connect(req, '127.0.0.1', this.address().port); <ide> assert.equal(err, 0); <ide> <ide> req.oncomplete = function(status, client_, req_) { <ide> var server = require('net').Server(function(s) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, makeConnection); <add>server.listen(0, makeConnection); <ide> <ide> process.on('exit', function() { <ide> assert.equal(1, shutdownCount); <ide><path>test/parallel/test-tcp-wrap-listen.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var TCP = process.binding('tcp_wrap').TCP; <ide> var WriteWrap = process.binding('stream_wrap').WriteWrap; <ide> <ide> var server = new TCP(); <ide> <del>var r = server.bind('0.0.0.0', common.PORT); <add>var r = server.bind('0.0.0.0', 0); <ide> assert.equal(0, r); <add>var port = {}; <add>server.getsockname(port); <add>port = port.port; <ide> <ide> server.listen(128); <ide> <ide> server.onconnection = function(err, client) { <ide> <ide> var net = require('net'); <ide> <del>var c = net.createConnection(common.PORT); <add>var c = net.createConnection(port); <ide> c.on('connect', function() { <ide> c.end('hello world'); <ide> }); <ide><path>test/parallel/test-tcp-wrap.js <ide> 'use strict'; <del>var common = require('../common'); <add>require('../common'); <ide> var assert = require('assert'); <ide> <ide> var TCP = process.binding('tcp_wrap').TCP; <ide> var uv = process.binding('uv'); <ide> <ide> var handle = new TCP(); <ide> <del>// Should be able to bind to the common.PORT <del>var err = handle.bind('0.0.0.0', common.PORT); <add>// Should be able to bind to the port <add>var err = handle.bind('0.0.0.0', 0); <ide> assert.equal(err, 0); <ide> <ide> // Should not be able to bind to the same port again <del>err = handle.bind('0.0.0.0', common.PORT); <add>var out = {}; <add>handle.getsockname(out); <add>err = handle.bind('0.0.0.0', out.port); <ide> assert.equal(err, uv.UV_EINVAL); <ide> <ide> handle.close(); <ide><path>test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js <ide> const server = net.createServer(function onClient(client) { <ide> } <ide> }); <ide> <del>server.listen(common.PORT, common.localhostIPv4, function() { <add>server.listen(0, common.localhostIPv4, function() { <ide> var nbClientsEnded = 0; <ide> <ide> function addEndedClient(client) { <ide> server.listen(common.PORT, common.localhostIPv4, function() { <ide> } <ide> } <ide> <del> const client1 = net.connect({ port: common.PORT }); <add> const client1 = net.connect({ port: this.address().port }); <ide> client1.on('end', addEndedClient); <ide> <del> const client2 = net.connect({ port: common.PORT }); <add> const client2 = net.connect({ port: this.address().port }); <ide> client2.on('end', addEndedClient); <ide> }); <ide><path>test/parallel/test-tls-0-dns-altname.js <ide> var server = tls.createServer({ <ide> c.destroy(); <ide> server.close(); <ide> }); <del>}).listen(common.PORT, function() { <del> var c = tls.connect(common.PORT, { <add>}).listen(0, function() { <add> var c = tls.connect(this.address().port, { <ide> rejectUnauthorized: false <ide> }, function() { <ide> requests++; <ide><path>test/parallel/test-tls-alert-handling.js <ide> var server = tls.createServer(opts, function(s) { <ide> }); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> sendClient(); <ide> }); <ide> <ide> <ide> function sendClient() { <del> var client = tls.connect(common.PORT, { <add> var client = tls.connect(server.address().port, { <ide> rejectUnauthorized: false <ide> }); <ide> client.on('data', function(chunk) { <ide> function sendClient() { <ide> <ide> function sendBADTLSRecord() { <ide> var BAD_RECORD = Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); <del> var socket = net.connect(common.PORT); <add> var socket = net.connect(server.address().port); <ide> var client = tls.connect({ <ide> socket: socket, <ide> rejectUnauthorized: false <ide><path>test/parallel/test-tls-alert.js <ide> var server = tls.Server({ <ide> secureProtocol: 'TLSv1_2_server_method', <ide> key: loadPEM('agent2-key'), <ide> cert: loadPEM('agent2-cert') <del>}, null).listen(common.PORT, function() { <add>}, null).listen(0, function() { <ide> var args = ['s_client', '-quiet', '-tls1_1', <del> '-connect', '127.0.0.1:' + common.PORT]; <add> '-connect', `127.0.0.1:${this.address().port}`]; <ide> <ide> // for the performance and stability issue in s_client on Windows <ide> if (common.isWindows) <ide><path>test/parallel/test-tls-alpn-server-client.js <ide> function loadPEM(n) { <ide> return fs.readFileSync(filenamePEM(n)); <ide> } <ide> <del>var serverPort = common.PORT; <ide> var serverIP = common.localhostIPv4; <ide> <ide> function checkResults(result, expected) { <ide> function runTest(clientsOptions, serverOptions, cb) { <ide> results[index].server = {ALPN: c.alpnProtocol, NPN: c.npnProtocol}; <ide> }); <ide> <del> server.listen(serverPort, serverIP, function() { <add> server.listen(0, serverIP, function() { <ide> connectClient(clientsOptions); <ide> }); <ide> <ide> function connectClient(options) { <ide> var opt = options.shift(); <del> opt.port = serverPort; <add> opt.port = server.address().port; <ide> opt.host = serverIP; <ide> opt.rejectUnauthorized = false; <ide> <ide><path>test/parallel/test-tls-async-cb-after-socket-end.js <ide> server.on('resumeSession', function(id, cb) { <ide> next(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var clientOpts = { <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false, <ide> session: false <ide> }; <ide><path>test/parallel/test-tls-cert-regression.js <ide> function test(cert, key, cb) { <ide> var server = tls.createServer({ <ide> cert: cert, <ide> key: key <del> }).listen(common.PORT, function() { <add> }).listen(0, function() { <ide> server.close(cb); <ide> }); <ide> } <ide><path>test/parallel/test-tls-client-destroy-soon.js <ide> var server = tls.createServer(options, function(socket) { <ide> }); <ide> <ide> // start listening <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> var client = tls.connect({ <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function() { <ide> client.on('readable', function() { <ide><path>test/parallel/test-tls-client-getephemeralkeyinfo.js <ide> function test(size, type, name, next) { <ide> if (next) next(); <ide> }); <ide> <del> server.listen(common.PORT, '127.0.0.1', function() { <add> server.listen(0, '127.0.0.1', function() { <ide> var client = tls.connect({ <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function() { <ide> var ekeyinfo = client.getEphemeralKeyInfo(); <ide><path>test/parallel/test-tls-client-mindhsize.js <ide> function test(size, err, next) { <ide> if (next) next(); <ide> }); <ide> <del> server.listen(common.PORT, '127.0.0.1', function() { <add> server.listen(0, '127.0.0.1', function() { <ide> // client set minimum DH parameter size to 2048 bits so that <ide> // it fails when it make a connection to the tls server where <ide> // dhparams is 1024 bits <ide> var client = tls.connect({ <ide> minDHSize: 2048, <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function() { <ide> nsuccess++; <ide><path>test/parallel/test-tls-client-reject.js <ide> var server = tls.createServer(options, function(socket) { <ide> console.error(data.toString()); <ide> assert.equal(data, 'ok'); <ide> }); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> unauthorized(); <ide> }); <ide> <ide> function unauthorized() { <ide> var socket = tls.connect({ <del> port: common.PORT, <add> port: server.address().port, <ide> servername: 'localhost', <ide> rejectUnauthorized: false <ide> }, function() { <ide> function unauthorized() { <ide> } <ide> <ide> function rejectUnauthorized() { <del> var socket = tls.connect(common.PORT, { <add> var socket = tls.connect(server.address().port, { <ide> servername: 'localhost' <ide> }, function() { <ide> assert(false); <ide> function rejectUnauthorized() { <ide> } <ide> <ide> function authorized() { <del> var socket = tls.connect(common.PORT, { <add> var socket = tls.connect(server.address().port, { <ide> ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))], <ide> servername: 'localhost' <ide> }, function() { <ide><path>test/parallel/test-tls-client-resume.js <ide> var server = tls.Server(options, function(socket) { <ide> }); <ide> <ide> // start listening <del>server.listen(common.PORT, function() { <add>server.listen(0, function() { <ide> <ide> var session1 = null; <ide> var client1 = tls.connect({ <del> port: common.PORT, <add> port: this.address().port, <ide> rejectUnauthorized: false <ide> }, function() { <ide> console.log('connect1'); <ide> server.listen(common.PORT, function() { <ide> console.log('close1'); <ide> <ide> var opts = { <del> port: common.PORT, <add> port: server.address().port, <ide> rejectUnauthorized: false, <ide> session: session1 <ide> }; <ide><path>test/parallel/test-tls-client-verify.js <ide> function testServers(index, servers, clientOptions, cb) { <ide> s.end('hello world\n'); <ide> }); <ide> <del> server.listen(common.PORT, function() { <add> server.listen(0, function() { <ide> var b = ''; <ide> <ide> console.error('connecting...'); <add> clientOptions.port = this.address().port; <ide> var client = tls.connect(clientOptions, function() { <ide> var authorized = client.authorized || <ide> hosterr.test(client.authorizationError); <ide> function runTest(testIndex) { <ide> if (!tcase) return; <ide> <ide> var clientOptions = { <del> port: common.PORT, <add> port: undefined, <ide> ca: tcase.ca.map(loadPEM), <ide> key: loadPEM(tcase.key), <ide> cert: loadPEM(tcase.cert), <ide><path>test/parallel/test-tls-close-error.js <ide> var server = tls.createServer({ <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }, function(c) { <del>}).listen(common.PORT, function() { <del> var c = tls.connect(common.PORT, function() { <add>}).listen(0, function() { <add> var c = tls.connect(this.address().port, function() { <ide> assert(false, 'should not be called'); <ide> }); <ide> <ide><path>test/parallel/test-tls-close-notify.js <ide> var server = tls.createServer({ <ide> // Send close-notify without shutting down TCP socket <ide> if (c._handle.shutdownSSL() !== 1) <ide> c._handle.shutdownSSL(); <del>}).listen(common.PORT, function() { <del> var c = tls.connect(common.PORT, { <add>}).listen(0, function() { <add> var c = tls.connect(this.address().port, { <ide> rejectUnauthorized: false <ide> }, function() { <ide> // Ensure that we receive 'end' event anyway <ide><path>test/parallel/test-tls-cnnic-whitelist.js <ide> var testCases = [ <ide> cert: loadPEM('agent7-cert') <ide> }, <ide> clientOpts: { <del> port: common.PORT, <add> port: undefined, <ide> rejectUnauthorized: true, <ide> ca: [loadPEM('fake-cnnic-root-cert')] <ide> }, <ide> var testCases = [ <ide> cert: loadPEM('agent6-cert') <ide> }, <ide> clientOpts: { <del> port: common.PORT, <add> port: undefined, <ide> rejectUnauthorized: true <ide> }, <ide> errorCode: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY' <ide> function runTest(tindex) { <ide> <ide> var server = tls.createServer(tcase.serverOpts, function(s) { <ide> s.resume(); <del> }).listen(common.PORT, function() { <add> }).listen(0, function() { <add> tcase.clientOpts = this.address().port; <ide> var client = tls.connect(tcase.clientOpts); <ide> client.on('error', function(e) { <ide> assert.strictEqual(e.code, tcase.errorCode); <ide><path>test/parallel/test-tls-connect-given-socket.js <ide> var options = { <ide> var server = tls.createServer(options, function(socket) { <ide> serverConnected++; <ide> socket.end('Hello'); <del>}).listen(common.PORT, function() { <add>}).listen(0, function() { <ide> var waiting = 2; <ide> function establish(socket) { <ide> var client = tls.connect({ <ide> var server = tls.createServer(options, function(socket) { <ide> } <ide> <ide> // Immediate death socket <del> var immediateDeath = net.connect(common.PORT); <add> var immediateDeath = net.connect(this.address().port); <ide> establish(immediateDeath).destroy(); <ide> <ide> // Outliving <del> var outlivingTCP = net.connect(common.PORT); <add> var outlivingTCP = net.connect(this.address().port); <ide> outlivingTCP.on('connect', function() { <ide> outlivingTLS.destroy(); <ide> next(); <ide> var server = tls.createServer(options, function(socket) { <ide> <ide> function next() { <ide> // Already connected socket <del> var connected = net.connect(common.PORT, function() { <add> var connected = net.connect(server.address().port, function() { <ide> establish(connected); <ide> }); <ide> <ide> // Connecting socket <del> var connecting = net.connect(common.PORT); <add> var connecting = net.connect(server.address().port); <ide> establish(connecting); <ide> <ide> }
300
Ruby
Ruby
add note on possible future deprecation
3a68b915ebad687f0044d9bc1d81e0fa9ad40745
<ide><path>Library/Homebrew/extend/ENV/std.rb <ide> require "hardware" <ide> require "extend/ENV/shared" <ide> <add># TODO: deprecate compiling related codes after it's only used by brew test. <ide> # @private <ide> module Stdenv <ide> include SharedEnvExtension
1
Ruby
Ruby
fix method visibility
b88a181b7f296d89237bdb727ecc15cbfdf13b65
<ide><path>actionpack/lib/action_dispatch/middleware/flash.rb <ide> def notice=(message) <ide> end <ide> <ide> protected <add> def now_is_loaded? <add> @now <add> end <ide> <del> def now_is_loaded? <del> @now <del> end <del> <del> # Used internally by the <tt>keep</tt> and <tt>discard</tt> methods <del> # use() # marks the entire flash as used <del> # use('msg') # marks the "msg" entry as used <del> # use(nil, false) # marks the entire flash as unused (keeps it around for one more action) <del> # use('msg', false) # marks the "msg" entry as unused (keeps it around for one more action) <del> # Returns the single value for the key you asked to be marked (un)used or the FlashHash itself <del> # if no key is passed. <del> def use(key = nil, used = true) <del> Array(key || keys).each { |k| used ? @used << k : @used.delete(k) } <del> return key ? self[key] : self <del> end <add> private <add> # Used internally by the <tt>keep</tt> and <tt>discard</tt> methods <add> # use() # marks the entire flash as used <add> # use('msg') # marks the "msg" entry as used <add> # use(nil, false) # marks the entire flash as unused (keeps it around for one more action) <add> # use('msg', false) # marks the "msg" entry as unused (keeps it around for one more action) <add> # Returns the single value for the key you asked to be marked (un)used or the FlashHash itself <add> # if no key is passed. <add> def use(key = nil, used = true) <add> Array(key || keys).each { |k| used ? @used << k : @used.delete(k) } <add> return key ? self[key] : self <add> end <ide> end <ide> <ide> def initialize(app)
1
Text
Text
add similarweb to the who uses airflow section
f1ca7a384f3af12df9e7fa30c11a553667889d69
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> * Lyft <ide> * [Sense360](https://github.com/Sense360) [[@kamilmroczek](https://github.com/KamilMroczek)] <ide> * [Sidecar](https://hello.getsidecar.com/) [[@getsidecar](https://github.com/getsidecar)] <add>* [SimilarWeb](https://www.similarweb.com/) [[@similarweb](https://github.com/similarweb)] <ide> * Stripe [@jbalogh] <ide> * [WeTransfer](https://github.com/WeTransfer) [[@jochem](https://github.com/jochem)] <ide> * Wooga
1
Text
Text
add changelog for [skip ci]
aa3d2d03b34bead79902802ceb88b0756aab9810
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Sean Griffin* <ide> <add>* The schema cache is now cleared after the 'migrate' task is run <add> <add> Closes #24273 <add> <add> *Chris Arcand* <add> <ide> * MySQL: strict mode respects other SQL modes rather than overwriting them. <ide> Setting `strict: true` adds `STRICT_ALL_TABLES` to `sql_mode`. Setting <ide> `strict: false` removes `STRICT_TRANS_TABLES`, `STRICT_ALL_TABLES`, and
1
Javascript
Javascript
add browser tests to test task
8b21db0007e18f38da6ad7e0e4c8f8b05183de9e
<ide><path>Gruntfile.js <ide> module.exports = function (grunt) { <ide> <ide> // Default task. <ide> grunt.registerTask('default', ['jshint', 'nodeunit']); <del> grunt.registerTask('test', ['nodeunit']); <add> grunt.registerTask('test', ['test:node', 'test:browser']); <add> <add> //test tasks <add> grunt.registerTask('test:node', ['nodeunit']); <add> grunt.registerTask('test:browser', ['concat', 'embed_languages', 'karma:chrome']); <ide> <ide> // Task to be run when releasing a new version <ide> grunt.registerTask('release', ['jshint', 'nodeunit', 'concat',
1
Javascript
Javascript
extract module/errors into a shared file
7b345bca558bd714478821dd945fbf2d05b5994c
<ide><path>packages/react-native-codegen/src/parsers/errors.js <ide> <ide> 'use strict'; <ide> <add>const invariant = require('invariant'); <add> <add>type ParserType = 'Flow' | 'TypeScript'; <add> <ide> class ParserError extends Error { <ide> nodes: $ReadOnlyArray<$FlowFixMe>; <ide> constructor( <del> hasteModuleName: string, <add> nativeModuleName: string, <ide> astNodeOrNodes: $FlowFixMe, <ide> message: string, <ide> ) { <del> super(`Module ${hasteModuleName}: ${message}`); <add> super(`Module ${nativeModuleName}: ${message}`); <ide> <ide> this.nodes = Array.isArray(astNodeOrNodes) <ide> ? astNodeOrNodes <ide> class ParserError extends Error { <ide> } <ide> } <ide> <add>class MisnamedModuleInterfaceParserError extends ParserError { <add> constructor(nativeModuleName: string, id: $FlowFixMe, language: ParserType) { <add> super( <add> nativeModuleName, <add> id, <add> `All ${language} interfaces extending TurboModule must be called 'Spec'. Please rename ${language} interface '${id.name}' to 'Spec'.`, <add> ); <add> } <add>} <add> <add>class ModuleInterfaceNotFoundParserError extends ParserError { <add> constructor(nativeModuleName: string, ast: $FlowFixMe, language: ParserType) { <add> super( <add> nativeModuleName, <add> ast, <add> `No ${language} interfaces extending TurboModule were detected in this NativeModule spec.`, <add> ); <add> } <add>} <add> <add>class MoreThanOneModuleInterfaceParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowModuleInterfaces: $ReadOnlyArray<$FlowFixMe>, <add> names: $ReadOnlyArray<string>, <add> language: ParserType, <add> ) { <add> const finalName = names[names.length - 1]; <add> const allButLastName = names.slice(0, -1); <add> const quote = (x: string) => `'${x}'`; <add> <add> const nameStr = <add> allButLastName.map(quote).join(', ') + ', and ' + quote(finalName); <add> <add> super( <add> nativeModuleName, <add> flowModuleInterfaces, <add> `Every NativeModule spec file must declare exactly one NativeModule ${language} interface. This file declares ${names.length}: ${nameStr}. Please remove the extraneous ${language} interface declarations.`, <add> ); <add> } <add>} <add> <add>class UnsupportedModulePropertyParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> propertyValue: $FlowFixMe, <add> propertyName: string, <add> invalidPropertyValueType: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> propertyValue, <add> `${language} interfaces extending TurboModule must only contain 'FunctionTypeAnnotation's. Property '${propertyName}' refers to a '${invalidPropertyValueType}'.`, <add> ); <add> } <add>} <add> <add>class UnsupportedTypeAnnotationParserError extends ParserError { <add> +typeAnnotationType: string; <add> constructor( <add> nativeModuleName: string, <add> typeAnnotation: $FlowFixMe, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> typeAnnotation, <add> `${language} type annotation '${typeAnnotation.type}' is unsupported in NativeModule specs.`, <add> ); <add> <add> this.typeAnnotationType = typeAnnotation.type; <add> } <add>} <add> <add>class UnsupportedGenericParserError extends ParserError { <add> +genericName: string; <add> constructor( <add> nativeModuleName: string, <add> genericTypeAnnotation: $FlowFixMe, <add> language: ParserType, <add> ) { <add> const genericName = <add> language === 'TypeScript' <add> ? genericTypeAnnotation.typeName.name <add> : genericTypeAnnotation.id.name; <add> super( <add> nativeModuleName, <add> genericTypeAnnotation, <add> `Unrecognized generic type '${genericName}' in NativeModule spec.`, <add> ); <add> <add> this.genericName = genericName; <add> } <add>} <add> <add>class IncorrectlyParameterizedGenericParserError extends ParserError { <add> +genericName: string; <add> +numTypeParameters: number; <add> <add> // $FlowFixMe[missing-local-annot] <add> constructor( <add> nativeModuleName: string, <add> genericTypeAnnotation: $FlowFixMe, <add> language: ParserType, <add> ) { <add> const genericName = <add> language === 'TypeScript' <add> ? genericTypeAnnotation.typeName.name <add> : genericTypeAnnotation.id.name; <add> if (genericTypeAnnotation.typeParameters == null) { <add> super( <add> nativeModuleName, <add> genericTypeAnnotation, <add> `Generic '${genericName}' must have type parameters.`, <add> ); <add> return; <add> } <add> <add> if ( <add> genericTypeAnnotation.typeParameters.type === <add> 'TypeParameterInstantiation' && <add> genericTypeAnnotation.typeParameters.params.length !== 1 <add> ) { <add> super( <add> nativeModuleName, <add> genericTypeAnnotation.typeParameters, <add> `Generic '${genericName}' must have exactly one type parameter.`, <add> ); <add> return; <add> } <add> <add> invariant( <add> false, <add> "Couldn't create IncorrectlyParameterizedGenericParserError", <add> ); <add> } <add>} <add> <add>/** <add> * Array parsing errors <add> */ <add> <add>class UnsupportedArrayElementTypeAnnotationParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> arrayElementTypeAST: $FlowFixMe, <add> arrayType: 'Array' | '$ReadOnlyArray' | 'ReadonlyArray', <add> invalidArrayElementType: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> arrayElementTypeAST, <add> `${arrayType} element types cannot be '${invalidArrayElementType}'.`, <add> ); <add> } <add>} <add> <add>/** <add> * Object parsing errors <add> */ <add> <add>class UnsupportedObjectPropertyTypeAnnotationParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> propertyAST: $FlowFixMe, <add> invalidPropertyType: string, <add> language: ParserType, <add> ) { <add> let message = `'ObjectTypeAnnotation' cannot contain '${invalidPropertyType}'.`; <add> <add> if ( <add> invalidPropertyType === 'ObjectTypeSpreadProperty' && <add> language !== 'TypeScript' <add> ) { <add> message = "Object spread isn't supported in 'ObjectTypeAnnotation's."; <add> } <add> <add> super(nativeModuleName, propertyAST, message); <add> } <add>} <add> <add>class UnsupportedObjectPropertyValueTypeAnnotationParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> propertyValueAST: $FlowFixMe, <add> propertyName: string, <add> invalidPropertyValueType: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> propertyValueAST, <add> `Object property '${propertyName}' cannot have type '${invalidPropertyValueType}'.`, <add> ); <add> } <add>} <add> <add>/** <add> * Function parsing errors <add> */ <add> <add>class UnnamedFunctionParamParserError extends ParserError { <add> constructor( <add> functionParam: $FlowFixMe, <add> nativeModuleName: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> functionParam, <add> 'All function parameters must be named.', <add> ); <add> } <add>} <add> <add>class UnsupportedFunctionParamTypeAnnotationParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowParamTypeAnnotation: $FlowFixMe, <add> paramName: string, <add> invalidParamType: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> flowParamTypeAnnotation, <add> `Function parameter '${paramName}' cannot have type '${invalidParamType}'.`, <add> ); <add> } <add>} <add> <add>class UnsupportedFunctionReturnTypeAnnotationParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowReturnTypeAnnotation: $FlowFixMe, <add> invalidReturnType: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> flowReturnTypeAnnotation, <add> `Function return cannot have type '${invalidReturnType}'.`, <add> ); <add> } <add>} <add> <add>/** <add> * Enum parsing errors <add> */ <add> <add>class UnsupportedEnumDeclarationParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> arrayElementTypeAST: $FlowFixMe, <add> memberType: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> arrayElementTypeAST, <add> `Unexpected enum member type ${memberType}. Only string and number enum members are supported`, <add> ); <add> } <add>} <add> <add>/** <add> * Union parsing errors <add> */ <add> <add>class UnsupportedUnionTypeAnnotationParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> arrayElementTypeAST: $FlowFixMe, <add> types: string[], <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> arrayElementTypeAST, <add> `Union members must be of the same type, but multiple types were found ${types.join( <add> ', ', <add> )}'.`, <add> ); <add> } <add>} <add> <add>/** <add> * Module parsing errors <add> */ <add> <add>class UnusedModuleInterfaceParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowInterface: $FlowFixMe, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> flowInterface, <add> "Unused NativeModule spec. Please load the NativeModule by calling TurboModuleRegistry.get<Spec>('<moduleName>').", <add> ); <add> } <add>} <add> <add>class MoreThanOneModuleRegistryCallsParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowCallExpressions: $FlowFixMe, <add> numCalls: number, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> flowCallExpressions, <add> `Every NativeModule spec file must contain exactly one NativeModule load. This file contains ${numCalls}. Please simplify this spec file, splitting it as necessary, to remove the extraneous loads.`, <add> ); <add> } <add>} <add> <add>class UntypedModuleRegistryCallParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowCallExpression: $FlowFixMe, <add> methodName: string, <add> moduleName: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> flowCallExpression, <add> `Please type this NativeModule load: TurboModuleRegistry.${methodName}<Spec>('${moduleName}').`, <add> ); <add> } <add>} <add> <add>class IncorrectModuleRegistryCallTypeParameterParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowTypeArguments: $FlowFixMe, <add> methodName: string, <add> moduleName: string, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> flowTypeArguments, <add> `Please change these type arguments to reflect TurboModuleRegistry.${methodName}<Spec>('${moduleName}').`, <add> ); <add> } <add>} <add> <add>class IncorrectModuleRegistryCallArityParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowCallExpression: $FlowFixMe, <add> methodName: string, <add> incorrectArity: number, <add> language: ParserType, <add> ) { <add> super( <add> nativeModuleName, <add> flowCallExpression, <add> `Please call TurboModuleRegistry.${methodName}<Spec>() with exactly one argument. Detected ${incorrectArity}.`, <add> ); <add> } <add>} <add> <add>class IncorrectModuleRegistryCallArgumentTypeParserError extends ParserError { <add> constructor( <add> nativeModuleName: string, <add> flowArgument: $FlowFixMe, <add> methodName: string, <add> type: string, <add> language: ParserType, <add> ) { <add> const a = /[aeiouy]/.test(type.toLowerCase()) ? 'an' : 'a'; <add> super( <add> nativeModuleName, <add> flowArgument, <add> `Please call TurboModuleRegistry.${methodName}<Spec>() with a string literal. Detected ${a} '${type}'`, <add> ); <add> } <add>} <add> <ide> module.exports = { <ide> ParserError, <add> IncorrectlyParameterizedGenericParserError, <add> MisnamedModuleInterfaceParserError, <add> ModuleInterfaceNotFoundParserError, <add> MoreThanOneModuleInterfaceParserError, <add> UnnamedFunctionParamParserError, <add> UnsupportedArrayElementTypeAnnotationParserError, <add> UnsupportedGenericParserError, <add> UnsupportedTypeAnnotationParserError, <add> UnsupportedFunctionParamTypeAnnotationParserError, <add> UnsupportedFunctionReturnTypeAnnotationParserError, <add> UnsupportedEnumDeclarationParserError, <add> UnsupportedUnionTypeAnnotationParserError, <add> UnsupportedModulePropertyParserError, <add> UnsupportedObjectPropertyTypeAnnotationParserError, <add> UnsupportedObjectPropertyValueTypeAnnotationParserError, <add> UnusedModuleInterfaceParserError, <add> MoreThanOneModuleRegistryCallsParserError, <add> UntypedModuleRegistryCallParserError, <add> IncorrectModuleRegistryCallTypeParameterParserError, <add> IncorrectModuleRegistryCallArityParserError, <add> IncorrectModuleRegistryCallArgumentTypeParserError, <ide> }; <ide><path>packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js <ide> import type { <ide> const {parseString} = require('../../index.js'); <ide> const {unwrapNullable} = require('../../../parsers-commons'); <ide> const { <del> UnsupportedFlowGenericParserError, <del> UnsupportedFlowTypeAnnotationParserError, <add> UnsupportedGenericParserError, <add> UnsupportedTypeAnnotationParserError, <ide> UnnamedFunctionParamParserError, <del> IncorrectlyParameterizedFlowGenericParserError, <del>} = require('../errors'); <add> IncorrectlyParameterizedGenericParserError, <add>} = require('../../../errors'); <ide> const invariant = require('invariant'); <ide> <ide> type PrimitiveTypeAnnotationType = <ide> describe('Flow Module Parser', () => { <ide> export default TurboModuleRegistry.get<Spec>('Foo'); <ide> `); <ide> <del> expect(parser).toThrow(UnsupportedFlowTypeAnnotationParserError); <add> expect(parser).toThrow(UnsupportedTypeAnnotationParserError); <ide> }); <ide> <ide> it('should fail parsing when a function param type is unamed', () => { <ide> describe('Flow Module Parser', () => { <ide> () => { <ide> it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Function'`, () => { <ide> expect(() => parseParamType('arg', 'Function')).toThrow( <del> UnsupportedFlowGenericParserError, <add> UnsupportedGenericParserError, <ide> ); <ide> }); <ide> <ide> describe('Flow Module Parser', () => { <ide> describe('Array Types', () => { <ide> it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array'`, () => { <ide> expect(() => parseParamType('arg', 'Array')).toThrow( <del> IncorrectlyParameterizedFlowGenericParserError, <add> IncorrectlyParameterizedGenericParserError, <ide> ); <ide> }); <ide> <ide> describe('Flow Module Parser', () => { <ide> it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { <ide> expect(() => <ide> parseParamTypeObjectLiteralProp('prop', 'Array'), <del> ).toThrow(IncorrectlyParameterizedFlowGenericParserError); <add> ).toThrow(IncorrectlyParameterizedGenericParserError); <ide> }); <ide> <ide> function parseArrayElementType( <ide> describe('Flow Module Parser', () => { <ide> describe('Array Types', () => { <ide> it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array'`, () => { <ide> expect(() => parseReturnType('Array')).toThrow( <del> IncorrectlyParameterizedFlowGenericParserError, <add> IncorrectlyParameterizedGenericParserError, <ide> ); <ide> }); <ide> <ide> describe('Flow Module Parser', () => { <ide> <ide> it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Function'`, () => { <ide> expect(() => parseReturnType('Function')).toThrow( <del> UnsupportedFlowGenericParserError, <add> UnsupportedGenericParserError, <ide> ); <ide> }); <ide> <ide> describe('Flow Module Parser', () => { <ide> it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { <ide> expect(() => <ide> parseObjectLiteralReturnTypeProp('prop', 'Array'), <del> ).toThrow(IncorrectlyParameterizedFlowGenericParserError); <add> ).toThrow(IncorrectlyParameterizedGenericParserError); <ide> }); <ide> <ide> function parseArrayElementType( <ide><path>packages/react-native-codegen/src/parsers/flow/modules/errors.js <del>/** <del> * Copyright (c) Meta Platforms, Inc. and affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @flow strict-local <del> * @format <del> */ <del> <del>'use strict'; <del> <del>const invariant = require('invariant'); <del>const {ParserError} = require('../../errors'); <del> <del>class MisnamedModuleFlowInterfaceParserError extends ParserError { <del> constructor(hasteModuleName: string, id: $FlowFixMe) { <del> super( <del> hasteModuleName, <del> id, <del> `All Flow interfaces extending TurboModule must be called 'Spec'. Please rename Flow interface '${id.name}' to 'Spec'.`, <del> ); <del> } <del>} <del> <del>class ModuleFlowInterfaceNotFoundParserError extends ParserError { <del> constructor(hasteModuleName: string, ast: $FlowFixMe) { <del> super( <del> hasteModuleName, <del> ast, <del> 'No Flow interfaces extending TurboModule were detected in this NativeModule spec.', <del> ); <del> } <del>} <del> <del>class MoreThanOneModuleFlowInterfaceParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowModuleInterfaces: $ReadOnlyArray<$FlowFixMe>, <del> names: $ReadOnlyArray<string>, <del> ) { <del> const finalName = names[names.length - 1]; <del> const allButLastName = names.slice(0, -1); <del> const quote = (x: string) => `'${x}'`; <del> <del> const nameStr = <del> allButLastName.map(quote).join(', ') + ', and ' + quote(finalName); <del> <del> super( <del> hasteModuleName, <del> flowModuleInterfaces, <del> `Every NativeModule spec file must declare exactly one NativeModule Flow interface. This file declares ${names.length}: ${nameStr}. Please remove the extraneous Flow interface declarations.`, <del> ); <del> } <del>} <del> <del>class UnsupportedModulePropertyParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> propertyValue: $FlowFixMe, <del> propertyName: string, <del> invalidPropertyValueType: string, <del> ) { <del> super( <del> hasteModuleName, <del> propertyValue, <del> `Flow interfaces extending TurboModule must only contain 'FunctionTypeAnnotation's. Property '${propertyName}' refers to a '${invalidPropertyValueType}'.`, <del> ); <del> } <del>} <del> <del>class UnsupportedFlowTypeAnnotationParserError extends ParserError { <del> +typeAnnotationType: string; <del> constructor(hasteModuleName: string, typeAnnotation: $FlowFixMe) { <del> super( <del> hasteModuleName, <del> typeAnnotation, <del> `Flow type annotation '${typeAnnotation.type}' is unsupported in NativeModule specs.`, <del> ); <del> <del> this.typeAnnotationType = typeAnnotation.type; <del> } <del>} <del> <del>class UnsupportedFlowGenericParserError extends ParserError { <del> +genericName: string; <del> constructor(hasteModuleName: string, genericTypeAnnotation: $FlowFixMe) { <del> const genericName = genericTypeAnnotation.id.name; <del> super( <del> hasteModuleName, <del> genericTypeAnnotation, <del> `Unrecognized generic type '${genericName}' in NativeModule spec.`, <del> ); <del> <del> this.genericName = genericName; <del> } <del>} <del> <del>class IncorrectlyParameterizedFlowGenericParserError extends ParserError { <del> +genericName: string; <del> +numTypeParameters: number; <del> <del> // $FlowFixMe[missing-local-annot] <del> constructor(hasteModuleName: string, genericTypeAnnotation: $FlowFixMe) { <del> if (genericTypeAnnotation.typeParameters == null) { <del> super( <del> hasteModuleName, <del> genericTypeAnnotation, <del> `Generic '${genericTypeAnnotation.id.name}' must have type parameters.`, <del> ); <del> return; <del> } <del> <del> if ( <del> genericTypeAnnotation.typeParameters.type === <del> 'TypeParameterInstantiation' && <del> genericTypeAnnotation.typeParameters.params.length !== 1 <del> ) { <del> super( <del> hasteModuleName, <del> genericTypeAnnotation.typeParameters, <del> `Generic '${genericTypeAnnotation.id.name}' must have exactly one type parameter.`, <del> ); <del> return; <del> } <del> <del> invariant( <del> false, <del> "Couldn't create IncorrectlyParameterizedFlowGenericParserError", <del> ); <del> } <del>} <del> <del>/** <del> * Array parsing errors <del> */ <del> <del>class UnsupportedArrayElementTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> arrayElementTypeAST: $FlowFixMe, <del> arrayType: 'Array' | '$ReadOnlyArray', <del> invalidArrayElementType: string, <del> ) { <del> super( <del> hasteModuleName, <del> arrayElementTypeAST, <del> `${arrayType} element types cannot be '${invalidArrayElementType}'.`, <del> ); <del> } <del>} <del> <del>/** <del> * Object parsing errors <del> */ <del> <del>class UnsupportedObjectPropertyTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> propertyAST: $FlowFixMe, <del> invalidPropertyType: string, <del> ) { <del> let message = `'ObjectTypeAnnotation' cannot contain '${invalidPropertyType}'.`; <del> <del> if (invalidPropertyType === 'ObjectTypeSpreadProperty') { <del> message = "Object spread isn't supported in 'ObjectTypeAnnotation's."; <del> } <del> <del> super(hasteModuleName, propertyAST, message); <del> } <del>} <del> <del>class UnsupportedObjectPropertyValueTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> propertyValueAST: $FlowFixMe, <del> propertyName: string, <del> invalidPropertyValueType: string, <del> ) { <del> super( <del> hasteModuleName, <del> propertyValueAST, <del> `Object property '${propertyName}' cannot have type '${invalidPropertyValueType}'.`, <del> ); <del> } <del>} <del> <del>/** <del> * Function parsing errors <del> */ <del> <del>class UnnamedFunctionParamParserError extends ParserError { <del> constructor(functionParam: $FlowFixMe, hasteModuleName: string) { <del> super( <del> hasteModuleName, <del> functionParam, <del> 'All function parameters must be named.', <del> ); <del> } <del>} <del> <del>class UnsupportedFunctionParamTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowParamTypeAnnotation: $FlowFixMe, <del> paramName: string, <del> invalidParamType: string, <del> ) { <del> super( <del> hasteModuleName, <del> flowParamTypeAnnotation, <del> `Function parameter '${paramName}' cannot have type '${invalidParamType}'.`, <del> ); <del> } <del>} <del> <del>class UnsupportedFunctionReturnTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowReturnTypeAnnotation: $FlowFixMe, <del> invalidReturnType: string, <del> ) { <del> super( <del> hasteModuleName, <del> flowReturnTypeAnnotation, <del> `Function return cannot have type '${invalidReturnType}'.`, <del> ); <del> } <del>} <del> <del>/** <del> * Enum parsing errors <del> */ <del> <del>class UnsupportedEnumDeclarationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> arrayElementTypeAST: $FlowFixMe, <del> memberType: string, <del> ) { <del> super( <del> hasteModuleName, <del> arrayElementTypeAST, <del> `Unexpected enum member type ${memberType}. Only string and number enum members are supported`, <del> ); <del> } <del>} <del> <del>/** <del> * Union parsing errors <del> */ <del> <del>class UnsupportedUnionTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> arrayElementTypeAST: $FlowFixMe, <del> types: string[], <del> ) { <del> super( <del> hasteModuleName, <del> arrayElementTypeAST, <del> `Union members must be of the same type, but multiple types were found ${types.join( <del> ', ', <del> )}'.`, <del> ); <del> } <del>} <del> <del>/** <del> * Module parsing errors <del> */ <del> <del>class UnusedModuleFlowInterfaceParserError extends ParserError { <del> constructor(hasteModuleName: string, flowInterface: $FlowFixMe) { <del> super( <del> hasteModuleName, <del> flowInterface, <del> "Unused NativeModule spec. Please load the NativeModule by calling TurboModuleRegistry.get<Spec>('<moduleName>').", <del> ); <del> } <del>} <del> <del>class MoreThanOneModuleRegistryCallsParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowCallExpressions: $FlowFixMe, <del> numCalls: number, <del> ) { <del> super( <del> hasteModuleName, <del> flowCallExpressions, <del> `Every NativeModule spec file must contain exactly one NativeModule load. This file contains ${numCalls}. Please simplify this spec file, splitting it as necessary, to remove the extraneous loads.`, <del> ); <del> } <del>} <del> <del>class UntypedModuleRegistryCallParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowCallExpression: $FlowFixMe, <del> methodName: string, <del> moduleName: string, <del> ) { <del> super( <del> hasteModuleName, <del> flowCallExpression, <del> `Please type this NativeModule load: TurboModuleRegistry.${methodName}<Spec>('${moduleName}').`, <del> ); <del> } <del>} <del> <del>class IncorrectModuleRegistryCallTypeParameterParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowTypeArguments: $FlowFixMe, <del> methodName: string, <del> moduleName: string, <del> ) { <del> super( <del> hasteModuleName, <del> flowTypeArguments, <del> `Please change these type arguments to reflect TurboModuleRegistry.${methodName}<Spec>('${moduleName}').`, <del> ); <del> } <del>} <del> <del>class IncorrectModuleRegistryCallArityParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowCallExpression: $FlowFixMe, <del> methodName: string, <del> incorrectArity: number, <del> ) { <del> super( <del> hasteModuleName, <del> flowCallExpression, <del> `Please call TurboModuleRegistry.${methodName}<Spec>() with exactly one argument. Detected ${incorrectArity}.`, <del> ); <del> } <del>} <del> <del>class IncorrectModuleRegistryCallArgumentTypeParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowArgument: $FlowFixMe, <del> methodName: string, <del> type: string, <del> ) { <del> const a = /[aeiouy]/.test(type.toLowerCase()) ? 'an' : 'a'; <del> super( <del> hasteModuleName, <del> flowArgument, <del> `Please call TurboModuleRegistry.${methodName}<Spec>() with a string literal. Detected ${a} '${type}'`, <del> ); <del> } <del>} <del> <del>module.exports = { <del> IncorrectlyParameterizedFlowGenericParserError, <del> MisnamedModuleFlowInterfaceParserError, <del> ModuleFlowInterfaceNotFoundParserError, <del> MoreThanOneModuleFlowInterfaceParserError, <del> UnnamedFunctionParamParserError, <del> UnsupportedArrayElementTypeAnnotationParserError, <del> UnsupportedFlowGenericParserError, <del> UnsupportedFlowTypeAnnotationParserError, <del> UnsupportedFunctionParamTypeAnnotationParserError, <del> UnsupportedFunctionReturnTypeAnnotationParserError, <del> UnsupportedEnumDeclarationParserError, <del> UnsupportedUnionTypeAnnotationParserError, <del> UnsupportedModulePropertyParserError, <del> UnsupportedObjectPropertyTypeAnnotationParserError, <del> UnsupportedObjectPropertyValueTypeAnnotationParserError, <del> UnusedModuleFlowInterfaceParserError, <del> MoreThanOneModuleRegistryCallsParserError, <del> UntypedModuleRegistryCallParserError, <del> IncorrectModuleRegistryCallTypeParameterParserError, <del> IncorrectModuleRegistryCallArityParserError, <del> IncorrectModuleRegistryCallArgumentTypeParserError, <del>}; <ide><path>packages/react-native-codegen/src/parsers/flow/modules/index.js <ide> const { <ide> emitInt32, <ide> } = require('../../parsers-primitives'); <ide> const { <del> IncorrectlyParameterizedFlowGenericParserError, <del> MisnamedModuleFlowInterfaceParserError, <del> ModuleFlowInterfaceNotFoundParserError, <del> MoreThanOneModuleFlowInterfaceParserError, <add> IncorrectlyParameterizedGenericParserError, <add> MisnamedModuleInterfaceParserError, <add> ModuleInterfaceNotFoundParserError, <add> MoreThanOneModuleInterfaceParserError, <ide> UnnamedFunctionParamParserError, <ide> UnsupportedArrayElementTypeAnnotationParserError, <del> UnsupportedFlowGenericParserError, <del> UnsupportedFlowTypeAnnotationParserError, <add> UnsupportedGenericParserError, <add> UnsupportedTypeAnnotationParserError, <ide> UnsupportedFunctionParamTypeAnnotationParserError, <ide> UnsupportedFunctionReturnTypeAnnotationParserError, <ide> UnsupportedEnumDeclarationParserError, <ide> UnsupportedUnionTypeAnnotationParserError, <ide> UnsupportedModulePropertyParserError, <ide> UnsupportedObjectPropertyTypeAnnotationParserError, <ide> UnsupportedObjectPropertyValueTypeAnnotationParserError, <del> UnusedModuleFlowInterfaceParserError, <add> UnusedModuleInterfaceParserError, <ide> MoreThanOneModuleRegistryCallsParserError, <ide> UntypedModuleRegistryCallParserError, <ide> IncorrectModuleRegistryCallTypeParameterParserError, <ide> IncorrectModuleRegistryCallArityParserError, <ide> IncorrectModuleRegistryCallArgumentTypeParserError, <del>} = require('./errors.js'); <add>} = require('../../errors.js'); <ide> <ide> const invariant = require('invariant'); <add>const language = 'Flow'; <ide> <ide> function nullGuard<T>(fn: () => T): ?T { <ide> return fn(); <ide> function translateTypeAnnotation( <ide> typeAnnotation.typeParameters.params[0], <ide> typeAnnotation.type, <ide> 'void', <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> typeAnnotation.typeParameters.params[0], <ide> typeAnnotation.type, <ide> 'Promise', <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> typeAnnotation.typeParameters.params[0], <ide> typeAnnotation.type, <ide> 'FunctionTypeAnnotation', <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> hasteModuleName, <ide> typeAnnotation, <ide> memberType, <add> language, <ide> ); <ide> } <ide> } <del> throw new UnsupportedFlowGenericParserError( <add> throw new UnsupportedGenericParserError( <ide> hasteModuleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> } <ide> function translateTypeAnnotation( <ide> hasteModuleName, <ide> property, <ide> property.type, <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> property.value, <ide> property.key, <ide> propertyTypeAnnotation.type, <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> property.value, <ide> property.key, <ide> 'void', <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> property.value, <ide> property.key, <ide> 'Promise', <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> hasteModuleName, <ide> typeAnnotation, <ide> unionTypes, <add> language, <ide> ); <ide> } <ide> return wrapNullable(nullable, { <ide> function translateTypeAnnotation( <ide> // Fallthrough <ide> } <ide> default: { <del> throw new UnsupportedFlowTypeAnnotationParserError( <add> throw new UnsupportedTypeAnnotationParserError( <ide> hasteModuleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> } <ide> function assertGenericTypeAnnotationHasExactlyOneTypeParameter( <ide> typeAnnotation: $FlowFixMe, <ide> ) { <ide> if (typeAnnotation.typeParameters == null) { <del> throw new IncorrectlyParameterizedFlowGenericParserError( <add> throw new IncorrectlyParameterizedGenericParserError( <ide> moduleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> <ide> function assertGenericTypeAnnotationHasExactlyOneTypeParameter( <ide> ); <ide> <ide> if (typeAnnotation.typeParameters.params.length !== 1) { <del> throw new IncorrectlyParameterizedFlowGenericParserError( <add> throw new IncorrectlyParameterizedGenericParserError( <ide> moduleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> } <ide> function translateFunctionTypeAnnotation( <ide> for (const flowParam of (flowFunctionTypeAnnotation.params: $ReadOnlyArray<$FlowFixMe>)) { <ide> const parsedParam = tryParse(() => { <ide> if (flowParam.name == null) { <del> throw new UnnamedFunctionParamParserError(flowParam, hasteModuleName); <add> throw new UnnamedFunctionParamParserError( <add> flowParam, <add> hasteModuleName, <add> language, <add> ); <ide> } <ide> <ide> const paramName = flowParam.name.name; <ide> function translateFunctionTypeAnnotation( <ide> flowParam.typeAnnotation, <ide> paramName, <ide> 'void', <add> language, <ide> ); <ide> } <ide> <ide> function translateFunctionTypeAnnotation( <ide> flowParam.typeAnnotation, <ide> paramName, <ide> 'Promise', <add> language, <ide> ); <ide> } <ide> <ide> function translateFunctionTypeAnnotation( <ide> hasteModuleName, <ide> flowFunctionTypeAnnotation.returnType, <ide> 'FunctionTypeAnnotation', <add> language, <ide> ); <ide> } <ide> <ide> function buildPropertySchema( <ide> property.value, <ide> property.key.name, <ide> value.type, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> ); <ide> <ide> if (moduleSpecs.length === 0) { <del> throw new ModuleFlowInterfaceNotFoundParserError(hasteModuleName, ast); <add> throw new ModuleInterfaceNotFoundParserError( <add> hasteModuleName, <add> ast, <add> language, <add> ); <ide> } <ide> <ide> if (moduleSpecs.length > 1) { <del> throw new MoreThanOneModuleFlowInterfaceParserError( <add> throw new MoreThanOneModuleInterfaceParserError( <ide> hasteModuleName, <ide> moduleSpecs, <ide> moduleSpecs.map(node => node.id.name), <add> language, <ide> ); <ide> } <ide> <ide> const [moduleSpec] = moduleSpecs; <ide> <ide> if (moduleSpec.id.name !== 'Spec') { <del> throw new MisnamedModuleFlowInterfaceParserError( <add> throw new MisnamedModuleInterfaceParserError( <ide> hasteModuleName, <ide> moduleSpec.id, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> }); <ide> <ide> if (callExpressions.length === 0) { <del> throw new UnusedModuleFlowInterfaceParserError( <add> throw new UnusedModuleInterfaceParserError( <ide> hasteModuleName, <ide> moduleSpec, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> hasteModuleName, <ide> callExpressions, <ide> callExpressions.length, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> callExpression, <ide> methodName, <ide> callExpression.arguments.length, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> callExpression.arguments[0], <ide> methodName, <ide> type, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> callExpression, <ide> methodName, <ide> $moduleName, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> typeArguments, <ide> methodName, <ide> $moduleName, <add> language, <ide> ); <ide> } <ide> <ide><path>packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js <ide> import type { <ide> const {parseString} = require('../../index.js'); <ide> const {unwrapNullable} = require('../../../parsers-commons'); <ide> const { <del> UnsupportedTypeScriptGenericParserError, <del> UnsupportedTypeScriptTypeAnnotationParserError, <add> UnsupportedGenericParserError, <add> UnsupportedTypeAnnotationParserError, <ide> UnnamedFunctionParamParserError, <del> IncorrectlyParameterizedTypeScriptGenericParserError, <del>} = require('../errors'); <add> IncorrectlyParameterizedGenericParserError, <add>} = require('../../../errors'); <ide> const invariant = require('invariant'); <ide> <ide> type PrimitiveTypeAnnotationType = <ide> describe('TypeScript Module Parser', () => { <ide> export default TurboModuleRegistry.get<Spec>('Foo'); <ide> `); <ide> <del> expect(parser).toThrow(UnsupportedTypeScriptTypeAnnotationParserError); <add> expect(parser).toThrow(UnsupportedTypeAnnotationParserError); <ide> }); <ide> <ide> it('should fail parsing when a function param type is unamed', () => { <ide> describe('TypeScript Module Parser', () => { <ide> () => { <ide> it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Function'`, () => { <ide> expect(() => parseParamType('arg', 'Function')).toThrow( <del> UnsupportedTypeScriptGenericParserError, <add> UnsupportedGenericParserError, <ide> ); <ide> }); <ide> <ide> describe('TypeScript Module Parser', () => { <ide> describe('Array Types', () => { <ide> it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array'`, () => { <ide> expect(() => parseParamType('arg', 'Array')).toThrow( <del> IncorrectlyParameterizedTypeScriptGenericParserError, <add> IncorrectlyParameterizedGenericParserError, <ide> ); <ide> }); <ide> <ide> describe('TypeScript Module Parser', () => { <ide> it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { <ide> expect(() => <ide> parseParamTypeObjectLiteralProp('prop', 'Array'), <del> ).toThrow( <del> IncorrectlyParameterizedTypeScriptGenericParserError, <del> ); <add> ).toThrow(IncorrectlyParameterizedGenericParserError); <ide> }); <ide> <ide> function parseArrayElementType( <ide> describe('TypeScript Module Parser', () => { <ide> describe('Array Types', () => { <ide> it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array'`, () => { <ide> expect(() => parseReturnType('Array')).toThrow( <del> IncorrectlyParameterizedTypeScriptGenericParserError, <add> IncorrectlyParameterizedGenericParserError, <ide> ); <ide> }); <ide> <ide> describe('TypeScript Module Parser', () => { <ide> <ide> it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Function'`, () => { <ide> expect(() => parseReturnType('Function')).toThrow( <del> UnsupportedTypeScriptGenericParserError, <add> UnsupportedGenericParserError, <ide> ); <ide> }); <ide> <ide> describe('TypeScript Module Parser', () => { <ide> it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { <ide> expect(() => <ide> parseObjectLiteralReturnTypeProp('prop', 'Array'), <del> ).toThrow( <del> IncorrectlyParameterizedTypeScriptGenericParserError, <del> ); <add> ).toThrow(IncorrectlyParameterizedGenericParserError); <ide> }); <ide> <ide> function parseArrayElementType( <ide><path>packages/react-native-codegen/src/parsers/typescript/modules/errors.js <del>/** <del> * Copyright (c) Meta Platforms, Inc. and affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @flow strict-local <del> * @format <del> */ <del> <del>'use strict'; <del> <del>const invariant = require('invariant'); <del>const {ParserError} = require('../../errors'); <del> <del>class MisnamedModuleTypeScriptInterfaceParserError extends ParserError { <del> constructor(hasteModuleName: string, id: $FlowFixMe) { <del> super( <del> hasteModuleName, <del> id, <del> `All TypeScript interfaces extending TurboModule must be called 'Spec'. Please rename TypeScript interface '${id.name}' to 'Spec'.`, <del> ); <del> } <del>} <del> <del>class ModuleTypeScriptInterfaceNotFoundParserError extends ParserError { <del> constructor(hasteModuleName: string, ast: $FlowFixMe) { <del> super( <del> hasteModuleName, <del> ast, <del> 'No TypeScript interfaces extending TurboModule were detected in this NativeModule spec.', <del> ); <del> } <del>} <del> <del>class MoreThanOneModuleTypeScriptInterfaceParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowModuleInterfaces: $ReadOnlyArray<$FlowFixMe>, <del> names: $ReadOnlyArray<string>, <del> ) { <del> const finalName = names[names.length - 1]; <del> const allButLastName = names.slice(0, -1); <del> const quote = (x: string) => `'${x}'`; <del> <del> const nameStr = <del> allButLastName.map(quote).join(', ') + ', and ' + quote(finalName); <del> <del> super( <del> hasteModuleName, <del> flowModuleInterfaces, <del> `Every NativeModule spec file must declare exactly one NativeModule TypeScript interface. This file declares ${names.length}: ${nameStr}. Please remove the extraneous TypeScript interface declarations.`, <del> ); <del> } <del>} <del> <del>class UnsupportedModulePropertyParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> propertyValue: $FlowFixMe, <del> propertyName: string, <del> invalidPropertyValueType: string, <del> ) { <del> super( <del> hasteModuleName, <del> propertyValue, <del> `TypeScript interfaces extending TurboModule must only contain 'FunctionTypeAnnotation's. Property '${propertyName}' refers to a '${invalidPropertyValueType}'.`, <del> ); <del> } <del>} <del> <del>class UnsupportedTypeScriptTypeAnnotationParserError extends ParserError { <del> +typeAnnotationType: string; <del> constructor(hasteModuleName: string, typeAnnotation: $FlowFixMe) { <del> super( <del> hasteModuleName, <del> typeAnnotation, <del> `TypeScript type annotation '${typeAnnotation.type}' is unsupported in NativeModule specs.`, <del> ); <del> <del> this.typeAnnotationType = typeAnnotation.type; <del> } <del>} <del> <del>class UnsupportedTypeScriptGenericParserError extends ParserError { <del> +genericName: string; <del> constructor(hasteModuleName: string, genericTypeAnnotation: $FlowFixMe) { <del> const genericName = genericTypeAnnotation.typeName.name; <del> super( <del> hasteModuleName, <del> genericTypeAnnotation, <del> `Unrecognized generic type '${genericName}' in NativeModule spec.`, <del> ); <del> <del> this.genericName = genericName; <del> } <del>} <del> <del>class IncorrectlyParameterizedTypeScriptGenericParserError extends ParserError { <del> +genericName: string; <del> +numTypeParameters: number; <del> <del> // $FlowFixMe[missing-local-annot] <del> constructor(hasteModuleName: string, genericTypeAnnotation: $FlowFixMe) { <del> if (genericTypeAnnotation.typeParameters == null) { <del> super( <del> hasteModuleName, <del> genericTypeAnnotation, <del> `Generic '${genericTypeAnnotation.typeName.name}' must have type parameters.`, <del> ); <del> return; <del> } <del> <del> if ( <del> genericTypeAnnotation.typeParameters.type === <del> 'TypeParameterInstantiation' && <del> genericTypeAnnotation.typeParameters.params.length !== 1 <del> ) { <del> super( <del> hasteModuleName, <del> genericTypeAnnotation.typeParameters, <del> `Generic '${genericTypeAnnotation.typeName.name}' must have exactly one type parameter.`, <del> ); <del> return; <del> } <del> <del> invariant( <del> false, <del> "Couldn't create IncorrectlyParameterizedFlowGenericParserError", <del> ); <del> } <del>} <del> <del>/** <del> * Array parsing errors <del> */ <del> <del>class UnsupportedArrayElementTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> arrayElementTypeAST: $FlowFixMe, <del> arrayType: 'Array' | 'ReadonlyArray', <del> invalidArrayElementType: string, <del> ) { <del> super( <del> hasteModuleName, <del> arrayElementTypeAST, <del> `${arrayType} element types cannot be '${invalidArrayElementType}'.`, <del> ); <del> } <del>} <del> <del>/** <del> * Object parsing errors <del> */ <del> <del>class UnsupportedObjectPropertyTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> propertyAST: $FlowFixMe, <del> invalidPropertyType: string, <del> ) { <del> let message = `'ObjectTypeAnnotation' cannot contain '${invalidPropertyType}'.`; <del> <del> super(hasteModuleName, propertyAST, message); <del> } <del>} <del> <del>class UnsupportedObjectPropertyValueTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> propertyValueAST: $FlowFixMe, <del> propertyName: string, <del> invalidPropertyValueType: string, <del> ) { <del> super( <del> hasteModuleName, <del> propertyValueAST, <del> `Object property '${propertyName}' cannot have type '${invalidPropertyValueType}'.`, <del> ); <del> } <del>} <del> <del>/** <del> * Function parsing errors <del> */ <del> <del>class UnnamedFunctionParamParserError extends ParserError { <del> constructor(functionParam: $FlowFixMe, hasteModuleName: string) { <del> super( <del> hasteModuleName, <del> functionParam, <del> 'All function parameters must be named.', <del> ); <del> } <del>} <del> <del>class UnsupportedFunctionParamTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowParamTypeAnnotation: $FlowFixMe, <del> paramName: string, <del> invalidParamType: string, <del> ) { <del> super( <del> hasteModuleName, <del> flowParamTypeAnnotation, <del> `Function parameter '${paramName}' cannot have type '${invalidParamType}'.`, <del> ); <del> } <del>} <del> <del>class UnsupportedFunctionReturnTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowReturnTypeAnnotation: $FlowFixMe, <del> invalidReturnType: string, <del> ) { <del> super( <del> hasteModuleName, <del> flowReturnTypeAnnotation, <del> `Function return cannot have type '${invalidReturnType}'.`, <del> ); <del> } <del>} <del> <del>/** <del> * Enum parsing errors <del> */ <del> <del>class UnsupportedTypeScriptEnumDeclarationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> arrayElementTypeAST: $FlowFixMe, <del> memberType: string, <del> ) { <del> super( <del> hasteModuleName, <del> arrayElementTypeAST, <del> `Unexpected enum member type ${memberType}. Only string and number enum members are supported`, <del> ); <del> } <del>} <del> <del>/** <del> * Union parsing errors <del> */ <del> <del>class UnsupportedTypeScriptUnionTypeAnnotationParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> arrayElementTypeAST: $FlowFixMe, <del> types: string[], <del> ) { <del> super( <del> hasteModuleName, <del> arrayElementTypeAST, <del> `Union members must be of the same type, but multiple types were found ${types.join( <del> ', ', <del> )}'.`, <del> ); <del> } <del>} <del> <del>/** <del> * Module parsing errors <del> */ <del> <del>class UnusedModuleTypeScriptInterfaceParserError extends ParserError { <del> constructor(hasteModuleName: string, flowInterface: $FlowFixMe) { <del> super( <del> hasteModuleName, <del> flowInterface, <del> "Unused NativeModule spec. Please load the NativeModule by calling TurboModuleRegistry.get<Spec>('<moduleName>').", <del> ); <del> } <del>} <del> <del>class MoreThanOneModuleRegistryCallsParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowCallExpressions: $FlowFixMe, <del> numCalls: number, <del> ) { <del> super( <del> hasteModuleName, <del> flowCallExpressions, <del> `Every NativeModule spec file must contain exactly one NativeModule load. This file contains ${numCalls}. Please simplify this spec file, splitting it as necessary, to remove the extraneous loads.`, <del> ); <del> } <del>} <del> <del>class UntypedModuleRegistryCallParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowCallExpression: $FlowFixMe, <del> methodName: string, <del> moduleName: string, <del> ) { <del> super( <del> hasteModuleName, <del> flowCallExpression, <del> `Please type this NativeModule load: TurboModuleRegistry.${methodName}<Spec>('${moduleName}').`, <del> ); <del> } <del>} <del> <del>class IncorrectModuleRegistryCallTypeParameterParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowTypeArguments: $FlowFixMe, <del> methodName: string, <del> moduleName: string, <del> ) { <del> super( <del> hasteModuleName, <del> flowTypeArguments, <del> `Please change these type arguments to reflect TurboModuleRegistry.${methodName}<Spec>('${moduleName}').`, <del> ); <del> } <del>} <del> <del>class IncorrectModuleRegistryCallArityParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowCallExpression: $FlowFixMe, <del> methodName: string, <del> incorrectArity: number, <del> ) { <del> super( <del> hasteModuleName, <del> flowCallExpression, <del> `Please call TurboModuleRegistry.${methodName}<Spec>() with exactly one argument. Detected ${incorrectArity}.`, <del> ); <del> } <del>} <del> <del>class IncorrectModuleRegistryCallArgumentTypeParserError extends ParserError { <del> constructor( <del> hasteModuleName: string, <del> flowArgument: $FlowFixMe, <del> methodName: string, <del> type: string, <del> ) { <del> const a = /[aeiouy]/.test(type.toLowerCase()) ? 'an' : 'a'; <del> super( <del> hasteModuleName, <del> flowArgument, <del> `Please call TurboModuleRegistry.${methodName}<Spec>() with a string literal. Detected ${a} '${type}'`, <del> ); <del> } <del>} <del> <del>module.exports = { <del> IncorrectlyParameterizedTypeScriptGenericParserError, <del> MisnamedModuleTypeScriptInterfaceParserError, <del> ModuleTypeScriptInterfaceNotFoundParserError, <del> MoreThanOneModuleTypeScriptInterfaceParserError, <del> UnnamedFunctionParamParserError, <del> UnsupportedArrayElementTypeAnnotationParserError, <del> UnsupportedTypeScriptGenericParserError, <del> UnsupportedTypeScriptTypeAnnotationParserError, <del> UnsupportedFunctionParamTypeAnnotationParserError, <del> UnsupportedFunctionReturnTypeAnnotationParserError, <del> UnsupportedTypeScriptEnumDeclarationParserError, <del> UnsupportedTypeScriptUnionTypeAnnotationParserError, <del> UnsupportedModulePropertyParserError, <del> UnsupportedObjectPropertyTypeAnnotationParserError, <del> UnsupportedObjectPropertyValueTypeAnnotationParserError, <del> UnusedModuleTypeScriptInterfaceParserError, <del> MoreThanOneModuleRegistryCallsParserError, <del> UntypedModuleRegistryCallParserError, <del> IncorrectModuleRegistryCallTypeParameterParserError, <del> IncorrectModuleRegistryCallArityParserError, <del> IncorrectModuleRegistryCallArgumentTypeParserError, <del>}; <ide><path>packages/react-native-codegen/src/parsers/typescript/modules/index.js <ide> const { <ide> emitInt32, <ide> } = require('../../parsers-primitives'); <ide> const { <del> IncorrectlyParameterizedTypeScriptGenericParserError, <del> MisnamedModuleTypeScriptInterfaceParserError, <del> ModuleTypeScriptInterfaceNotFoundParserError, <del> MoreThanOneModuleTypeScriptInterfaceParserError, <add> IncorrectlyParameterizedGenericParserError, <add> MisnamedModuleInterfaceParserError, <add> ModuleInterfaceNotFoundParserError, <add> MoreThanOneModuleInterfaceParserError, <ide> UnnamedFunctionParamParserError, <ide> UnsupportedArrayElementTypeAnnotationParserError, <del> UnsupportedTypeScriptGenericParserError, <del> UnsupportedTypeScriptTypeAnnotationParserError, <add> UnsupportedGenericParserError, <add> UnsupportedTypeAnnotationParserError, <ide> UnsupportedFunctionParamTypeAnnotationParserError, <ide> UnsupportedFunctionReturnTypeAnnotationParserError, <del> UnsupportedTypeScriptEnumDeclarationParserError, <del> UnsupportedTypeScriptUnionTypeAnnotationParserError, <add> UnsupportedEnumDeclarationParserError, <add> UnsupportedUnionTypeAnnotationParserError, <ide> UnsupportedModulePropertyParserError, <ide> UnsupportedObjectPropertyTypeAnnotationParserError, <ide> UnsupportedObjectPropertyValueTypeAnnotationParserError, <del> UnusedModuleTypeScriptInterfaceParserError, <add> UnusedModuleInterfaceParserError, <ide> MoreThanOneModuleRegistryCallsParserError, <ide> UntypedModuleRegistryCallParserError, <ide> IncorrectModuleRegistryCallTypeParameterParserError, <ide> IncorrectModuleRegistryCallArityParserError, <ide> IncorrectModuleRegistryCallArgumentTypeParserError, <del>} = require('./errors.js'); <add>} = require('../../errors.js'); <ide> <ide> const invariant = require('invariant'); <add>const language = 'TypeScript'; <ide> <ide> function nullGuard<T>(fn: () => T): ?T { <ide> return fn(); <ide> function translateArrayTypeAnnotation( <ide> tsElementType, <ide> tsArrayType, <ide> 'void', <add> language, <ide> ); <ide> } <ide> <ide> function translateArrayTypeAnnotation( <ide> tsElementType, <ide> tsArrayType, <ide> 'Promise', <add> language, <ide> ); <ide> } <ide> <ide> function translateArrayTypeAnnotation( <ide> tsElementType, <ide> tsArrayType, <ide> 'FunctionTypeAnnotation', <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> nullable, <ide> ); <ide> } else { <del> throw new UnsupportedTypeScriptGenericParserError( <add> throw new UnsupportedGenericParserError( <ide> hasteModuleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> } <ide> function translateTypeAnnotation( <ide> memberType: memberType, <ide> }); <ide> } else { <del> throw new UnsupportedTypeScriptEnumDeclarationParserError( <add> throw new UnsupportedEnumDeclarationParserError( <ide> hasteModuleName, <ide> typeAnnotation, <ide> memberType, <add> language, <ide> ); <ide> } <ide> } <del> throw new UnsupportedTypeScriptGenericParserError( <add> throw new UnsupportedGenericParserError( <ide> hasteModuleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> } <ide> function translateTypeAnnotation( <ide> hasteModuleName, <ide> property, <ide> property.type, <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> property.typeAnnotation.typeAnnotation, <ide> property.key, <ide> propertyTypeAnnotation.type, <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> property.typeAnnotation.typeAnnotation, <ide> property.key, <ide> 'void', <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> property.typeAnnotation.typeAnnotation, <ide> property.key, <ide> 'Promise', <add> language, <ide> ); <ide> } <ide> <ide> function translateTypeAnnotation( <ide> .filter((value, index, self) => self.indexOf(value) === index); <ide> // Only support unionTypes of the same kind <ide> if (unionTypes.length > 1) { <del> throw new UnsupportedTypeScriptUnionTypeAnnotationParserError( <add> throw new UnsupportedUnionTypeAnnotationParserError( <ide> hasteModuleName, <ide> typeAnnotation, <ide> unionTypes, <add> language, <ide> ); <ide> } <ide> return wrapNullable(nullable, { <ide> function translateTypeAnnotation( <ide> // Fallthrough <ide> } <ide> default: { <del> throw new UnsupportedTypeScriptTypeAnnotationParserError( <add> throw new UnsupportedTypeAnnotationParserError( <ide> hasteModuleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> } <ide> function assertGenericTypeAnnotationHasExactlyOneTypeParameter( <ide> typeAnnotation: $FlowFixMe, <ide> ) { <ide> if (typeAnnotation.typeParameters == null) { <del> throw new IncorrectlyParameterizedTypeScriptGenericParserError( <add> throw new IncorrectlyParameterizedGenericParserError( <ide> moduleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> <ide> function assertGenericTypeAnnotationHasExactlyOneTypeParameter( <ide> ); <ide> <ide> if (typeAnnotation.typeParameters.params.length !== 1) { <del> throw new IncorrectlyParameterizedTypeScriptGenericParserError( <add> throw new IncorrectlyParameterizedGenericParserError( <ide> moduleName, <ide> typeAnnotation, <add> language, <ide> ); <ide> } <ide> } <ide> function translateFunctionTypeAnnotation( <ide> throw new UnnamedFunctionParamParserError( <ide> typeScriptParam, <ide> hasteModuleName, <add> language, <ide> ); <ide> } <ide> <ide> function translateFunctionTypeAnnotation( <ide> typeScriptParam.typeAnnotation, <ide> paramName, <ide> 'void', <add> language, <ide> ); <ide> } <ide> <ide> function translateFunctionTypeAnnotation( <ide> typeScriptParam.typeAnnotation, <ide> paramName, <ide> 'Promise', <add> language, <ide> ); <ide> } <ide> <ide> function translateFunctionTypeAnnotation( <ide> hasteModuleName, <ide> typescriptFunctionTypeAnnotation.returnType, <ide> 'FunctionTypeAnnotation', <add> language, <ide> ); <ide> } <ide> <ide> function buildPropertySchema( <ide> property.value, <ide> property.key.name, <ide> value.type, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> ); <ide> <ide> if (moduleSpecs.length === 0) { <del> throw new ModuleTypeScriptInterfaceNotFoundParserError( <add> throw new ModuleInterfaceNotFoundParserError( <ide> hasteModuleName, <ide> ast, <add> language, <ide> ); <ide> } <ide> <ide> if (moduleSpecs.length > 1) { <del> throw new MoreThanOneModuleTypeScriptInterfaceParserError( <add> throw new MoreThanOneModuleInterfaceParserError( <ide> hasteModuleName, <ide> moduleSpecs, <ide> moduleSpecs.map(node => node.id.name), <add> language, <ide> ); <ide> } <ide> <ide> const [moduleSpec] = moduleSpecs; <ide> <ide> if (moduleSpec.id.name !== 'Spec') { <del> throw new MisnamedModuleTypeScriptInterfaceParserError( <add> throw new MisnamedModuleInterfaceParserError( <ide> hasteModuleName, <ide> moduleSpec.id, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> }); <ide> <ide> if (callExpressions.length === 0) { <del> throw new UnusedModuleTypeScriptInterfaceParserError( <add> throw new UnusedModuleInterfaceParserError( <ide> hasteModuleName, <ide> moduleSpec, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> hasteModuleName, <ide> callExpressions, <ide> callExpressions.length, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> callExpression, <ide> methodName, <ide> callExpression.arguments.length, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> callExpression.arguments[0], <ide> methodName, <ide> type, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> callExpression, <ide> methodName, <ide> $moduleName, <add> language, <ide> ); <ide> } <ide> <ide> function buildModuleSchema( <ide> typeParameters, <ide> methodName, <ide> $moduleName, <add> language, <ide> ); <ide> } <ide>
7
Ruby
Ruby
add missing require to routes inspector
f99453071bc1673a51da06b88b78140a37bce084
<ide><path>actionpack/lib/action_dispatch/routing/inspector.rb <ide> require 'delegate' <add>require 'active_support/core_ext/string/strip' <ide> <ide> module ActionDispatch <ide> module Routing
1
Javascript
Javascript
remove old code
a65762cab6edf33d87a129e406f633dfa445bb23
<ide><path>src/node.js <ide> var tty = NativeModule.require('tty'); <ide> stream = new tty.WriteStream(fd); <ide> stream._type = 'tty'; <del> <del> // Hack to have stream not keep the event loop alive. <del> // See https://github.com/joyent/node/issues/1726 <del> if (stream._handle && stream._handle.unref) { <del> stream._handle.unref(); <del> } <ide> break; <ide> <ide> case 'FILE': <ide> readable: false, <ide> writable: true <ide> }); <del> <del> // FIXME Should probably have an option in net.Socket to create a <del> // stream from an existing fd which is writable only. But for now <del> // we'll just add this hack and set the `readable` member to false. <del> // Test: ./node test/fixtures/echo.js < /etc/passwd <del> stream.readable = false; <del> stream.read = null; <ide> stream._type = 'pipe'; <del> <del> // FIXME Hack to have stream not keep the event loop alive. <del> // See https://github.com/joyent/node/issues/1726 <del> if (stream._handle && stream._handle.unref) { <del> stream._handle.unref(); <del> } <ide> break; <ide> <ide> default:
1
Ruby
Ruby
add plugins and builtins to the load_path
25b5161e16dc67a8c3d4cce2937a81f19fd37ca6
<ide><path>railties/lib/initializer.rb <ide> def default_load_paths <ide> lib <ide> vendor <ide> ).map { |dir| "#{root_path}/#{dir}" }.select { |dir| File.directory?(dir) } <add> <add> paths.concat Dir["#{root_path}/vendor/plugins/*/lib/"] <add> paths.concat builtin_directories <ide> end <ide> <ide> def default_load_once_paths
1
Text
Text
add docs [ci skip]
40f13c3f0ceb004560e94d99b4ccc835b9f52360
<ide><path>website/docs/api/cli.md <ide> copied into the package and imported in the `__init__.py`. If the path to a <ide> [`meta.json`](/api/data-formats#meta) is supplied, or a `meta.json` is found in <ide> the input directory, this file is used. Otherwise, the data can be entered <ide> directly from the command line. spaCy will then create a build artifact that you <del>can distribute and install with `pip install`. <add>can distribute and install with `pip install`. As of v3.1, the `package` command <add>will also create a formatted `README.md` based on the pipeline information <add>defined in the `meta.json`. If a `README.md` is already present in the source <add>directory, it will be used instead. <ide> <ide> <Infobox title="New in v3.0" variant="warning"> <ide>
1
Go
Go
use logs instead of attach for builder
6f09d064bd438ab4425d6105f40887f02bb9e97e
<ide><path>builder/internals.go <ide> import ( <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/log" <ide> "github.com/docker/docker/pkg/parsers" <del> "github.com/docker/docker/pkg/promise" <ide> "github.com/docker/docker/pkg/symlink" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/pkg/tarsum" <ide> func (b *Builder) create() (*daemon.Container, error) { <ide> } <ide> <ide> func (b *Builder) run(c *daemon.Container) error { <del> var errCh chan error <del> if b.Verbose { <del> errCh = promise.Go(func() error { <del> // FIXME: call the 'attach' job so that daemon.Attach can be made private <del> // <del> // FIXME (LK4D4): Also, maybe makes sense to call "logs" job, it is like attach <del> // but without hijacking for stdin. Also, with attach there can be race <del> // condition because of some output already was printed before it. <del> return <-b.Daemon.Attach(&c.StreamConfig, c.Config.OpenStdin, c.Config.StdinOnce, c.Config.Tty, nil, nil, b.OutStream, b.ErrStream) <del> }) <del> } <del> <ide> //start the container <ide> if err := c.Start(); err != nil { <ide> return err <ide> } <ide> <del> if errCh != nil { <del> if err := <-errCh; err != nil { <add> if b.Verbose { <add> logsJob := b.Engine.Job("logs", c.ID) <add> logsJob.Setenv("follow", "1") <add> logsJob.Setenv("stdout", "1") <add> logsJob.Setenv("stderr", "1") <add> logsJob.Stdout.Add(b.OutStream) <add> logsJob.Stderr.Add(b.ErrStream) <add> if err := logsJob.Run(); err != nil { <ide> return err <ide> } <ide> } <ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildVerifySingleQuoteFails(t *testing.T) { <ide> <ide> logDone("build - verify single quotes fail") <ide> } <add> <add>func TestBuildVerboseOut(t *testing.T) { <add> name := "testbuildverboseout" <add> defer deleteImages(name) <add> <add> _, out, err := buildImageWithOut(name, <add> `FROM busybox <add>RUN echo 123`, <add> false) <add> <add> if err != nil { <add> t.Fatal(err) <add> } <add> if !strings.Contains(out, "\n123\n") { <add> t.Fatalf("Output should contain %q: %q", "123", out) <add> } <add> <add> logDone("build - verbose output from commands") <add>}
2
Python
Python
remove node_path from environment for tests
22d7dc221211678dd1d5ce30d298791df7dfd956
<ide><path>tools/test.py <ide> def Execute(args, context, timeout=None, env={}, faketty=False): <ide> fd_in = 0 <ide> pty_out = None <ide> <del> # Extend environment <ide> env_copy = os.environ.copy() <add> <add> # Remove NODE_PATH <add> if "NODE_PATH" in env_copy: <add> del env_copy["NODE_PATH"] <add> <add> # Extend environment <ide> for key, value in env.iteritems(): <ide> env_copy[key] = value <ide>
1
Python
Python
correct an issue if section did not exist
551bdbfe851297095d7fc7a52f88e36cef5a457a
<ide><path>glances/config.py <ide> from io import open <ide> import re <ide> <del>from glances.compat import ConfigParser, NoOptionError, system_exec <add>from glances.compat import ConfigParser, NoOptionError, NoSectionError, system_exec <ide> from glances.globals import BSD, LINUX, MACOS, SUNOS, WINDOWS <ide> from glances.logger import logger <ide> <ide> def get_value(self, section, option, <ide> ret = default <ide> try: <ide> ret = self.parser.get(section, option) <del> except NoOptionError: <add> except (NoOptionError, NoSectionError): <ide> pass <ide> <ide> # Search a substring `foo` and replace it by the result of its exec <ide> def get_int_value(self, section, option, default=0): <ide> """Get the int value of an option, if it exists.""" <ide> try: <ide> return self.parser.getint(section, option) <del> except NoOptionError: <add> except (NoOptionError, NoSectionError): <ide> return int(default) <ide> <ide> def get_float_value(self, section, option, default=0.0): <ide> """Get the float value of an option, if it exists.""" <ide> try: <ide> return self.parser.getfloat(section, option) <del> except NoOptionError: <add> except (NoOptionError, NoSectionError): <ide> return float(default) <ide> <ide> def get_bool_value(self, section, option, default=True): <ide> """Get the bool value of an option, if it exists.""" <ide> try: <ide> return self.parser.getboolean(section, option) <del> except NoOptionError: <add> except (NoOptionError, NoSectionError): <ide> return bool(default) <ide><path>glances/plugins/glances_diskio.py <ide> def __init__(self, args=None, config=None): <ide> self.display_curse = True <ide> # Hide stats if it has never been != 0 <ide> self.hide_zero = config.get_bool_value( <del> self.plugin_name, 'hide_zero', default=False) <add> self.plugin_name + 'XXX', 'hide_zero', default=False) <ide> self.hide_zero_fields = ['read_bytes', 'write_bytes'] <ide> <ide> def get_key(self):
2
Java
Java
introduce messaging package
69ef364ef9b874db3c88f7a3f84f6ab5182d22c7
<add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/StompCommand.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/StompCommand.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.stomp; <add>package org.springframework.web.messaging.stomp; <ide> <ide> <ide> /** <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/StompException.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/StompException.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.web.stomp; <add>package org.springframework.web.messaging.stomp; <ide> <ide> import org.springframework.core.NestedRuntimeException; <ide> <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/StompHeaders.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/StompHeaders.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.stomp; <add>package org.springframework.web.messaging.stomp; <ide> <ide> import java.io.Serializable; <ide> import java.util.Collection; <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/StompMessage.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/StompMessage.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.stomp; <add>package org.springframework.web.messaging.stomp; <ide> <ide> import java.nio.charset.Charset; <ide> <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/StompSession.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/StompSession.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.web.stomp; <add>package org.springframework.web.messaging.stomp; <ide> <ide> import java.io.IOException; <ide> <ide> <ide> /** <del> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide> public interface StompSession { <ide> String getId(); <ide> <ide> /** <add> * TODO... <add> * <p> <ide> * If the message is a STOMP ERROR message, the session will also be closed. <del> * <ide> */ <ide> void sendMessage(StompMessage message) throws IOException; <ide> <add> /** <add> * Register a task to be invoked if the underlying connection is closed. <add> */ <add> void registerConnectionClosedCallback(Runnable task); <add> <ide> } <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/adapter/StompMessageHandler.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/adapter/StompMessageProcessor.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.stomp.adapter; <add>package org.springframework.web.messaging.stomp.adapter; <ide> <del>import org.springframework.web.stomp.StompMessage; <del>import org.springframework.web.stomp.StompSession; <add>import org.springframework.web.messaging.stomp.StompMessage; <add>import org.springframework.web.messaging.stomp.StompSession; <ide> <ide> <ide> /** <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public interface StompMessageProcessor { <add>public interface StompMessageHandler { <ide> <del> void processMessage(StompSession stompSession, StompMessage message); <del> <del> void processConnectionClosed(StompSession stompSession); <add> void handleMessage(StompSession stompSession, StompMessage message); <ide> <ide> } <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/adapter/StompWebSocketHandler.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/adapter/StompWebSocketHandler.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.web.stomp.adapter; <add>package org.springframework.web.messaging.stomp.adapter; <ide> <ide> import java.util.Map; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> <ide> import org.springframework.util.Assert; <add>import org.springframework.web.messaging.stomp.StompCommand; <add>import org.springframework.web.messaging.stomp.StompHeaders; <add>import org.springframework.web.messaging.stomp.StompMessage; <add>import org.springframework.web.messaging.stomp.StompSession; <add>import org.springframework.web.messaging.stomp.support.StompMessageConverter; <ide> import org.springframework.web.socket.CloseStatus; <ide> import org.springframework.web.socket.TextMessage; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.socket.adapter.TextWebSocketHandlerAdapter; <del>import org.springframework.web.stomp.StompCommand; <del>import org.springframework.web.stomp.StompHeaders; <del>import org.springframework.web.stomp.StompMessage; <del>import org.springframework.web.stomp.StompSession; <del>import org.springframework.web.stomp.support.StompMessageConverter; <ide> <ide> <ide> /** <del> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide> public class StompWebSocketHandler extends TextWebSocketHandlerAdapter { <ide> <del> private final StompMessageProcessor messageProcessor; <add> private final StompMessageHandler messageHandler; <ide> <ide> private final StompMessageConverter messageConverter = new StompMessageConverter(); <ide> <del> private final Map<String, StompSession> sessions = new ConcurrentHashMap<String, StompSession>(); <add> private final Map<String, WebSocketStompSession> sessions = new ConcurrentHashMap<String, WebSocketStompSession>(); <ide> <ide> <del> public StompWebSocketHandler(StompMessageProcessor messageProcessor) { <del> this.messageProcessor = messageProcessor; <add> public StompWebSocketHandler(StompMessageHandler messageHandler) { <add> this.messageHandler = messageHandler; <ide> } <ide> <ide> <ide> protected void handleTextMessage(WebSocketSession session, TextMessage message) <ide> // TODO: validate size limits <ide> // http://stomp.github.io/stomp-specification-1.2.html#Size_Limits <ide> <del> this.messageProcessor.processMessage(stompSession, stompMessage); <add> this.messageHandler.handleMessage(stompSession, stompMessage); <ide> <ide> // TODO: send RECEIPT message if incoming message has "receipt" header <ide> // http://stomp.github.io/stomp-specification-1.2.html#Header_receipt <ide> protected void handleTextMessage(WebSocketSession session, TextMessage message) <ide> <ide> @Override <ide> public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { <del> StompSession stompSession = this.sessions.remove(session.getId()); <add> WebSocketStompSession stompSession = this.sessions.remove(session.getId()); <ide> if (stompSession != null) { <del> this.messageProcessor.processConnectionClosed(stompSession); <add> stompSession.handleConnectionClosed(); <ide> } <ide> } <ide> <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/adapter/WebSocketStompSession.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/adapter/WebSocketStompSession.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.stomp.adapter; <add>package org.springframework.web.messaging.stomp.adapter; <ide> <ide> import java.io.IOException; <add>import java.util.ArrayList; <add>import java.util.List; <ide> <ide> import org.springframework.util.Assert; <add>import org.springframework.web.messaging.stomp.StompCommand; <add>import org.springframework.web.messaging.stomp.StompMessage; <add>import org.springframework.web.messaging.stomp.StompSession; <add>import org.springframework.web.messaging.stomp.support.StompMessageConverter; <ide> import org.springframework.web.socket.CloseStatus; <ide> import org.springframework.web.socket.TextMessage; <ide> import org.springframework.web.socket.WebSocketSession; <del>import org.springframework.web.stomp.StompCommand; <del>import org.springframework.web.stomp.StompMessage; <del>import org.springframework.web.stomp.StompSession; <del>import org.springframework.web.stomp.support.StompMessageConverter; <ide> <ide> <ide> /** <ide> public class WebSocketStompSession implements StompSession { <ide> <ide> private final StompMessageConverter messageConverter; <ide> <add> private final List<Runnable> connectionClosedTasks = new ArrayList<Runnable>(); <add> <ide> <ide> public WebSocketStompSession(WebSocketSession webSocketSession, StompMessageConverter messageConverter) { <ide> Assert.notNull(webSocketSession, "webSocketSession is required"); <ide> public void sendMessage(StompMessage message) throws IOException { <ide> } <ide> } <ide> <add> public void registerConnectionClosedCallback(Runnable task) { <add> this.connectionClosedTasks.add(task); <add> } <add> <add> public void handleConnectionClosed() { <add> for (Runnable task : this.connectionClosedTasks) { <add> try { <add> task.run(); <add> } <add> catch (Throwable t) { <add> // ignore <add> } <add> } <add> } <add> <ide> } <ide>\ No newline at end of file <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/server/RelayStompService.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/server/RelayStompReactorService.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.stomp.server; <add>package org.springframework.web.messaging.stomp.server; <ide> <ide> import java.io.BufferedInputStream; <ide> import java.io.BufferedOutputStream; <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.core.task.TaskExecutor; <del>import org.springframework.web.stomp.StompCommand; <del>import org.springframework.web.stomp.StompHeaders; <del>import org.springframework.web.stomp.StompMessage; <del>import org.springframework.web.stomp.support.StompMessageConverter; <add>import org.springframework.web.messaging.stomp.StompCommand; <add>import org.springframework.web.messaging.stomp.StompHeaders; <add>import org.springframework.web.messaging.stomp.StompMessage; <add>import org.springframework.web.messaging.stomp.support.StompMessageConverter; <ide> <ide> import reactor.Fn; <ide> import reactor.core.Reactor; <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class RelayStompReactorService { <add>public class RelayStompService { <ide> <del> private static final Log logger = LogFactory.getLog(RelayStompReactorService.class); <add> private static final Log logger = LogFactory.getLog(RelayStompService.class); <ide> <ide> <ide> private final Reactor reactor; <ide> public class RelayStompReactorService { <ide> private final TaskExecutor taskExecutor; <ide> <ide> <del> public RelayStompReactorService(Reactor reactor, TaskExecutor executor) { <add> public RelayStompService(Reactor reactor, TaskExecutor executor) { <ide> this.reactor = reactor; <ide> this.taskExecutor = executor; // For now, a naively way to manage socket reading <ide> <ide> private void relayStompMessage(RelaySession session, StompMessage stompMessage) <ide> } <ide> <ide> private RelaySession getRelaySession(String stompSessionId) { <del> RelaySession session = RelayStompReactorService.this.relaySessions.get(stompSessionId); <add> RelaySession session = RelayStompService.this.relaySessions.get(stompSessionId); <ide> Assert.notNull(session, "RelaySession not found"); <ide> return session; <ide> } <ide> public void run() { <ide> } <ide> else if (b == 0x00) { <ide> byte[] bytes = out.toByteArray(); <del> StompMessage message = RelayStompReactorService.this.converter.toStompMessage(bytes); <del> RelayStompReactorService.this.reactor.notify(replyTo, Fn.event(message)); <add> StompMessage message = RelayStompService.this.converter.toStompMessage(bytes); <add> RelayStompService.this.reactor.notify(replyTo, Fn.event(message)); <ide> out.reset(); <ide> } <ide> else { <ide> private void sendLostConnectionErrorMessage() { <ide> StompHeaders headers = new StompHeaders(); <ide> headers.setMessage("Lost connection"); <ide> StompMessage errorMessage = new StompMessage(StompCommand.ERROR, headers); <del> RelayStompReactorService.this.reactor.notify(replyTo, Fn.event(errorMessage)); <add> RelayStompService.this.reactor.notify(replyTo, Fn.event(errorMessage)); <ide> } <ide> } <ide> <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/server/ServerStompMessageHandler.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/server/ReactorServerStompMessageProcessor.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.web.stomp.server; <add>package org.springframework.web.messaging.stomp.server; <ide> <ide> import java.io.IOException; <ide> import java.util.ArrayList; <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.util.CollectionUtils; <del>import org.springframework.web.stomp.StompCommand; <del>import org.springframework.web.stomp.StompException; <del>import org.springframework.web.stomp.StompHeaders; <del>import org.springframework.web.stomp.StompMessage; <del>import org.springframework.web.stomp.StompSession; <del>import org.springframework.web.stomp.adapter.StompMessageProcessor; <add>import org.springframework.web.messaging.stomp.StompCommand; <add>import org.springframework.web.messaging.stomp.StompException; <add>import org.springframework.web.messaging.stomp.StompHeaders; <add>import org.springframework.web.messaging.stomp.StompMessage; <add>import org.springframework.web.messaging.stomp.StompSession; <add>import org.springframework.web.messaging.stomp.adapter.StompMessageHandler; <ide> <ide> import reactor.Fn; <ide> import reactor.core.Reactor; <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class ReactorServerStompMessageProcessor implements StompMessageProcessor { <add>public class ServerStompMessageHandler implements StompMessageHandler { <ide> <del> private static Log logger = LogFactory.getLog(ReactorServerStompMessageProcessor.class); <add> private static Log logger = LogFactory.getLog(ServerStompMessageHandler.class); <ide> <ide> <ide> private final Reactor reactor; <ide> <del> private Map<String, List<Registration<?>>> registrationsBySession = new ConcurrentHashMap<String, List<Registration<?>>>(); <add> private Map<String, List<Registration<?>>> registrationsBySession = <add> new ConcurrentHashMap<String, List<Registration<?>>>(); <ide> <ide> <del> public ReactorServerStompMessageProcessor(Reactor reactor) { <add> public ServerStompMessageHandler(Reactor reactor) { <ide> this.reactor = reactor; <ide> } <ide> <del> public void processMessage(StompSession session, StompMessage message) { <add> public void handleMessage(StompSession session, StompMessage message) { <ide> try { <ide> StompCommand command = message.getCommand(); <ide> if (StompCommand.CONNECT.equals(command) || StompCommand.STOMP.equals(command)) { <add> registerConnectionClosedCallback(session); <ide> connect(session, message); <ide> } <ide> else if (StompCommand.SUBSCRIBE.equals(command)) { <ide> else if (StompCommand.BEGIN.equals(command) || StompCommand.COMMIT.equals(comman <ide> } <ide> } <ide> <add> private void registerConnectionClosedCallback(final StompSession session) { <add> session.registerConnectionClosedCallback(new Runnable() { <add> @Override <add> public void run() { <add> removeSubscriptions(session); <add> reactor.notify("CONNECTION_CLOSED", Fn.event(session.getId())); <add> } <add> }); <add> } <add> <ide> private void handleError(final StompSession session, Throwable t) { <ide> logger.error("Terminating STOMP session due to failure to send message: ", t); <ide> sendErrorMessage(session, t.getMessage()); <ide> private boolean removeSubscriptions(StompSession session) { <ide> return true; <ide> } <ide> <del> @Override <del> public void processConnectionClosed(StompSession session) { <del> removeSubscriptions(session); <del> this.reactor.notify("CONNECTION_CLOSED", Fn.event(session.getId())); <del> } <del> <ide> } <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/server/SimpleStompService.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/server/SimpleStompReactorService.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.stomp.server; <add>package org.springframework.web.messaging.stomp.server; <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del>import org.springframework.web.stomp.StompCommand; <del>import org.springframework.web.stomp.StompHeaders; <del>import org.springframework.web.stomp.StompMessage; <add>import org.springframework.web.messaging.stomp.StompCommand; <add>import org.springframework.web.messaging.stomp.StompHeaders; <add>import org.springframework.web.messaging.stomp.StompMessage; <ide> <ide> import reactor.Fn; <ide> import reactor.core.Reactor; <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class SimpleStompReactorService { <add>public class SimpleStompService { <ide> <del> private static final Log logger = LogFactory.getLog(SimpleStompReactorService.class); <add> private static final Log logger = LogFactory.getLog(SimpleStompService.class); <ide> <ide> private final Reactor reactor; <ide> <ide> private Map<String, List<Registration<?>>> subscriptionsBySession = new ConcurrentHashMap<String, List<Registration<?>>>(); <ide> <ide> <del> public SimpleStompReactorService(Reactor reactor) { <add> public SimpleStompService(Reactor reactor) { <ide> this.reactor = reactor; <ide> this.reactor.on(Fn.$(StompCommand.SUBSCRIBE), new SubscribeConsumer()); <ide> this.reactor.on(Fn.$(StompCommand.SEND), new SendConsumer()); <ide> public void accept(Event<StompMessage> event) { <ide> logger.debug("Subscribe " + message); <ide> } <ide> <del> Registration<?> registration = SimpleStompReactorService.this.reactor.on( <add> Registration<?> registration = SimpleStompService.this.reactor.on( <ide> Fn.$("destination:" + message.getHeaders().getDestination()), <ide> new Consumer<Event<StompMessage>>() { <ide> @Override <ide> public void accept(Event<StompMessage> event) { <ide> StompHeaders headers = new StompHeaders(); <ide> headers.setDestination(inMessage.getHeaders().getDestination()); <ide> StompMessage outMessage = new StompMessage(StompCommand.MESSAGE, headers, inMessage.getPayload()); <del> SimpleStompReactorService.this.reactor.notify(event.getReplyTo(), Fn.event(outMessage)); <add> SimpleStompService.this.reactor.notify(event.getReplyTo(), Fn.event(outMessage)); <ide> } <ide> }); <ide> <ide> public void accept(Event<StompMessage> event) { <ide> logger.debug("Message received: " + message); <ide> <ide> String destination = message.getHeaders().getDestination(); <del> SimpleStompReactorService.this.reactor.notify("destination:" + destination, Fn.event(message)); <add> SimpleStompService.this.reactor.notify("destination:" + destination, Fn.event(message)); <ide> } <ide> } <ide> <ide> private final class DisconnectConsumer implements Consumer<Event<String>> { <ide> @Override <ide> public void accept(Event<String> event) { <ide> String sessionId = event.getData(); <del> SimpleStompReactorService.this.removeSubscriptions(sessionId); <add> SimpleStompService.this.removeSubscriptions(sessionId); <ide> } <ide> } <ide> <add><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompMessageConverter.java <del><path>spring-websocket/src/main/java/org/springframework/web/stomp/support/StompMessageConverter.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>package org.springframework.web.stomp.support; <add>package org.springframework.web.messaging.stomp.support; <ide> <ide> import java.io.ByteArrayOutputStream; <ide> import java.io.IOException; <ide> import java.util.List; <ide> import java.util.Map.Entry; <ide> <ide> import org.springframework.util.Assert; <del>import org.springframework.web.stomp.StompCommand; <del>import org.springframework.web.stomp.StompException; <del>import org.springframework.web.stomp.StompHeaders; <del>import org.springframework.web.stomp.StompMessage; <add>import org.springframework.web.messaging.stomp.StompCommand; <add>import org.springframework.web.messaging.stomp.StompException; <add>import org.springframework.web.messaging.stomp.StompHeaders; <add>import org.springframework.web.messaging.stomp.StompMessage; <ide> <ide> /** <ide> * @author Gary Russell
12
Text
Text
add integration test guidelines
2d5ea98b2c2223e97627aa0d03e68c3f84e3b662
<ide><path>TESTING.md <ide> Bugs fixes should include a unit test case which exercises the bug. <ide> A bug fix may also include new assertions in an existing integration tests for the <ide> API endpoint. <ide> <add>### Integration tests environment considerations <add> <add>When adding new tests or modifying existing test under `integration/`, testing <add>environment should be properly considered. `skip.If` from <add>[gotest.tools/skip](https://godoc.org/gotest.tools/skip) can be used to make the <add>test run conditionally. Full testing environment conditions can be found at <add>[environment.go](https://github.com/moby/moby/blob/cb37987ee11655ed6bbef663d245e55922354c68/internal/test/environment/environment.go) <add> <add>Here is a quick example. If the test needs to interact with a docker daemon on <add>the same host, the following condition should be checked within the test code <add> <add>```go <add>skip.If(t, testEnv.IsRemoteDaemon()) <add>// your integration test code <add>``` <add> <add>If a remote daemon is detected, the test will be skipped. <add> <ide> ## Running tests <ide> <ide> To run the unit test suite:
1
Text
Text
add instructions for core vuln files
eb33cb412202de09c1bba67b6a65f80f4b422168
<ide><path>doc/guides/security-release-process.md <ide> information described. <ide> * [ ] PR machine-readable JSON descriptions of the vulnerabilities to the <ide> [core](https://github.com/nodejs/security-wg/tree/HEAD/vuln/core) <ide> vulnerability DB. ***LINK TO PR*** <add> * For each vulnerability add a `#.json` file, one can copy an existing <add> [json](https://github.com/nodejs/security-wg/blob/0d82062d917cb9ddab88f910559469b2b13812bf/vuln/core/78.json) <add> file, and increment the latest created file number and use that as the name <add> of the new file to be added. For example, `79.json`. <ide> <ide> * [ ] Close this issue <ide>
1
Python
Python
fix bad names in animation tracks on geometries
412044d236d99b97ba23f83cc541fad31bd7e706
<ide><path>utils/exporters/blender/addons/io_three/exporter/api/mesh.py <ide> def animated_blend_shapes(mesh, name, options): <ide> :param options: <ide> <ide> """ <add> <add> # let filter the name to only keep the node's name <add> # the two cases are '%sGeometry' and '%sGeometry.%d', and we want %s <add> name = re.search("^(.*)Geometry(\..*)?$", name).group(1) <add> <ide> logger.debug("mesh.animated_blend_shapes(%s, %s)", mesh, options) <ide> tracks = [] <ide> shp = mesh.shape_keys
1
Python
Python
add cache_dir for tokenizer verification loading
6c4d688ffa8095f6dbaa959a51b53a91073f2aeb
<ide><path>src/transformers/tokenization_utils_base.py <ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], <ide> init_configuration, <ide> *init_inputs, <ide> use_auth_token=use_auth_token, <add> cache_dir=cache_dir, <ide> **kwargs, <ide> ) <ide> <ide> def _from_pretrained( <ide> init_configuration, <ide> *init_inputs, <ide> use_auth_token=None, <add> cache_dir=None, <ide> **kwargs <ide> ): <ide> # We instantiate fast tokenizers based on a slow tokenizer if we don't have access to the tokenizer.json <ide> def _from_pretrained( <ide> <ide> # Second attempt. If we have not yet found tokenizer_class, let's try to use the config. <ide> try: <del> config = AutoConfig.from_pretrained(pretrained_model_name_or_path, use_auth_token=use_auth_token) <add> config = AutoConfig.from_pretrained( <add> pretrained_model_name_or_path, <add> use_auth_token=use_auth_token, <add> cache_dir=cache_dir, <add> ) <ide> config_tokenizer_class = config.tokenizer_class <ide> except (OSError, ValueError, KeyError): <ide> # skip if an error occurred.
1
Javascript
Javascript
throw exception for sync version. don't use const
b6f05fb8c6c4dc4ce6a00fba34a57bc77b8b02ed
<ide><path>extensions/firefox/components/PdfStreamConverter.js <ide> const Cr = Components.results; <ide> const Cu = Components.utils; <ide> const PDFJS_EVENT_ID = 'pdf.js.message'; <ide> const PDF_CONTENT_TYPE = 'application/pdf'; <del>const NS_ERROR_NOT_IMPLEMENTED = 0x80004001; <ide> const EXT_PREFIX = '[email protected]'; <ide> <ide> Cu.import('resource://gre/modules/XPCOMUtils.jsm'); <ide> PdfStreamConverter.prototype = { <ide> <ide> // nsIStreamConverter::convert <ide> convert: function(aFromStream, aFromType, aToType, aCtxt) { <del> return aFromStream; <add> throw Cr.NS_ERROR_NOT_IMPLEMENTED; <ide> }, <ide> <ide> // nsIStreamConverter::asyncConvertData <ide> asyncConvertData: function(aFromType, aToType, aListener, aCtxt) { <ide> if (!Services.prefs.getBoolPref('extensions.pdf.js.active')) <del> throw NS_ERROR_NOT_IMPLEMENTED; <add> throw Cr.NS_ERROR_NOT_IMPLEMENTED; <ide> // Store the listener passed to us <ide> this.listener = aListener; <ide> },
1
Ruby
Ruby
remove bazillion warnings from ap suite
da583df50c32d50261b682664fe43fd5e2f58f87
<ide><path>actionpack/lib/action_dispatch/testing/integration.rb <ide> def url_options <ide> end <ide> <ide> def respond_to?(method, include_private = false) <del> @integration_session.respond_to?(method, include_private) || super <add> integration_session.respond_to?(method, include_private) || super <ide> end <ide> <ide> # Delegate unhandled messages to the current session instance.
1
Ruby
Ruby
allow post in pypi version
6735debcd43dea6248c1e95c0842cc8252a5ac58
<ide><path>Library/Homebrew/livecheck/strategy/pypi.rb <ide> def self.find_versions(url, regex = nil) <ide> <ide> # Example regex: `%r{href=.*?/packages.*?/example[._-]v?(\d+(?:\.\d+)*).t}i`. <ide> regex ||= <del> %r{href=.*?/packages.*?/#{Regexp.escape(package_name)}[._-]v?(\d+(?:\.\d+)*)#{Regexp.escape(suffix)}}i <add> %r{href=.*?/packages.*?/#{Regexp.escape(package_name)}[._-] <add> v?(\d+(?:\.\d+)*(.post\d)?)#{Regexp.escape(suffix)}}ix <ide> <ide> Homebrew::Livecheck::Strategy::PageMatch.find_versions(page_url, regex) <ide> end
1
Python
Python
add tests for the polynomial classes true division
24a0fd428b80d8db50a9bd5f1c151d3a99bcdcb2
<ide><path>numpy/polynomial/tests/test_classes.py <ide> """ <ide> from __future__ import division, absolute_import, print_function <ide> <add>import operator as op <add>from numbers import Number <add> <ide> import numpy as np <ide> from numpy.polynomial import ( <ide> Polynomial, Legendre, Chebyshev, Laguerre, <ide> TestCase, assert_almost_equal, assert_raises, <ide> assert_equal, assert_, run_module_suite, dec) <ide> from numpy.testing.noseclasses import KnownFailure <add>from numpy.compat import long <ide> <ide> <ide> classes = ( <ide> def test_class_methods(): <ide> yield check_sub, Poly <ide> yield check_mul, Poly <ide> yield check_floordiv, Poly <add> yield check_truediv, Poly <ide> yield check_mod, Poly <ide> yield check_divmod, Poly <ide> yield check_pow, Poly <ide> def check_add(Poly): <ide> assert_poly_almost_equal(tuple(c2) + p1, p3) <ide> assert_poly_almost_equal(p1 + np.array(c2), p3) <ide> assert_poly_almost_equal(np.array(c2) + p1, p3) <del> assert_raises(TypeError, p1.__add__, Poly([0], domain=Poly.domain + 1)) <del> assert_raises(TypeError, p1.__add__, Poly([0], window=Poly.window + 1)) <add> assert_raises(TypeError, op.add, p1, Poly([0], domain=Poly.domain + 1)) <add> assert_raises(TypeError, op.add, p1, Poly([0], window=Poly.window + 1)) <ide> if Poly is Polynomial: <del> assert_raises(TypeError, p1.__add__, Chebyshev([0])) <add> assert_raises(TypeError, op.add, p1, Chebyshev([0])) <ide> else: <del> assert_raises(TypeError, p1.__add__, Polynomial([0])) <add> assert_raises(TypeError, op.add, p1, Polynomial([0])) <ide> <ide> <ide> def check_sub(Poly): <ide> def check_sub(Poly): <ide> assert_poly_almost_equal(tuple(c2) - p1, -p3) <ide> assert_poly_almost_equal(p1 - np.array(c2), p3) <ide> assert_poly_almost_equal(np.array(c2) - p1, -p3) <del> assert_raises(TypeError, p1.__sub__, Poly([0], domain=Poly.domain + 1)) <del> assert_raises(TypeError, p1.__sub__, Poly([0], window=Poly.window + 1)) <add> assert_raises(TypeError, op.sub, p1, Poly([0], domain=Poly.domain + 1)) <add> assert_raises(TypeError, op.sub, p1, Poly([0], window=Poly.window + 1)) <ide> if Poly is Polynomial: <del> assert_raises(TypeError, p1.__sub__, Chebyshev([0])) <add> assert_raises(TypeError, op.sub, p1, Chebyshev([0])) <ide> else: <del> assert_raises(TypeError, p1.__sub__, Polynomial([0])) <add> assert_raises(TypeError, op.sub, p1, Polynomial([0])) <ide> <ide> <ide> def check_mul(Poly): <ide> def check_mul(Poly): <ide> assert_poly_almost_equal(np.array(c2) * p1, p3) <ide> assert_poly_almost_equal(p1 * 2, p1 * Poly([2])) <ide> assert_poly_almost_equal(2 * p1, p1 * Poly([2])) <del> assert_raises(TypeError, p1.__mul__, Poly([0], domain=Poly.domain + 1)) <del> assert_raises(TypeError, p1.__mul__, Poly([0], window=Poly.window + 1)) <add> assert_raises(TypeError, op.mul, p1, Poly([0], domain=Poly.domain + 1)) <add> assert_raises(TypeError, op.mul, p1, Poly([0], window=Poly.window + 1)) <ide> if Poly is Polynomial: <del> assert_raises(TypeError, p1.__mul__, Chebyshev([0])) <add> assert_raises(TypeError, op.mul, p1, Chebyshev([0])) <ide> else: <del> assert_raises(TypeError, p1.__mul__, Polynomial([0])) <add> assert_raises(TypeError, op.mul, p1, Polynomial([0])) <ide> <ide> <ide> def check_floordiv(Poly): <ide> def check_floordiv(Poly): <ide> assert_poly_almost_equal(2 // p2, Poly([0])) <ide> assert_poly_almost_equal(p2 // 2, 0.5*p2) <ide> assert_raises( <del> TypeError, p1.__floordiv__, Poly([0], domain=Poly.domain + 1)) <add> TypeError, op.floordiv, p1, Poly([0], domain=Poly.domain + 1)) <ide> assert_raises( <del> TypeError, p1.__floordiv__, Poly([0], window=Poly.window + 1)) <add> TypeError, op.floordiv, p1, Poly([0], window=Poly.window + 1)) <ide> if Poly is Polynomial: <del> assert_raises(TypeError, p1.__floordiv__, Chebyshev([0])) <add> assert_raises(TypeError, op.floordiv, p1, Chebyshev([0])) <ide> else: <del> assert_raises(TypeError, p1.__floordiv__, Polynomial([0])) <add> assert_raises(TypeError, op.floordiv, p1, Polynomial([0])) <add> <add> <add>def check_truediv(Poly): <add> # true division is valid only if the denominator is a Number and <add> # not a python bool. <add> p1 = Poly([1,2,3]) <add> p2 = p1 * 5 <add> <add> for stype in np.ScalarType: <add> if not issubclass(stype, Number) or issubclass(stype, bool): <add> continue <add> s = stype(5) <add> assert_poly_almost_equal(op.truediv(p2, s), p1) <add> assert_raises(TypeError, op.truediv, s, p2) <add> for stype in (int, long, float): <add> s = stype(5) <add> assert_poly_almost_equal(op.truediv(p2, s), p1) <add> assert_raises(TypeError, op.truediv, s, p2) <add> for stype in [complex]: <add> s = stype(5, 0) <add> assert_poly_almost_equal(op.truediv(p2, s), p1) <add> assert_raises(TypeError, op.truediv, s, p2) <add> for s in [tuple(), list(), dict(), bool(), np.array([1])]: <add> assert_raises(TypeError, op.truediv, p2, s) <add> assert_raises(TypeError, op.truediv, s, p2) <add> for ptype in classes: <add> assert_raises(TypeError, op.truediv, p2, ptype(1)) <ide> <ide> <ide> def check_mod(Poly): <ide> def check_mod(Poly): <ide> assert_poly_almost_equal(np.array(c4) % p2, p3) <ide> assert_poly_almost_equal(2 % p2, Poly([2])) <ide> assert_poly_almost_equal(p2 % 2, Poly([0])) <del> assert_raises(TypeError, p1.__mod__, Poly([0], domain=Poly.domain + 1)) <del> assert_raises(TypeError, p1.__mod__, Poly([0], window=Poly.window + 1)) <add> assert_raises(TypeError, op.mod, p1, Poly([0], domain=Poly.domain + 1)) <add> assert_raises(TypeError, op.mod, p1, Poly([0], window=Poly.window + 1)) <ide> if Poly is Polynomial: <del> assert_raises(TypeError, p1.__mod__, Chebyshev([0])) <add> assert_raises(TypeError, op.mod, p1, Chebyshev([0])) <ide> else: <del> assert_raises(TypeError, p1.__mod__, Polynomial([0])) <add> assert_raises(TypeError, op.mod, p1, Polynomial([0])) <ide> <ide> <ide> def check_divmod(Poly): <ide> def check_pow(Poly): <ide> for i in range(5): <ide> assert_poly_almost_equal(tst**i, tgt) <ide> tgt = tgt * tst <del> assert_raises(ValueError, tgt.__pow__, 1.5) <del> assert_raises(ValueError, tgt.__pow__, -1) <add> assert_raises(ValueError, op.pow, tgt, 1.5) <add> assert_raises(ValueError, op.pow, tgt, -1) <ide> <ide> <ide> def check_call(Poly):
1
Text
Text
fix wrong date in changelog for 1.8.3
47bf11ee94664367a26ed8c91b9b586d3dd420f5
<ide><path>CHANGELOG.md <ide> and [read the end of life announcement](https://goo.gle/angularjs-end-of-life).* <ide> **Visit [angular.io](https://angular.io) for the actively supported Angular.** <ide> <ide> <a name="1.8.3"></a> <del># 1.8.3 ultimate-farewell (2020-10-21) <add># 1.8.3 ultimate-farewell (2022-04-07) <ide> <ide> One final release of AngularJS in order to update package README files on npm. <ide>
1
Python
Python
scheduler bugfix and docs tweaks
94adbe30ea45edd4fff5f936e4f0ec8e5b6e8c4d
<ide><path>airflow/hooks/dbapi_hook.py <ide> def __init__(self, *args, **kwargs): <ide> setattr(self, self.conn_name_attr, kwargs[self.conn_name_attr]) <ide> <ide> def get_conn(self): <del> """Returns a connection object""" <add> """Returns a connection object <add> """ <ide> db = self.get_connection(getattr(self, self.conn_name_attr)) <ide> return self.connector.connect( <ide> host=db.host, <ide> def run(self, sql, autocommit=False, parameters=None): <ide> Runs a command or a list of commands. Pass a list of sql <ide> statements to the sql parameter to get them to execute <ide> sequentially <add> <ide> :param sql: the sql statement to be executed (str) or a list of <ide> sql statements to execute <ide> :type sql: str or list <ide> def set_autocommit(self, conn, autocommit): <ide> conn.autocommit = autocommit <ide> <ide> def get_cursor(self): <del> """Returns a cursor""" <add> """ <add> Returns a cursor <add> """ <ide> return self.get_conn().cursor() <ide> <ide> def insert_rows(self, table, rows, target_fields=None, commit_every=1000): <ide><path>airflow/jobs.py <ide> def prioritize_queued(self, session, executor, dagbag): <ide> pickle_id = dag.pickle(session).id <ide> <ide> if dag.dag_id in overloaded_dags or dag.concurrency_reached: <del> overloaded_dags.append(dag.dag_id) <add> overloaded_dags.add(dag.dag_id) <ide> continue <ide> if ti.are_dependencies_met(): <ide> executor.queue_task_instance( <ide><path>airflow/models.py <ide> def __init__(self, event, task_instance, owner=None, extra=None): <ide> self.task_id = task_instance.task_id <ide> self.execution_date = task_instance.execution_date <ide> task_owner = task_instance.task.owner <del> <add> <ide> self.owner = owner or task_owner <ide> <ide> <ide> class DAG(object): <ide> :param max_active_runs: maximum number of active DAG runs, beyond this <ide> number of DAG runs in a running state, the scheduler won't create <ide> new active DAG runs <del> ":type max_active_runs: int" <add> :type max_active_runs: int <ide> """ <ide> <ide> def __init__(
3
PHP
PHP
change default value for queue.failed.database
77c5c1726f4a8d9fff8c21dec838c2091c4c6afc
<ide><path>config/queue.php <ide> */ <ide> <ide> 'failed' => [ <del> 'database' => 'mysql', 'table' => 'failed_jobs', <add> 'database' => env('DB_CONNECTION', 'mysql'), <add> 'table' => 'failed_jobs', <ide> ], <ide> <ide> ];
1
Javascript
Javascript
fix some jsdoc errors
1c18a74ea08f02160d1e4ce823a5cde1e2e49a2f
<ide><path>src/core/core.controller.js <ide> class Chart { <ide> /** <ide> * Handle an event <ide> * @private <del> * @param {IEvent} event the event to handle <add> * @param {IEvent} e the event to handle <ide> * @return {boolean} true if the chart needs to re-render <ide> */ <ide> handleEvent(e) { <ide><path>src/core/core.datasetController.js <ide> helpers.extend(DatasetController.prototype, { <ide> <ide> // Re-sync meta data in case the user replaced the data array or if we missed <ide> // any updates and so make sure that we handle number of datapoints changing. <del> me.resyncElements(dataChanged | labelsChanged | scaleChanged | stackChanged); <add> me.resyncElements(dataChanged || labelsChanged || scaleChanged || stackChanged); <ide> <ide> // if stack changed, update stack values for the whole dataset <ide> if (stackChanged) { <ide> helpers.extend(DatasetController.prototype, { <ide> me._cacheScaleStackStatus(); <ide> }, <ide> <del> update: helpers.noop, <add> /** <add> * @param {string} mode <add> */ <add> update: function(mode) {}, // eslint-disable-line no-unused-vars <ide> <ide> draw: function() { <ide> const ctx = this._ctx; <ide> helpers.extend(DatasetController.prototype, { <ide> * Returns a set of predefined style properties that should be used to represent the dataset <ide> * or the data if the index is specified <ide> * @param {number} index - data index <add> * @param {boolean} [active] - true if hover <ide> * @return {IStyleInterface} style object <ide> */ <ide> getStyle: function(index, active) { <ide><path>src/core/core.interaction.js <ide> import {_lookup, _rlookup} from '../helpers/helpers.collection'; <ide> <ide> /** <ide> * Helper function to get relative position for an event <del> * @param {Event|IEvent} event - The event to get the position for <add> * @param {Event|IEvent} e - The event to get the position for <ide> * @param {Chart} chart - The chart <ide> * @returns {object} the event position <ide> */ <ide> function evaluateAllVisibleItems(chart, handler) { <ide> * @param {string} axis - the axis mide. x|y|xy <ide> * @param {number} value - the value to find <ide> * @param {boolean} intersect - should the element intersect <del> * @returns {lo, hi} indices to search data array between <add> * @returns {{lo:number, hi:number}} indices to search data array between <ide> */ <ide> function binarySearch(metaset, axis, value, intersect) { <ide> const {controller, data, _sorted} = metaset; <ide> function binarySearch(metaset, axis, value, intersect) { <ide> * @param {string} axis - the axis mode. x|y|xy <ide> * @param {object} position - the point to be nearest to <ide> * @param {function} handler - the callback to execute for each visible item <del> * @param {boolean} intersect - consider intersecting items <add> * @param {boolean} [intersect] - consider intersecting items <ide> */ <ide> function optimizedEvaluateItems(chart, axis, position, handler, intersect) { <ide> const metasets = chart._getSortedVisibleDatasetMetas(); <ide> function getIntersectItems(chart, position, axis) { <ide> * Helper function to get the items nearest to the event position considering all visible items in the chart <ide> * @param {Chart} chart - the chart to look at elements from <ide> * @param {object} position - the point to be nearest to <del> * @param {function} axis - the axes along which to measure distance <del> * @param {boolean} intersect - if true, only consider items that intersect the position <add> * @param {string} axis - the axes along which to measure distance <add> * @param {boolean} [intersect] - if true, only consider items that intersect the position <ide> * @return {ChartElement[]} the nearest items <ide> */ <ide> function getNearestItems(chart, position, axis, intersect) { <ide><path>src/core/core.scale.js <ide> class Scale extends Element { <ide> * Get the padding needed for the scale <ide> * @method getPadding <ide> * @private <del> * @returns {Padding} the necessary padding <add> * @returns {object} the necessary padding <ide> */ <ide> getPadding() { <ide> const me = this; <ide> class Scale extends Element { <ide> beforeBuildTicks() { <ide> call(this.options.beforeBuildTicks, [this]); <ide> } <add> /** <add> * @return {object[]} the ticks <add> */ <ide> buildTicks() {} <ide> afterBuildTicks() { <ide> call(this.options.afterBuildTicks, [this]); <ide> class Scale extends Element { <ide> * Returns the location of the given data point. Value can either be an index or a numerical value <ide> * The coordinate (0, 0) is at the upper-left corner of the canvas <ide> * @param value <del> * @param index <del> * @param datasetIndex <ide> */ <del> getPixelForValue() {} <add> getPixelForValue(value) {} // eslint-disable-line no-unused-vars <ide> <ide> /** <ide> * Used to get the data value from a given pixel. This is the inverse of getPixelForValue <ide> * The coordinate (0, 0) is at the upper-left corner of the canvas <ide> * @param pixel <ide> */ <del> getValueForPixel() {} <add> getValueForPixel(pixel) {} // eslint-disable-line no-unused-vars <ide> <ide> /** <ide> * Returns the location of the tick at the given index <ide><path>src/helpers/helpers.dom.js <ide> function parseMaxStyle(styleValue, node, parentProperty) { <ide> * @param {HTMLElement} domNode - the node to check the constraint on <ide> * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height') <ide> * @param {string} percentageProperty - property of parent to use when calculating width as a percentage <add> * @return {number|undefined} number or undefined if no constraint <ide> * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser} <ide> */ <ide> function getConstraintDimension(domNode, maxStyle, percentageProperty) { <ide> function getConstraintDimension(domNode, maxStyle, percentageProperty) { <ide> hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity, <ide> hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity); <ide> } <del> <del> return 'none'; <ide> } <ide> <ide> export function getStyle(el, property) { <ide> export function getStyle(el, property) { <ide> document.defaultView.getComputedStyle(el, null).getPropertyValue(property); <ide> } <ide> <del>// returns Number or undefined if no constraint <add>/** @return {number|undefined} number or undefined if no constraint */ <ide> function getConstraintWidth(domNode) { <ide> return getConstraintDimension(domNode, 'max-width', 'clientWidth'); <ide> } <ide> <del>// returns Number or undefined if no constraint <add>/** @return {number|undefined} number or undefined if no constraint */ <ide> function getConstraintHeight(domNode) { <ide> return getConstraintDimension(domNode, 'max-height', 'clientHeight'); <ide> } <ide><path>src/platform/platform.base.js <ide> export default class BasePlatform { <ide> * @param {object} options - The chart options <ide> * @returns {CanvasRenderingContext2D} context2d instance <ide> */ <del> acquireContext() {} <add> acquireContext(canvas, options) {} // eslint-disable-line no-unused-vars <ide> <ide> /** <ide> * Called at chart destruction time, releases any resources associated to the context <ide> * previously returned by the acquireContext() method. <ide> * @param {CanvasRenderingContext2D} context - The context2d instance <ide> * @returns {boolean} true if the method succeeded, else false <ide> */ <del> releaseContext() {} <add> releaseContext(context) {} // eslint-disable-line no-unused-vars <ide> <ide> /** <ide> * Registers the specified listener on the given chart. <ide> export default class BasePlatform { <ide> * @param {function} listener - Receives a notification (an object that implements <ide> * the {@link IEvent} interface) when an event of the specified type occurs. <ide> */ <del> addEventListener() {} <add> addEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars <ide> <ide> /** <ide> * Removes the specified listener previously registered with addEventListener. <ide> * @param {Chart} chart - Chart from which to remove the listener <ide> * @param {string} type - The ({@link IEvent}) type to remove <ide> * @param {function} listener - The listener function to remove from the event target. <ide> */ <del> removeEventListener() {} <add> removeEventListener(chart, type, listener) {} // eslint-disable-line no-unused-vars <ide> <ide> /** <ide> * @returns {number} the current devicePixelRatio of the device this platform is connected to. <ide><path>src/plugins/plugin.filler.js <ide> function parseFillOption(line) { <ide> // @todo if (fill[0] === '#') <ide> function decodeFill(line, index, count) { <ide> const fill = parseFillOption(line); <del> let target = parseFloat(fill, 10); <add> let target = parseFloat(fill); <ide> <ide> if (isFinite(target) && Math.floor(target) === target) { <ide> if (fill[0] === '-' || fill[0] === '+') { <ide><path>src/plugins/plugin.legend.js <ide> defaults._set('legend', { <ide> <ide> /** <ide> * Helper function to get the box width based on the usePointStyle option <del> * @param {object} labelopts - the label options on the legend <add> * @param {object} labelOpts - the label options on the legend <ide> * @param {number} fontSize - the label font size <ide> * @return {number} width of the color box area <ide> */ <ide> class Legend extends Element { <ide> <ide> /** <ide> * Handle an event <add> * @param {IEvent} e - The event to handle <ide> * @private <del> * @param {IEvent} event - The event to handle <ide> */ <ide> handleEvent(e) { <ide> var me = this; <ide><path>src/plugins/plugin.tooltip.js <ide> function pushOrConcat(base, toPush) { <ide> <ide> /** <ide> * Returns array of strings split by newline <del> * @param {string} value - The value to split by newline. <add> * @param {string} str - The value to split by newline. <ide> * @returns {string[]} value if newline present - Returned from String split() method <ide> * @function <ide> */ <ide> class Tooltip extends Element { <ide> /** <ide> * Handle an event <ide> * @private <del> * @param {IEvent} event - The event to handle <add> * @param {IEvent} e - The event to handle <ide> * @returns {boolean} true if the tooltip changed <ide> */ <ide> handleEvent(e) { <ide><path>src/scales/scale.linearbase.js <ide> function niceNum(range, round) { <ide> * Generate a set of linear ticks <ide> * @param generationOptions the options used to generate the ticks <ide> * @param dataRange the range of the data <del> * @returns {number[]} array of tick values <add> * @returns {object[]} array of tick objects <ide> */ <ide> function generateTicks(generationOptions, dataRange) { <ide> const ticks = []; <ide><path>src/scales/scale.logarithmic.js <ide> function finiteOrDefault(value, def) { <ide> * Generate a set of logarithmic ticks <ide> * @param generationOptions the options used to generate the ticks <ide> * @param dataRange the range of the data <del> * @returns {number[]} array of tick values <add> * @returns {object[]} array of tick objects <ide> */ <ide> function generateTicks(generationOptions, dataRange) { <ide> const endExp = Math.floor(log10(dataRange.max)); <ide><path>src/scales/scale.time.js <ide> function getLabelBounds(scale) { <ide> /** <ide> * Return subset of `timestamps` between `min` and `max`. <ide> * Timestamps are assumend to be in sorted order. <del> * @param {int[]} timestamps - array of timestamps <del> * @param {int} min - min value (timestamp) <del> * @param {int} max - max value (timestamp) <add> * @param {number[]} timestamps - array of timestamps <add> * @param {number} min - min value (timestamp) <add> * @param {number} max - max value (timestamp) <ide> */ <ide> function filterBetween(timestamps, min, max) { <ide> let start = 0;
12
Go
Go
move stack dump dir to exec root
0bd720b28dc7b416fe2193bdafaca011ec24d032
<ide><path>daemon/daemon.go <ide> func NewDaemon(config *Config, registryService registry.Service, containerdRemot <ide> <ide> // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event <ide> // on Windows to dump Go routine stacks <del> d.setupDumpStackTrap(config.Root) <add> stackDumpDir := config.Root <add> if execRoot := config.GetExecRoot(); execRoot != "" { <add> stackDumpDir = execRoot <add> } <add> d.setupDumpStackTrap(stackDumpDir) <ide> <ide> return d, nil <ide> } <ide><path>pkg/signal/trap.go <ide> func DumpStacks(dir string) (string, error) { <ide> bufferLen *= 2 <ide> } <ide> buf = buf[:stackSize] <del> path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.Replace(time.Now().Format(time.RFC3339), ":", "", -1))) <del> f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666) <del> if err != nil { <del> return "", errors.Wrap(err, "failed to open file to write the goroutine stacks") <add> var f *os.File <add> if dir != "" { <add> path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.Replace(time.Now().Format(time.RFC3339), ":", "", -1))) <add> var err error <add> f, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666) <add> if err != nil { <add> return "", errors.Wrap(err, "failed to open file to write the goroutine stacks") <add> } <add> defer f.Close() <add> defer f.Sync() <add> } else { <add> f = os.Stderr <ide> } <del> defer f.Close() <ide> if _, err := f.Write(buf); err != nil { <ide> return "", errors.Wrap(err, "failed to write goroutine stacks") <ide> } <del> f.Sync() <del> return path, nil <add> return f.Name(), nil <ide> }
2
Ruby
Ruby
replace perl shebangs
ae49b0660052e88e53ebffc6e33dd48052d7cc2f
<ide><path>Library/Homebrew/extend/os/linux/keg_relocate.rb <ide> def relocate_dynamic_linkage(relocation) <ide> # Patching patchelf using itself fails with "Text file busy" or SIGBUS. <ide> return if name == "patchelf" <ide> <add> old_prefix, new_prefix = relocation.replacement_pair_for(:prefix) <add> <ide> elf_files.each do |file| <ide> file.ensure_writable do <del> change_rpath(file, relocation.old_prefix, relocation.new_prefix) <add> change_rpath(file, old_prefix, new_prefix) <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/extend/os/mac/keg_relocate.rb <ide> def file_linked_libraries(file, string) <ide> undef relocate_dynamic_linkage <ide> <ide> def relocate_dynamic_linkage(relocation) <add> old_prefix, new_prefix = relocation.replacement_pair_for(:prefix) <add> old_cellar, new_cellar = relocation.replacement_pair_for(:cellar) <add> <ide> mach_o_files.each do |file| <ide> file.ensure_writable do <ide> if file.dylib? <del> id = dylib_id_for(file).sub(relocation.old_prefix, relocation.new_prefix) <add> id = dylib_id_for(file).sub(old_prefix, new_prefix) <ide> change_dylib_id(id, file) <ide> end <ide> <ide> each_install_name_for(file) do |old_name| <del> if old_name.start_with? relocation.old_cellar <del> new_name = old_name.sub(relocation.old_cellar, relocation.new_cellar) <del> elsif old_name.start_with? relocation.old_prefix <del> new_name = old_name.sub(relocation.old_prefix, relocation.new_prefix) <add> if old_name.start_with? old_cellar <add> new_name = old_name.sub(old_cellar, new_cellar) <add> elsif old_name.start_with? old_prefix <add> new_name = old_name.sub(old_prefix, new_prefix) <ide> end <ide> <ide> change_install_name(old_name, new_name, file) if new_name <ide> end <ide> <ide> if ENV["HOMEBREW_RELOCATE_RPATHS"] <ide> each_rpath_for(file) do |old_name| <del> new_name = if old_name.start_with? relocation.old_cellar <del> old_name.sub(relocation.old_cellar, relocation.new_cellar) <del> elsif old_name.start_with? relocation.old_prefix <del> old_name.sub(relocation.old_prefix, relocation.new_prefix) <add> new_name = if old_name.start_with? old_cellar <add> old_name.sub(old_cellar, new_cellar) <add> elsif old_name.start_with? old_prefix <add> old_name.sub(old_prefix, new_prefix) <ide> end <ide> <ide> change_rpath(old_name, new_name, file) if new_name <ide> def mach_o_files <ide> mach_o_files <ide> end <ide> <add> def prepare_relocation_to_locations <add> relocation = generic_prepare_relocation_to_locations <add> <add> brewed_perl = runtime_dependencies&.any? { |dep| dep["full_name"] == "perl" && dep["declared_directly"] } <add> perl_path = if brewed_perl <add> "#{HOMEBREW_PREFIX}/opt/perl/bin/perl" <add> else <add> perl_version = if tab["built_on"].present? <add> tab["built_on"]["preferred_perl"] <add> else <add> MacOS.preferred_perl_version <add> end <add> "/usr/bin/perl#{perl_version}" <add> end <add> relocation.add_replacement_pair(:perl, PERL_PLACEHOLDER, perl_path) <add> <add> relocation <add> end <add> <ide> def recursive_fgrep_args <ide> # Don't recurse into symlinks; the man page says this is the default, but <ide> # it's wrong. -O is a BSD-grep-only option. <ide><path>Library/Homebrew/keg_relocate.rb <ide> class Keg <ide> CELLAR_PLACEHOLDER = "" <ide> REPOSITORY_PLACEHOLDER = "" <ide> LIBRARY_PLACEHOLDER = "" <add> PERL_PLACEHOLDER = "" <ide> <del> Relocation = Struct.new(:old_prefix, :old_cellar, :old_repository, :old_library, <del> :new_prefix, :new_cellar, :new_repository, :new_library) do <del> # Use keyword args instead of positional args for initialization. <del> def initialize(**kwargs) <del> super(*members.map { |k| kwargs[k] }) <add> class Relocation <add> extend T::Sig <add> <add> def initialize <add> @replacement_map = {} <add> end <add> <add> def freeze <add> @replacement_map.freeze <add> super <add> end <add> <add> sig { params(key: Symbol, old_value: T.any(String, Regexp), new_value: String).void } <add> def add_replacement_pair(key, old_value, new_value) <add> @replacement_map[key] = [old_value, new_value] <add> end <add> <add> sig { params(key: Symbol).returns(T::Array[T.any(String, Regexp)]) } <add> def replacement_pair_for(key) <add> @replacement_map.fetch(key) <add> end <add> <add> sig { params(text: String).void } <add> def replace_text(text) <add> replacements = @replacement_map.values.to_h <add> <add> sorted_keys = replacements.keys.sort_by do |key| <add> key.is_a?(String) ? key.length : 999 <add> end.reverse <add> <add> any_changed = false <add> sorted_keys.each do |key| <add> changed = text.gsub!(key, replacements[key]) <add> any_changed ||= changed <add> end <add> any_changed <ide> end <ide> end <ide> <ide> def relocate_dynamic_linkage(_relocation) <ide> [] <ide> end <ide> <add> def prepare_relocation_to_placeholders <add> relocation = Relocation.new <add> relocation.add_replacement_pair(:prefix, HOMEBREW_PREFIX.to_s, PREFIX_PLACEHOLDER) <add> relocation.add_replacement_pair(:cellar, HOMEBREW_CELLAR.to_s, CELLAR_PLACEHOLDER) <add> # when HOMEBREW_PREFIX == HOMEBREW_REPOSITORY we should use HOMEBREW_PREFIX for all relocations to avoid <add> # being unable to differentiate between them. <add> if HOMEBREW_PREFIX != HOMEBREW_REPOSITORY <add> relocation.add_replacement_pair(:repository, HOMEBREW_REPOSITORY.to_s, REPOSITORY_PLACEHOLDER) <add> end <add> relocation.add_replacement_pair(:library, HOMEBREW_LIBRARY.to_s, LIBRARY_PLACEHOLDER) <add> relocation.add_replacement_pair(:perl, <add> %r{\A#!(/usr/bin/perl\d\.\d+|#{HOMEBREW_PREFIX}/opt/perl/bin/perl)$}o, <add> "#!#{PERL_PLACEHOLDER}") <add> relocation <add> end <add> alias generic_prepare_relocation_to_placeholders prepare_relocation_to_placeholders <add> <ide> def replace_locations_with_placeholders <del> relocation = Relocation.new( <del> old_prefix: HOMEBREW_PREFIX.to_s, <del> old_cellar: HOMEBREW_CELLAR.to_s, <del> new_prefix: PREFIX_PLACEHOLDER, <del> new_cellar: CELLAR_PLACEHOLDER, <del> old_repository: HOMEBREW_REPOSITORY.to_s, <del> new_repository: REPOSITORY_PLACEHOLDER, <del> old_library: HOMEBREW_LIBRARY.to_s, <del> new_library: LIBRARY_PLACEHOLDER, <del> ) <add> relocation = prepare_relocation_to_placeholders.freeze <ide> relocate_dynamic_linkage(relocation) <ide> replace_text_in_files(relocation) <ide> end <ide> <add> def prepare_relocation_to_locations <add> relocation = Relocation.new <add> relocation.add_replacement_pair(:prefix, PREFIX_PLACEHOLDER, HOMEBREW_PREFIX.to_s) <add> relocation.add_replacement_pair(:cellar, CELLAR_PLACEHOLDER, HOMEBREW_CELLAR.to_s) <add> relocation.add_replacement_pair(:repository, REPOSITORY_PLACEHOLDER, HOMEBREW_REPOSITORY.to_s) <add> relocation.add_replacement_pair(:library, LIBRARY_PLACEHOLDER, HOMEBREW_LIBRARY.to_s) <add> relocation.add_replacement_pair(:perl, PERL_PLACEHOLDER, "#{HOMEBREW_PREFIX}/opt/perl/bin/perl") <add> relocation <add> end <add> alias generic_prepare_relocation_to_locations prepare_relocation_to_locations <add> <ide> def replace_placeholders_with_locations(files, skip_linkage: false) <del> relocation = Relocation.new( <del> old_prefix: PREFIX_PLACEHOLDER, <del> old_cellar: CELLAR_PLACEHOLDER, <del> old_repository: REPOSITORY_PLACEHOLDER, <del> old_library: LIBRARY_PLACEHOLDER, <del> new_prefix: HOMEBREW_PREFIX.to_s, <del> new_cellar: HOMEBREW_CELLAR.to_s, <del> new_repository: HOMEBREW_REPOSITORY.to_s, <del> new_library: HOMEBREW_LIBRARY.to_s, <del> ) <add> relocation = prepare_relocation_to_locations.freeze <ide> relocate_dynamic_linkage(relocation) unless skip_linkage <ide> replace_text_in_files(relocation, files: files) <ide> end <ide> def replace_text_in_files(relocation, files: nil) <ide> files.map(&path.method(:join)).group_by { |f| f.stat.ino }.each_value do |first, *rest| <ide> s = first.open("rb", &:read) <ide> <del> replacements = { <del> relocation.old_prefix => relocation.new_prefix, <del> relocation.old_cellar => relocation.new_cellar, <del> relocation.old_library => relocation.new_library, <del> }.compact <del> # when HOMEBREW_PREFIX == HOMEBREW_REPOSITORY we should use HOMEBREW_PREFIX for all relocations to avoid <del> # being unable to differentiate between them. <del> replacements[relocation.old_repository] = relocation.new_repository if HOMEBREW_PREFIX != HOMEBREW_REPOSITORY <del> changed = s.gsub!(Regexp.union(replacements.keys.sort_by(&:length).reverse), replacements) <del> next unless changed <add> next unless relocation.replace_text(s) <ide> <ide> changed_files += [first, *rest].map { |file| file.relative_path_from(path) } <ide>
3
Mixed
Javascript
remove duplicate error definition
e9358af5818d87ebedf5bf1eab1ec7972041bfea
<ide><path>doc/api/errors.md <ide> Used when an attempt is made to launch a Node.js process with an unknown <ide> by errors in user code, although it is not impossible. Occurrences of this error <ide> are most likely an indication of a bug within Node.js itself. <ide> <del><a id="ERR_VALUE_OUT_OF_RANGE"></a> <del>### ERR_VALUE_OUT_OF_RANGE <del> <del>Used when a number value is out of range. <del> <ide> <a id="ERR_V8BREAKITERATOR"></a> <ide> ### ERR_V8BREAKITERATOR <ide> <ide><path>lib/internal/errors.js <del>/* eslint-enable alphabetize-errors */ <add>/* eslint alphabetize-errors: "error" */ <ide> <ide> 'use strict'; <ide> <ide> E('ERR_REQUIRE_ESM', 'Must use import to load ES Module: %s'); <ide> E('ERR_SERVER_ALREADY_LISTEN', <ide> 'Listen method has been called more than once without closing.'); <ide> E('ERR_SOCKET_ALREADY_BOUND', 'Socket is already bound'); <del>E('ERR_SOCKET_BAD_PORT', 'Port should be > 0 and < 65536'); <ide> E('ERR_SOCKET_BAD_BUFFER_SIZE', 'Buffer size must be a positive integer'); <add>E('ERR_SOCKET_BAD_PORT', 'Port should be > 0 and < 65536'); <ide> E('ERR_SOCKET_BAD_TYPE', <ide> 'Bad socket type specified. Valid types are: udp4, udp6'); <add>E('ERR_SOCKET_BUFFER_SIZE', <add> (reason) => `Could not get or set buffer size: ${reason}`); <ide> E('ERR_SOCKET_CANNOT_SEND', 'Unable to send data'); <ide> E('ERR_SOCKET_CLOSED', 'Socket is closed'); <ide> E('ERR_SOCKET_DGRAM_NOT_RUNNING', 'Not running'); <del>E('ERR_SOCKET_BUFFER_SIZE', <del> (reason) => `Could not get or set buffer size: ${reason}`); <ide> E('ERR_STDERR_CLOSE', 'process.stderr cannot be closed'); <ide> E('ERR_STDOUT_CLOSE', 'process.stdout cannot be closed'); <ide> E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode'); <ide> E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s'); <ide> E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s'); <ide> E('ERR_UNKNOWN_STDIN_TYPE', 'Unknown stdin file type'); <ide> E('ERR_UNKNOWN_STREAM_TYPE', 'Unknown stream file type'); <add>E('ERR_V8BREAKITERATOR', 'Full ICU data not installed. ' + <add> 'See https://github.com/nodejs/node/wiki/Intl'); <add>E('ERR_VALID_PERFORMANCE_ENTRY_TYPE', <add> 'At least one valid performance entry type is required'); <ide> E('ERR_VALUE_OUT_OF_RANGE', (start, end, value) => { <ide> return `The value of "${start}" must be ${end}. Received "${value}"`; <ide> }); <del>E('ERR_VALID_PERFORMANCE_ENTRY_TYPE', <del> 'At least one valid performance entry type is required'); <del>E('ERR_VALUE_OUT_OF_RANGE', 'The value of "%s" must be %s. Received "%s"'); <ide> <ide> function invalidArgType(name, expected, actual) { <ide> internalAssert(name, 'name is required');
2
Ruby
Ruby
remove table quoting in primary_key method
1d7c751bf703c729887e2d8a9ae104a8e6aef010
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def pk_and_sequence_for(table) #:nodoc: <ide> <ide> # Returns just a table's primary key <ide> def primary_key(table) <del> row = exec_query(<<-end_sql, 'SCHEMA', [[nil, quote_table_name(table)]]).rows.first <add> row = exec_query(<<-end_sql, 'SCHEMA', [[nil, table]]).rows.first <ide> SELECT DISTINCT(attr.attname) <ide> FROM pg_attribute attr <ide> INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid <ide><path>activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb <ide> def test_default_sequence_name_bad_table <ide> @connection.default_sequence_name('zomg') <ide> end <ide> <add> def test_pk_and_sequence_for <add> pk, seq = @connection.pk_and_sequence_for('ex') <add> assert_equal 'id', pk <add> assert_equal @connection.default_sequence_name('ex', 'id'), seq <add> end <add> <add> def test_pk_and_sequence_for_with_non_standard_primary_key <add> @connection.exec_query('drop table if exists ex') <add> @connection.exec_query('create table ex(code serial primary key)') <add> pk, seq = @connection.pk_and_sequence_for('ex') <add> assert_equal 'code', pk <add> assert_equal @connection.default_sequence_name('ex', 'code'), seq <add> end <add> <add> def test_pk_and_sequence_for_returns_nil_if_no_seq <add> @connection.exec_query('drop table if exists ex') <add> @connection.exec_query('create table ex(id integer primary key)') <add> assert_nil @connection.pk_and_sequence_for('ex') <add> end <add> <add> def test_pk_and_sequence_for_returns_nil_if_no_pk <add> @connection.exec_query('drop table if exists ex') <add> @connection.exec_query('create table ex(id integer)') <add> assert_nil @connection.pk_and_sequence_for('ex') <add> end <add> <add> def test_pk_and_sequence_for_returns_nil_if_table_not_found <add> assert_nil @connection.pk_and_sequence_for('unobtainium') <add> end <add> <ide> def test_exec_insert_number <ide> insert(@connection, 'number' => 10) <ide> <ide><path>activerecord/test/cases/adapters/postgresql/schema_test.rb <ide> class Thing4 < ActiveRecord::Base <ide> set_table_name 'test_schema."Things"' <ide> end <ide> <del> class PrimaryKeyTestHarness < ActiveRecord::Base <del> set_table_name 'test_schema.pktest' <del> end <del> <ide> def setup <ide> @connection = ActiveRecord::Base.connection <ide> @connection.execute "CREATE SCHEMA #{SCHEMA_NAME} CREATE TABLE #{TABLE_NAME} (#{COLUMNS.join(',')})" <ide> def test_with_uppercase_index_name <ide> end <ide> <ide> def test_primary_key_with_schema_specified <del> [ %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}"), %(#{SCHEMA_NAME}."#{PK_TABLE_NAME}"), %(#{SCHEMA_NAME}."#{PK_TABLE_NAME}")].each do |given| <add> [ <add> %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}"), <add> %(#{SCHEMA_NAME}."#{PK_TABLE_NAME}"), <add> %(#{SCHEMA_NAME}.#{PK_TABLE_NAME}) <add> ].each do |given| <ide> assert_equal 'id', @connection.primary_key(given), "primary key should be found when table referenced as #{given}" <ide> end <ide> end <ide> def test_primary_key_raises_error_if_table_not_found_on_schema_search_path <ide> end <ide> end <ide> <add> def test_pk_and_sequence_for_with_schema_specified <add> [ <add> %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}"), <add> %(#{SCHEMA_NAME}."#{PK_TABLE_NAME}"), <add> %(#{SCHEMA_NAME}.#{PK_TABLE_NAME}) <add> ].each do |given| <add> pk, seq = @connection.pk_and_sequence_for(given) <add> assert_equal 'id', pk, "primary key should be found when table referenced as #{given}" <add> assert_equal "#{SCHEMA_NAME}.#{PK_TABLE_NAME}_id_seq", seq, "sequence name should be found when table referenced as #{given}" <add> end <add> end <add> <ide> def test_extract_schema_and_table <ide> { <ide> %(table_name) => [nil,'table_name'],
3
Text
Text
fix token api docs from
a2345618f111552e141e128e1d48dd1d0a672a6b
<ide><path>website/docs/api/token.md <ide> property to `0` for the first word of the document. <ide> - assert doc[4].sent_start == 1 <ide> + assert doc[4].is_sent_start == True <ide> ``` <add></Infobox> <ide> <ide> ## Token.is_sent_end {#is_sent_end tag="property" new="2"} <ide>
1
Text
Text
update nested serialization docs
7815811fe3047b5110e6993ecd72349f6f232232
<ide><path>docs/api-guide/relations.md <ide> Nested relationships can be expressed by using serializers as fields. <ide> <ide> If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field. <ide> <del>Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style. <del> <ide> ## Example <ide> <ide> For example, the following serializer: <ide><path>docs/api-guide/serializers.md <ide> If a nested representation may optionally accept the `None` value you should pas <ide> content = serializers.CharField(max_length=200) <ide> created = serializers.DateTimeField() <ide> <del>Similarly if a nested representation should be a list of items, you should the `many=True` flag to the nested serialized. <add>Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serialized. <ide> <ide> class CommentSerializer(serializers.Serializer): <ide> user = UserSerializer(required=False) <ide> edits = EditItemSerializer(many=True) # A nested list of 'edit' items. <ide> content = serializers.CharField(max_length=200) <ide> created = serializers.DateTimeField() <ide> <del>--- <del> <del>**Note**: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the `RelatedField` subclasses. <add>Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object. <ide> <del>--- <add> serializer = CommentSerializer(comment, data={'user': {'email': 'foobar', 'user': 'doe'}, 'content': 'baz'}) <add> serializer.is_valid() <add> # False <add> serializer.errors <add> # {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']} <ide> <ide> ## Dealing with multiple objects <ide> <ide> You can provide arbitrary additional context by passing a `context` argument whe <ide> <ide> The context dictionary can be used within any serializer field logic, such as a custom `.to_native()` method, by accessing the `self.context` attribute. <ide> <del>--- <del> <add>- <ide> # ModelSerializer <ide> <ide> Often you'll want serializer classes that map closely to model definitions. <ide> The default `ModelSerializer` uses primary keys for relationships, but you can a <ide> <ide> The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. <ide> <add>If you want to customize the way the serialization is done (e.g. using `allow_add_remove`) you'll need to define the field yourself. <add> <ide> ## Specifying which fields should be read-only <ide> <ide> You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so:
2
Javascript
Javascript
remove bad stats merge
225994b607b753b08dc9845db5a9779f419dcd48
<ide><path>lib/Stats.js <ide> class Stats { <ide> errors: false, <ide> errorDetails: false, <ide> warnings: false, <del> publicPath: false <add> publicPath: false, <add> performance: false <ide> }; <ide> } else { <ide> return { <ide> class Stats { <ide> depth: pn === "verbose", <ide> usedExports: pn === "verbose", <ide> providedExports: pn === "verbose", <del> colors: true <add> colors: true, <add> performance: true <ide> }; <ide> } <ide>
1
Javascript
Javascript
remove jquery metadata
9124a9a5510a66826b18f0f618a5df9038e65a6f
<ide><path>actionview/test/ujs/public/vendor/jquery.metadata.js <del>/* <del> * Metadata - jQuery plugin for parsing metadata from elements <del> * <del> * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan <del> * <del> * Dual licensed under the MIT and GPL licenses: <del> * http://www.opensource.org/licenses/mit-license.php <del> * http://www.gnu.org/licenses/gpl.html <del> * <del> * Revision: $Id: jquery.metadata.js 4187 2007-12-16 17:15:27Z joern.zaefferer $ <del> * <del> */ <del> <del>/** <del> * Sets the type of metadata to use. Metadata is encoded in JSON, and each property <del> * in the JSON will become a property of the element itself. <del> * <del> * There are three supported types of metadata storage: <del> * <del> * attr: Inside an attribute. The name parameter indicates *which* attribute. <del> * <del> * class: Inside the class attribute, wrapped in curly braces: { } <del> * <del> * elem: Inside a child element (e.g. a script tag). The <del> * name parameter indicates *which* element. <del> * <del> * The metadata for an element is loaded the first time the element is accessed via jQuery. <del> * <del> * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements <del> * matched by expr, then redefine the metadata type and run another $(expr) for other elements. <del> * <del> * @name $.metadata.setType <del> * <del> * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p> <del> * @before $.metadata.setType("class") <del> * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" <del> * @desc Reads metadata from the class attribute <del> * <del> * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p> <del> * @before $.metadata.setType("attr", "data") <del> * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" <del> * @desc Reads metadata from a "data" attribute <del> * <del> * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p> <del> * @before $.metadata.setType("elem", "script") <del> * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" <del> * @desc Reads metadata from a nested script element <del> * <del> * @param String type The encoding type <del> * @param String name The name of the attribute to be used to get metadata (optional) <del> * @cat Plugins/Metadata <del> * @descr Sets the type of encoding to be used when loading metadata for the first time <del> * @type undefined <del> * @see metadata() <del> */ <del> <del>(function($) { <del> <del>$.extend({ <del> metadata : { <del> defaults : { <del> type: 'class', <del> name: 'metadata', <del> cre: /({.*})/, <del> single: 'metadata' <del> }, <del> setType: function( type, name ){ <del> this.defaults.type = type; <del> this.defaults.name = name; <del> }, <del> get: function( elem, opts ){ <del> var settings = $.extend({},this.defaults,opts); <del> // check for empty string in single property <del> if ( !settings.single.length ) settings.single = 'metadata'; <del> <del> var data = $.data(elem, settings.single); <del> // returned cached data if it already exists <del> if ( data ) return data; <del> <del> data = "{}"; <del> <del> if ( settings.type == "class" ) { <del> var m = settings.cre.exec( elem.className ); <del> if ( m ) <del> data = m[1]; <del> } else if ( settings.type == "elem" ) { <del> if( !elem.getElementsByTagName ) <del> return undefined; <del> var e = elem.getElementsByTagName(settings.name); <del> if ( e.length ) <del> data = $.trim(e[0].innerHTML); <del> } else if ( elem.getAttribute != undefined ) { <del> var attr = elem.getAttribute( settings.name ); <del> if ( attr ) <del> data = attr; <del> } <del> <del> if ( data.indexOf( '{' ) <0 ) <del> data = "{" + data + "}"; <del> <del> data = eval("(" + data + ")"); <del> <del> $.data( elem, settings.single, data ); <del> return data; <del> } <del> } <del>}); <del> <del>/** <del> * Returns the metadata object for the first member of the jQuery object. <del> * <del> * @name metadata <del> * @descr Returns element's metadata object <del> * @param Object opts An object containing settings to override the defaults <del> * @type jQuery <del> * @cat Plugins/Metadata <del> */ <del>$.fn.metadata = function( opts ){ <del> return $.metadata.get( this[0], opts ); <del>}; <del> <del>})(jQuery); <ide>\ No newline at end of file
1
Java
Java
implement sessionfactoryimplementor in sf proxies
5aa24af1269bf0ac9691afc63da6f6051543ad6a
<ide><path>org.springframework.integration-tests/src/test/java/org/springframework/orm/hibernate3/HibernateSessionFactoryConfigurationTests.java <ide> import org.hibernate.Transaction; <ide> import org.hibernate.cfg.AnnotationConfiguration; <ide> import org.hibernate.classic.Session; <add>import org.hibernate.engine.SessionFactoryImplementor; <ide> import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.springframework.beans.factory.BeanCreationException; <ide> public void usingSessionFactoryBuilder_withLateCustomConfigurationClass() throws <ide> } <ide> <ide> @Test <del> public void builtSessionFactoryIsDisposableBeanProxy() { <add> public void builtSessionFactoryIsProxyImplementingDisposableBeanAndSessionFactoryImplementor() { <ide> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AnnotationSessionFactoryConfig.class); <ide> SessionFactory sessionFactory = ctx.getBean(SessionFactory.class); <ide> assertThat(sessionFactory, instanceOf(DisposableBean.class)); <add> assertThat(sessionFactory, instanceOf(SessionFactoryImplementor.class)); <ide> assertThat(sessionFactory.toString(), startsWith("DisposableBean proxy for SessionFactory")); <ide> ctx.close(); <ide> assertTrue("SessionFactory was not closed as expected", sessionFactory.isClosed()); <ide><path>org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryBuilderSupport.java <ide> public SessionFactoryBuilderSupport(DataSource dataSource) { <ide> <ide> /** <ide> * Build the underlying Hibernate SessionFactory. <del> * @return the raw SessionFactory (potentially to be wrapped with a <del> * transaction-aware proxy before it is exposed to the application) <add> * @return the {@code SessionFactory}, potentially wrapped as a <add> * {@code DisposableBean} and/or transaction-aware proxy before it is exposed to the <add> * application. <ide> * @throws Exception in case of initialization failure <ide> */ <ide> public SessionFactory buildSessionFactory() throws Exception { <ide> public SessionFactory buildSessionFactory() throws Exception { <ide> <ide> /** <ide> * Populate the underlying {@code Configuration} instance with the various <del> * properties of this builder. Customization may be performed through <del> * {@code pre*} and {@code post*} methods. <add> * properties of this builder, then return the raw session factory resulting from <add> * calling {@link Configuration#buildSessionFactory()}. Customization may be performed <add> * through {@code pre*} and {@code post*} methods. <ide> * @see #preBuildSessionFactory() <ide> * @see #postProcessMappings() <ide> * @see #postBuildSessionFactory() <ide> protected void postBuildSessionFactory() { <ide> * <p>Subclasses may override this to implement transaction awareness through <ide> * a {@code SessionFactory} proxy for example, or even to avoid creation of the <ide> * {@code DisposableBean} proxy altogether. <del> * @param rawSf the raw {@code SessionFactory} as built by {@link #buildSessionFactory()} <del> * @return the {@code SessionFactory} reference to expose <add> * @param rawSf the raw {@code SessionFactory} as built by {@link #doBuildSessionFactory()} <add> * @return a proxied {@code SessionFactory} if wrapping was necessary, otherwise the <add> * original given 'raw' {@code SessionFactory} object. <ide> * @see #buildSessionFactory() <ide> */ <ide> protected SessionFactory wrapSessionFactoryIfNecessary(final SessionFactory rawSf) { <ide> return (SessionFactory) Proxy.newProxyInstance( <ide> this.beanClassLoader, <ide> new Class<?>[] { <ide> SessionFactory.class, <add> SessionFactoryImplementor.class, <ide> DisposableBean.class <ide> }, <ide> new InvocationHandler() {
2
Ruby
Ruby
stream blobs from disk
847342c25c61acaea988430dc3ab66a82e3ed486
<ide><path>activestorage/app/controllers/active_storage/disk_controller.rb <ide> # Always go through the BlobsController, or your own authenticated controller, rather than directly <ide> # to the service url. <ide> class ActiveStorage::DiskController < ActiveStorage::BaseController <add> include ActionController::Live <add> <ide> skip_forgery_protection <ide> <ide> def show <ide> if key = decode_verified_key <del> send_data disk_service.download(key), <del> disposition: params[:disposition], content_type: params[:content_type] <add> response.headers["Content-Type"] = params[:content_type] || DEFAULT_SEND_FILE_TYPE <add> response.headers["Content-Disposition"] = params[:disposition] || DEFAULT_SEND_FILE_DISPOSITION <add> <add> disk_service.download key do |chunk| <add> response.stream.write chunk <add> end <ide> else <ide> head :not_found <ide> end <add> ensure <add> response.stream.close <ide> end <ide> <ide> def update <ide> if token = decode_verified_token <ide> if acceptable_content?(token) <ide> disk_service.upload token[:key], request.body, checksum: token[:checksum] <add> head :no_content <ide> else <ide> head :unprocessable_entity <ide> end <ide> def update <ide> end <ide> rescue ActiveStorage::IntegrityError <ide> head :unprocessable_entity <add> ensure <add> response.stream.close <ide> end <ide> <ide> private
1
Javascript
Javascript
avoid shader duplication
78a25d5a88d4034ea8d39f7c158fcc54695f9110
<ide><path>examples/jsm/csm/CSM.js <ide> export default class CSM { <ide> this.breaks = []; <ide> <ide> this.lights = []; <del> this.shaders = []; <del> this.materials = []; <add> this.shaders = new Map(); <ide> this.createLights(); <ide> <ide> this.getBreaks(); <ide> export default class CSM { <ide> const breaksVec2 = []; <ide> this.getExtendedBreaks( breaksVec2 ); <ide> <del> const self = this; <ide> const far = Math.min( this.camera.far, this.maxFar ); <add> const shaders = this.shaders; <add> const camera = this.camera; <ide> <ide> material.onBeforeCompile = function ( shader ) { <ide> <ide> shader.uniforms.CSM_cascades = { value: breaksVec2 }; <del> shader.uniforms.cameraNear = { value: self.camera.near }; <add> shader.uniforms.cameraNear = { value: camera.near }; <ide> shader.uniforms.shadowFar = { value: far }; <ide> <del> self.shaders.push( shader ); <add> shaders.set( material, shader ); <ide> <ide> }; <del> this.materials.push( material ); <add> shaders.set( material, null ); <ide> <ide> } <ide> <ide> updateUniforms() { <ide> <ide> const far = Math.min( this.camera.far, this.maxFar ); <add> const shaders = this.shaders; <ide> <del> for ( let i = 0; i < this.shaders.length; i ++ ) { <add> shaders.forEach( function ( shader, material ) { <ide> <del> const shader = this.shaders[ i ]; <del> const uniforms = shader.uniforms; <del> this.getExtendedBreaks( uniforms.CSM_cascades.value ); <del> uniforms.cameraNear.value = this.camera.near; <del> uniforms.shadowFar.value = far; <add> if ( shader !== null ) { <ide> <del> } <add> const uniforms = shader.uniforms; <add> this.getExtendedBreaks( uniforms.CSM_cascades.value ); <add> uniforms.cameraNear.value = this.camera.near; <add> uniforms.shadowFar.value = far; <ide> <del> for ( let i = 0; i < this.materials.length; i ++ ) { <add> } <ide> <del> const material = this.materials[ i ]; <ide> if ( ! this.fade && 'CSM_FADE' in material.defines ) { <ide> <ide> delete material.defines.CSM_FADE; <ide> export default class CSM { <ide> <ide> } <ide> <del> } <add> }, this ); <ide> <ide> } <ide>
1
Javascript
Javascript
fix undefined timeout regression
bde32f8a4d24cf5201b3178c275b1cda9d77003c
<ide><path>lib/timers.js <ide> var lists = {}; <ide> // with them. <ide> exports.active = function(item) { <ide> const msecs = item._idleTimeout; <del> if (msecs < 0) return; <add> if (msecs < 0 || msecs === undefined) return; <ide> <ide> item._idleStart = Timer.now(); <ide> <ide><path>test/parallel/test-timers-active.js <ide> legitTimers.forEach(function(legit) { <ide> <ide> // active() should not create a timer for these <ide> var bogusTimers = [ <del> { _idleTimeout: -1 } <add> { _idleTimeout: -1 }, <add> { _idleTimeout: undefined }, <ide> ]; <ide> <ide> bogusTimers.forEach(function(bogus) {
2
Ruby
Ruby
convert buildenvironment test to spec
f581ad7f0b73e0a8d38868d2d4fa85bb7fb0c486
<ide><path>Library/Homebrew/test/build_environment_spec.rb <add>require "build_environment" <add> <add>RSpec::Matchers.alias_matcher :use_userpaths, :be_userpaths <add> <add>describe BuildEnvironment do <add> let(:env) { described_class.new } <add> <add> describe "#<<" do <add> it "returns itself" do <add> expect(env << :foo).to be env <add> end <add> end <add> <add> describe "#merge" do <add> it "returns itself" do <add> expect(env.merge([])).to be env <add> end <add> end <add> <add> describe "#std?" do <add> it "returns true if the environment contains :std" do <add> env << :std <add> expect(env).to be_std <add> end <add> <add> it "returns false if the environment does not contain :std" do <add> expect(env).not_to be_std <add> end <add> end <add> <add> describe "#userpaths?" do <add> it "returns true if the environment contains :userpaths" do <add> env << :userpaths <add> expect(env).to use_userpaths <add> end <add> <add> it "returns false if the environment does not contain :userpaths" do <add> expect(env).not_to use_userpaths <add> end <add> end <add>end <add> <add>describe BuildEnvironmentDSL do <add> subject { double.extend(described_class) } <add> <add> context "single argument" do <add> before(:each) do <add> subject.instance_eval do <add> env :userpaths <add> end <add> end <add> <add> its(:env) { is_expected.to use_userpaths } <add> end <add> <add> context "multiple arguments" do <add> before(:each) do <add> subject.instance_eval do <add> env :userpaths, :std <add> end <add> end <add> <add> its(:env) { is_expected.to be_std } <add> its(:env) { is_expected.to use_userpaths } <add> end <add>end <ide><path>Library/Homebrew/test/build_environment_test.rb <del>require "testing_env" <del>require "build_environment" <del> <del>class BuildEnvironmentTests < Homebrew::TestCase <del> def setup <del> super <del> @env = BuildEnvironment.new <del> end <del> <del> def test_shovel_returns_self <del> assert_same @env, @env << :foo <del> end <del> <del> def test_merge_returns_self <del> assert_same @env, @env.merge([]) <del> end <del> <del> def test_std? <del> @env << :std <del> assert_predicate @env, :std? <del> end <del> <del> def test_userpaths? <del> @env << :userpaths <del> assert_predicate @env, :userpaths? <del> end <del>end <del> <del>class BuildEnvironmentDSLTests < Homebrew::TestCase <del> def make_instance(&block) <del> obj = Object.new.extend(BuildEnvironmentDSL) <del> obj.instance_eval(&block) <del> obj <del> end <del> <del> def test_env_single_argument <del> obj = make_instance { env :userpaths } <del> assert_predicate obj.env, :userpaths? <del> end <del> <del> def test_env_multiple_arguments <del> obj = make_instance { env :userpaths, :std } <del> assert_predicate obj.env, :userpaths? <del> assert_predicate obj.env, :std? <del> end <del>end
2
Ruby
Ruby
simplify time.find_timezone! logic
f6893cd2426521d0edcaeed1df4861d9ea8a44c7
<ide><path>activesupport/lib/active_support/core_ext/time/zones.rb <ide> def use_zone(time_zone) <ide> # Time.find_zone! false # => false <ide> # Time.find_zone! "NOT-A-TIMEZONE" # => ArgumentError: Invalid Timezone: NOT-A-TIMEZONE <ide> def find_zone!(time_zone) <del> if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone) <del> time_zone <del> else <del> # Look up the timezone based on the identifier (unless we've been <del> # passed a TZInfo::Timezone) <del> unless time_zone.respond_to?(:period_for_local) <del> time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone) <del> end <add> return time_zone unless time_zone <ide> <del> # Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone <del> if time_zone.is_a?(ActiveSupport::TimeZone) <del> time_zone <del> else <del> ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone) <del> end <del> end <del> rescue TZInfo::InvalidTimezoneIdentifier <del> raise ArgumentError, "Invalid Timezone: #{time_zone}" <add> ActiveSupport::TimeZone[time_zone] || raise(ArgumentError, "Invalid Timezone: #{time_zone}") <ide> end <ide> <ide> # Returns a TimeZone instance matching the time zone provided. <ide><path>activesupport/lib/active_support/values/time_zone.rb <ide> def all <ide> # Returns +nil+ if no such time zone is known to the system. <ide> def [](arg) <ide> case arg <add> when self <add> arg <ide> when String <ide> begin <ide> @lazy_zones_map[arg] ||= create(arg) <ide> rescue TZInfo::InvalidTimezoneIdentifier <ide> nil <ide> end <add> when TZInfo::Timezone <add> @lazy_zones_map[arg.name] ||= create(arg.name, nil, arg) <ide> when Numeric, ActiveSupport::Duration <ide> arg *= 3600 if arg.abs <= 13 <ide> all.find { |z| z.utc_offset == arg.to_i } <ide><path>activesupport/test/core_ext/time_with_zone_test.rb <ide> def test_find_zone_without_bang_returns_nil_if_time_zone_can_not_be_found <ide> end <ide> <ide> def test_find_zone_with_bang_raises_if_time_zone_can_not_be_found <del> assert_raise(ArgumentError) { Time.find_zone!("No such timezone exists") } <del> assert_raise(ArgumentError) { Time.find_zone!(-15.hours) } <del> assert_raise(ArgumentError) { Time.find_zone!(Object.new) } <add> error = assert_raise(ArgumentError) { Time.find_zone!("No such timezone exists") } <add> assert_equal "Invalid Timezone: No such timezone exists", error.message <add> <add> error = assert_raise(ArgumentError) { Time.find_zone!(-15.hours) } <add> assert_equal "Invalid Timezone: -54000", error.message <add> <add> error = assert_raise(ArgumentError) { Time.find_zone!(Object.new) } <add> assert_match "invalid argument to TimeZone[]", error.message <add> end <add> <add> def test_find_zone_with_bang_doesnt_raises_with_nil_and_false <add> assert_nil Time.find_zone!(nil) <add> assert_equal false, Time.find_zone!(false) <ide> end <ide> <ide> def test_time_zone_setter_with_find_zone_without_bang <ide><path>activesupport/test/time_zone_test.rb <ide> def test_from_duration_to_map <ide> assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[-480.minutes] # PST <ide> end <ide> <add> def test_from_tzinfo_to_map <add> tzinfo = TZInfo::Timezone.get("Europe/London") <add> assert_instance_of ActiveSupport::TimeZone, ActiveSupport::TimeZone[tzinfo] <add> assert_same ActiveSupport::TimeZone[tzinfo], ActiveSupport::TimeZone[tzinfo] <add> end <add> <ide> ActiveSupport::TimeZone.all.each do |zone| <ide> name = zone.name.downcase.gsub(/[^a-z]/, "_") <ide> define_method("test_from_#{name}_to_map") do
4
PHP
PHP
make draw() and increment() also chainable
8c55c8820e7d6b22052238ad7bee8188510a91ba
<ide><path>src/Shell/Helper/ProgressHelper.php <ide> public function init(array $args = []) <ide> * Increment the progress bar. <ide> * <ide> * @param int $num The amount of progress to advance by. <del> * @return void <add> * @return $this <ide> */ <ide> public function increment($num = 1) <ide> { <ide> $this->_progress = min(max(0, $this->_progress + $num), $this->_total); <add> <add> return $this; <ide> } <ide> <ide> /** <ide> * Render the progress bar based on the current state. <ide> * <del> * @return void <add> * @return $this; <ide> */ <ide> public function draw() <ide> { <ide> public function draw() <ide> $bar .= str_pad($percent, $numberLen, ' ', STR_PAD_LEFT); <ide> <ide> $this->_io->overwrite($bar, 0); <add> <add> return $this; <ide> } <ide> } <ide><path>tests/TestCase/Shell/Helper/ProgressHelperTest.php <ide> public function testIncrementAndRender() <ide> $this->assertEquals($expected, $this->stub->messages()); <ide> } <ide> <add> /** <add> * Test using the helper chained. <add> * <add> * @return void <add> */ <add> public function testIncrementAndRenderChained() <add> { <add> $this->helper->init() <add> ->increment(20) <add> ->draw() <add> ->increment(40) <add> ->draw() <add> ->increment(40) <add> ->draw(); <add> <add> $expected = [ <add> '', <add> '==============> 20%', <add> '', <add> '============================================> 60%', <add> '', <add> '==========================================================================> 100%', <add> ]; <add> $this->assertEquals($expected, $this->stub->messages()); <add> } <add> <ide> /** <ide> * Test negative numbers <ide> *
2
Text
Text
add coterminal angles article
1f3fb19b0536ab6b56c8e468b15f2df05c1bb5a4
<ide><path>guide/english/mathematics/coterminal-angles/index.md <ide> title: Coterminal Angles <ide> --- <ide> ## Coterminal Angles <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/coterminal-angles/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <del> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <del> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <del> <del>#### More Information: <del><!-- Please add any articles you think might be helpful to read before writing the article --> <del> <add>Coterminal angles are, in short, angles that share a terminal side. As there are 360 degrees in a circle, an angle A is coterminal with another angle B if B = A + (*K* * 360), where *K* is any integer. The logic behind this is that if you were to start at A and go one full rotation around the circle, you would end up back at A, as you would if you went 2, 5, or 10,000 rotations around the circle. Therefore, if you started at 0 and traveled A + (*K* * 360) degrees clockwise, you would end up at A. <ide> <add>*K* as mentioned above can be negative. In this case, the coterminal angle will be negative. This still makes sense, as if you start at 0 degrees and travel A + (*K* * 360) **counterclockwise**, you will end up at A.
1
Ruby
Ruby
fix railties tests for 7.0
05023462642761c5c85b395f17b5a4c9be640bf2
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def delete_api_initializers <ide> <ide> def delete_new_framework_defaults <ide> unless options[:update] <del> remove_file "config/initializers/new_framework_defaults_6_2.rb" <add> remove_file "config/initializers/new_framework_defaults_7_0.rb" <ide> end <ide> end <ide> <ide><path>railties/test/application/configuration_test.rb <ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end <ide> test "ActionView::Helpers::UrlHelper.button_to_generates_button_tag can be configured via config.action_view.button_to_generates_button_tag" do <ide> remove_from_config '.*config\.load_defaults.*\n' <ide> <del> app_file "config/initializers/new_framework_defaults_6_2.rb", <<-RUBY <add> app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY <ide> Rails.application.config.action_view.button_to_generates_button_tag = true <ide> RUBY <ide> <ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end <ide> test "ActionView::Helpers::AssetTagHelper.apply_stylesheet_media_default can be configured via config.action_view.apply_stylesheet_media_default" do <ide> remove_from_config '.*config\.load_defaults.*\n' <ide> <del> app_file "config/initializers/new_framework_defaults_6_2.rb", <<-RUBY <add> app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY <ide> Rails.application.config.action_view.apply_stylesheet_media_default = false <ide> RUBY <ide> <ide> class MyLogger < ::Logger <ide> test "ActionDispatch::Request.return_only_media_type_on_content_type can be configured in the new framework defaults" do <ide> remove_from_config '.*config\.load_defaults.*\n' <ide> <del> app_file "config/initializers/new_framework_defaults_6_2.rb", <<-RUBY <add> app_file "config/initializers/new_framework_defaults_7_0.rb", <<-RUBY <ide> Rails.application.config.action_dispatch.return_only_request_media_type_on_content_type = false <ide> RUBY <ide> <ide><path>railties/test/generators/app_generator_test.rb <ide> def test_new_application_not_include_api_initializers <ide> <ide> def test_new_application_doesnt_need_defaults <ide> run_generator <del> assert_no_file "config/initializers/new_framework_defaults_6_2.rb" <add> assert_no_file "config/initializers/new_framework_defaults_7_0.rb" <ide> end <ide> <ide> def test_new_application_load_defaults <ide> def test_app_update_create_new_framework_defaults <ide> app_root = File.join(destination_root, "myapp") <ide> run_generator [app_root] <ide> <del> assert_no_file "#{app_root}/config/initializers/new_framework_defaults_6_2.rb" <add> assert_no_file "#{app_root}/config/initializers/new_framework_defaults_7_0.rb" <ide> <ide> stub_rails_application(app_root) do <ide> generator = Rails::Generators::AppGenerator.new ["rails"], { update: true }, { destination_root: app_root, shell: @shell } <ide> generator.send(:app_const) <ide> quietly { generator.update_config_files } <ide> <del> assert_file "#{app_root}/config/initializers/new_framework_defaults_6_2.rb" <add> assert_file "#{app_root}/config/initializers/new_framework_defaults_7_0.rb" <ide> end <ide> end <ide>
3
Javascript
Javascript
add depth of field post-process with bokeh shader
7eac0a724b4cacc040e4ec2de8441c56eeb90992
<ide><path>examples/js/postprocessing/BokehPass.js <add>/** <add> * Depth-of-field post-process with bokeh shader <add> */ <add> <add> <add>THREE.BokehPass = function ( scene, camera, params ) { <add> <add> this.scene = scene; <add> this.camera = camera; <add> <add> var focus = ( params.focus !== undefined ) ? params.focus : 1.0; <add> var aspect = ( params.aspect !== undefined ) ? params.aspect : camera.aspect; <add> var aperture = ( params.aperture !== undefined ) ? params.aperture : 0.025; <add> var maxblur = ( params.maxblur !== undefined ) ? params.maxblur : 1.0; <add> <add> // render targets <add> <add> var width = params.width || window.innerWidth || 1; <add> var height = params.height || window.innerHeight || 1; <add> <add> this.renderTargetColor = new THREE.WebGLRenderTarget( width, height, { <add> minFilter: THREE.LinearFilter, <add> magFilter: THREE.LinearFilter, <add> format: THREE.RGBFormat <add> } ); <add> <add> this.renderTargetDepth = this.renderTargetColor.clone(); <add> <add> // depth material <add> <add> this.materialDepth = new THREE.MeshDepthMaterial(); <add> <add> // bokeh material <add> <add> if ( THREE.BokehShader === undefined ) { <add> console.error( "THREE.BokehPass relies on THREE.BokehShader" ); <add> } <add> <add> var bokehShader = THREE.BokehShader; <add> var bokehUniforms = THREE.UniformsUtils.clone( bokehShader.uniforms ); <add> <add> bokehUniforms[ "tDepth" ].value = this.renderTargetDepth; <add> <add> bokehUniforms[ "focus" ].value = focus; <add> bokehUniforms[ "aspect" ].value = aspect; <add> bokehUniforms[ "aperture" ].value = aperture; <add> bokehUniforms[ "maxblur" ].value = maxblur; <add> <add> this.materialBokeh = new THREE.ShaderMaterial({ <add> uniforms: bokehUniforms, <add> vertexShader: bokehShader.vertexShader, <add> fragmentShader: bokehShader.fragmentShader <add> }); <add> <add> this.uniforms = bokehUniforms; <add> this.enabled = true; <add> this.needsSwap = false; <add> this.renderToScreen = false; <add> this.clear = false; <add> <add>}; <add> <add>THREE.BokehPass.prototype = { <add> <add> render: function ( renderer, writeBuffer, readBuffer, delta, maskActive ) { <add> <add> var composer = THREE.EffectComposer; <add> <add> composer.quad.material = this.materialBokeh; <add> <add> // Render depth into texture <add> <add> this.scene.overrideMaterial = this.materialDepth; <add> <add> renderer.render( this.scene, this.camera, this.renderTargetDepth, true ); <add> <add> // Render bokeh composite <add> <add> this.uniforms[ "tColor" ].value = readBuffer; <add> <add> if ( this.renderToScreen ) { <add> <add> renderer.render( composer.scene, composer.camera ); <add> <add> } else { <add> <add> renderer.render( composer.scene, composer.camera, writeBuffer, this.clear ); <add> <add> } <add> <add> this.scene.overrideMaterial = null; <add> <add> } <add> <add>}; <add>
1
Javascript
Javascript
use capture phase for mouseup handler
3926dac789733856cfb7f8533ffb00e4ab663272
<ide><path>src/text-editor-component.js <ide> class TextEditorComponent { <ide> } <ide> <ide> window.addEventListener('mousemove', didMouseMove) <del> window.addEventListener('mouseup', didMouseUp) <add> window.addEventListener('mouseup', didMouseUp, {capture: true}) <ide> } <ide> <ide> autoscrollOnMouseDrag ({clientX, clientY}, verticalOnly = false) {
1
Ruby
Ruby
add comment to env.libxml2
522ed0050f55a8aa45a7fb35d2ebda96b07a9a95
<ide><path>Library/Homebrew/extend/ENV.rb <ide> def no_optimization <ide> self['CFLAGS'] = self['CXXFLAGS'] = SAFE_CFLAGS_FLAGS <ide> end <ide> <add> # Some configure scripts won't find libxml2 without help <ide> def libxml2 <del> append_to_cflags ' -I/usr/include/libxml2' <add> append_to_cflags '-I/usr/include/libxml2' <ide> end <ide> <ide> def x11
1
Javascript
Javascript
fix tests for non-crypto builds
15cd45c6fc637c437cf63e6b04882be18f09c130
<ide><path>test/parallel/test-async-wrap-check-providers.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const crypto = require('crypto'); <ide> const dgram = require('dgram'); <ide><path>test/parallel/test-async-wrap-post-did-throw.js <ide> 'use strict'; <ide> <del>require('../common'); <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const async_wrap = process.binding('async_wrap'); <ide> var asyncThrows = 0; <ide><path>test/parallel/test-async-wrap-throw-from-callback.js <ide> 'use strict'; <ide> <del>require('../common'); <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const async_wrap = process.binding('async_wrap'); <ide> const assert = require('assert'); <ide> const crypto = require('crypto'); <ide><path>test/parallel/test-crypto-rsa-dsa.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var fs = require('fs'); <del>var constants = require('crypto').constants; <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> return; <ide> } <add>var constants = require('crypto').constants; <ide> var crypto = require('crypto'); <ide> <ide> // Test certificates <ide><path>test/parallel/test-http-invalid-urls.js <ide> 'use strict'; <ide> <del>require('../common'); <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const https = require('https'); <ide><path>test/parallel/test-https-agent-getname.js <ide> 'use strict'; <ide> <del>require('../common'); <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const https = require('https'); <ide> <ide><path>test/parallel/test-https-connect-address-family.js <ide> 'use strict'; <ide> const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const https = require('https'); <ide> <ide><path>test/parallel/test-https-resume-after-renew.js <ide> 'use strict'; <del>var common = require('../common'); <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> var fs = require('fs'); <ide> var https = require('https'); <ide> var crypto = require('crypto'); <ide><path>test/parallel/test-net-access-byteswritten.js <ide> 'use strict'; <ide> <del>require('../common'); <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> const tls = require('tls'); <ide><path>test/parallel/test-npm-install.js <ide> 'use strict'; <ide> const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <ide> <ide> const path = require('path'); <ide> const spawn = require('child_process').spawn; <ide><path>test/parallel/test-stream-base-no-abort.js <ide> 'use strict'; <ide> <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const async_wrap = process.binding('async_wrap'); <ide> const uv = process.binding('uv'); <ide> const assert = require('assert'); <del>const common = require('../common'); <ide> const dgram = require('dgram'); <ide> const fs = require('fs'); <ide> const net = require('net'); <ide><path>test/parallel/test-tls-async-cb-after-socket-end.js <ide> 'use strict'; <ide> <del>var common = require('../common'); <del> <del>var path = require('path'); <del>var fs = require('fs'); <del>const SSL_OP_NO_TICKET = require('crypto').constants.SSL_OP_NO_TICKET; <del> <add>const common = require('../common'); <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> return; <ide> } <ide> <add>const path = require('path'); <add>const fs = require('fs'); <add>const SSL_OP_NO_TICKET = require('crypto').constants.SSL_OP_NO_TICKET; <add> <ide> var tls = require('tls'); <ide> <ide> var options = { <ide><path>test/parallel/test-tls-basic-validations.js <ide> 'use strict'; <ide> <del>require('../common'); <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const tls = require('tls'); <ide> <ide><path>test/parallel/test-tls-connect-address-family.js <ide> 'use strict'; <ide> const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const tls = require('tls'); <ide> <ide><path>test/parallel/test-tls-connect-stream-writes.js <ide> 'use strict'; <ide> const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const tls = require('tls'); <ide><path>test/parallel/test-tls-npn-server-client.js <ide> 'use strict'; <add>const common = require('../common'); <ide> if (!process.features.tls_npn) { <ide> common.skip('node compiled without OpenSSL or ' + <ide> 'with old OpenSSL version.'); <ide> return; <ide> } <ide> <del>const common = require('../common'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> <ide><path>test/parallel/test-tls-parse-cert-string.js <ide> 'use strict'; <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <ide> <del>require('../common'); <ide> const assert = require('assert'); <ide> const tls = require('tls'); <ide> <ide><path>test/parallel/test-tls-securepair-fiftharg.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const tls = require('tls'); <ide><path>test/parallel/test-tls-sni-option.js <ide> 'use strict'; <add>const common = require('../common'); <ide> if (!process.features.tls_sni) { <ide> common.skip('node compiled without OpenSSL or ' + <ide> 'with old OpenSSL version.'); <ide> return; <ide> } <ide> <del>const common = require('../common'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> <ide><path>test/parallel/test-tls-sni-server-client.js <ide> 'use strict'; <add>const common = require('../common'); <ide> if (!process.features.tls_sni) { <ide> common.skip('node compiled without OpenSSL or ' + <ide> 'with old OpenSSL version.'); <ide> return; <ide> } <ide> <del>const common = require('../common'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> <ide><path>test/parallel/test-tls-two-cas-one-string.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const tls = require('tls'); <ide> const fs = require('fs'); <ide> <ide><path>test/parallel/test-tls-wrap-no-abort.js <ide> 'use strict'; <ide> <del>require('../common'); <add>const common = require('../common'); <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <ide> const util = require('util'); <ide> const TLSWrap = process.binding('tls_wrap').TLSWrap; <ide>
22
Java
Java
revert d2759498 to unbreak ama release build
b6ef42299e22079c74a79a03e7e5165bb54246f4
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerImpl.java <ide> import com.facebook.react.common.annotations.VisibleForTesting; <ide> import com.facebook.react.devsupport.DevServerHelper; <ide> import com.facebook.react.devsupport.DevSupportManager; <del>import com.facebook.react.devsupport.DevSupportManagerImpl; <del>import com.facebook.react.devsupport.DisabledDevSupportManager; <ide> import com.facebook.react.devsupport.ReactInstanceDevCommandsHandler; <ide> import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; <ide> import com.facebook.react.modules.core.DeviceEventManagerModule; <ide> public T get() throws Exception { <ide> mJSMainModuleName = jsMainModuleName; <ide> mPackages = packages; <ide> mUseDeveloperSupport = useDeveloperSupport; <del> if (mUseDeveloperSupport) { <del> mDevSupportManager = new DevSupportManagerImpl( <del> applicationContext, <del> mDevInterface, <del> mJSMainModuleName, <del> useDeveloperSupport); <del> } else { <del> mDevSupportManager = new DisabledDevSupportManager(); <del> } <add> // We need to instantiate DevSupportManager regardless to the useDeveloperSupport option, <add> // although will prevent dev support manager from displaying any options or dialogs by <add> // checking useDeveloperSupport option before calling setDevSupportEnabled on this manager <add> // TODO(6803830): Don't instantiate devsupport manager when useDeveloperSupport is false <add> mDevSupportManager = new DevSupportManager( <add> applicationContext, <add> mDevInterface, <add> mJSMainModuleName, <add> useDeveloperSupport); <ide> mBridgeIdleDebugListener = bridgeIdleDebugListener; <ide> mLifecycleState = initialLifecycleState; <ide> mUIImplementationProvider = uiImplementationProvider; <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/DefaultNativeModuleCallExceptionHandler.java <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> */ <del> <del>package com.facebook.react.bridge; <del> <del>/** <del> * Crashy crashy exception handler. <del> */ <del>public class DefaultNativeModuleCallExceptionHandler implements NativeModuleCallExceptionHandler { <del> <del> @Override <del> public void handleException(Exception e) { <del> if (e instanceof RuntimeException) { <del> // Because we are rethrowing the original exception, the original stacktrace will be <del> // preserved. <del> throw (RuntimeException) e; <del> } else { <del> throw new RuntimeException(e); <del> } <del> } <del>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManager.java <ide> <ide> package com.facebook.react.devsupport; <ide> <add>import javax.annotation.Nullable; <add> <add>import java.io.File; <add>import java.io.IOException; <add>import java.util.LinkedHashMap; <add>import java.util.Locale; <add>import java.util.concurrent.ExecutionException; <add>import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.TimeoutException; <add> <add>import android.app.AlertDialog; <add>import android.app.ProgressDialog; <add>import android.content.BroadcastReceiver; <add>import android.content.Context; <add>import android.content.DialogInterface; <add>import android.content.Intent; <add>import android.content.IntentFilter; <add>import android.content.pm.PackageInfo; <add>import android.content.pm.PackageManager; <add>import android.hardware.SensorManager; <add>import android.os.Debug; <add>import android.os.Environment; <add>import android.view.WindowManager; <add>import android.widget.Toast; <add> <add>import com.facebook.common.logging.FLog; <add>import com.facebook.infer.annotation.Assertions; <add>import com.facebook.react.R; <add>import com.facebook.react.bridge.CatalystInstance; <add>import com.facebook.react.bridge.JavaJSExecutor; <ide> import com.facebook.react.bridge.NativeModuleCallExceptionHandler; <ide> import com.facebook.react.bridge.ReactContext; <ide> import com.facebook.react.bridge.ReadableArray; <add>import com.facebook.react.bridge.UiThreadUtil; <add>import com.facebook.react.bridge.WebsocketJavaScriptExecutor; <add>import com.facebook.react.common.ReactConstants; <add>import com.facebook.react.common.ShakeDetector; <add>import com.facebook.react.common.futures.SimpleSettableFuture; <add>import com.facebook.react.devsupport.StackTraceHelper.StackFrame; <ide> import com.facebook.react.modules.debug.DeveloperSettings; <ide> <ide> /** <del> * Interface for accessing and interacting with development features. <del> * In dev mode, use the implementation {@link DevSupportManagerImpl}. <del> * In production mode, use the dummy implementation {@link DisabledDevSupportManager}. <add> * Interface for accessing and interacting with development features. Following features <add> * are supported through this manager class: <add> * 1) Displaying JS errors (aka RedBox) <add> * 2) Displaying developers menu (Reload JS, Debug JS) <add> * 3) Communication with developer server in order to download updated JS bundle <add> * 4) Starting/stopping broadcast receiver for js reload signals <add> * 5) Starting/stopping motion sensor listener that recognize shake gestures which in turn may <add> * trigger developers menu. <add> * 6) Launching developers settings view <add> * <add> * This class automatically monitors the state of registered views and activities to which they are <add> * bound to make sure that we don't display overlay or that we we don't listen for sensor events <add> * when app is backgrounded. <add> * <add> * {@link ReactInstanceDevCommandsHandler} implementation is responsible for instantiating this <add> * instance and for populating with an instance of {@link CatalystInstance} whenever instance <add> * manager recreates it (through {@link #onNewCatalystContextCreated}). Also, instance manager is <add> * responsible for enabling/disabling dev support in case when app is backgrounded or when all the <add> * views has been detached from the instance (through {@link #setDevSupportEnabled} method). <add> * <add> * IMPORTANT: In order for developer support to work correctly it is required that the <add> * manifest of your application contain the following entries: <add> * {@code <activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>} <add> * {@code <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>} <ide> */ <del>public interface DevSupportManager extends NativeModuleCallExceptionHandler { <del> <del> void showNewJavaError(String message, Throwable e); <del> void addCustomDevOption(String optionName, DevOptionHandler optionHandler); <del> void showNewJSError(String message, ReadableArray details, int errorCookie); <del> void updateJSError(final String message, final ReadableArray details, final int errorCookie); <del> void showDevOptionsDialog(); <del> void setDevSupportEnabled(boolean isDevSupportEnabled); <del> boolean getDevSupportEnabled(); <del> DeveloperSettings getDevSettings(); <del> void onNewReactContextCreated(ReactContext reactContext); <del> void onReactInstanceDestroyed(ReactContext reactContext); <del> String getSourceMapUrl(); <del> String getSourceUrl(); <del> String getJSBundleURLForRemoteDebugging(); <del> String getDownloadedJSBundleFile(); <del> boolean hasUpToDateJSBundleInCache(); <del> void reloadSettings(); <del> void handleReloadJS(); <del> void isPackagerRunning(DevServerHelper.PackagerStatusCallback callback); <add>public class DevSupportManager implements NativeModuleCallExceptionHandler { <add> <add> private static final int JAVA_ERROR_COOKIE = -1; <add> private static final String JS_BUNDLE_FILE_NAME = "ReactNativeDevBundle.js"; <add> <add> private static final String EXOPACKAGE_LOCATION_FORMAT <add> = "/data/local/tmp/exopackage/%s//secondary-dex"; <add> <add> private static final int JAVA_SAMPLING_PROFILE_MEMORY_BYTES = 8 * 1024 * 1024; <add> private static final int JAVA_SAMPLING_PROFILE_DELTA_US = 100; <add> <add> private final Context mApplicationContext; <add> private final ShakeDetector mShakeDetector; <add> private final BroadcastReceiver mReloadAppBroadcastReceiver; <add> private final DevServerHelper mDevServerHelper; <add> private final LinkedHashMap<String, DevOptionHandler> mCustomDevOptions = <add> new LinkedHashMap<>(); <add> private final ReactInstanceDevCommandsHandler mReactInstanceCommandsHandler; <add> private final @Nullable String mJSAppBundleName; <add> private final File mJSBundleTempFile; <add> <add> private @Nullable RedBoxDialog mRedBoxDialog; <add> private @Nullable AlertDialog mDevOptionsDialog; <add> private @Nullable DebugOverlayController mDebugOverlayController; <add> private @Nullable ReactContext mCurrentContext; <add> private DevInternalSettings mDevSettings; <add> private boolean mIsUsingJSProxy = false; <add> private boolean mIsReceiverRegistered = false; <add> private boolean mIsShakeDetectorStarted = false; <add> private boolean mIsDevSupportEnabled = false; <add> private boolean mIsCurrentlyProfiling = false; <add> private int mProfileIndex = 0; <add> <add> public DevSupportManager( <add> Context applicationContext, <add> ReactInstanceDevCommandsHandler reactInstanceCommandsHandler, <add> @Nullable String packagerPathForJSBundleName, <add> boolean enableOnCreate) { <add> mReactInstanceCommandsHandler = reactInstanceCommandsHandler; <add> mApplicationContext = applicationContext; <add> mJSAppBundleName = packagerPathForJSBundleName; <add> mDevSettings = new DevInternalSettings(applicationContext, this); <add> mDevServerHelper = new DevServerHelper(mDevSettings); <add> <add> // Prepare shake gesture detector (will be started/stopped from #reload) <add> mShakeDetector = new ShakeDetector(new ShakeDetector.ShakeListener() { <add> @Override <add> public void onShake() { <add> showDevOptionsDialog(); <add> } <add> }); <add> <add> // Prepare reload APP broadcast receiver (will be registered/unregistered from #reload) <add> mReloadAppBroadcastReceiver = new BroadcastReceiver() { <add> @Override <add> public void onReceive(Context context, Intent intent) { <add> String action = intent.getAction(); <add> if (DevServerHelper.getReloadAppAction(context).equals(action)) { <add> if (intent.getBooleanExtra(DevServerHelper.RELOAD_APP_EXTRA_JS_PROXY, false)) { <add> mIsUsingJSProxy = true; <add> mDevServerHelper.launchChromeDevtools(); <add> } else { <add> mIsUsingJSProxy = false; <add> } <add> handleReloadJS(); <add> } <add> } <add> }; <add> <add> // We store JS bundle loaded from dev server in a single destination in app's data dir. <add> // In case when someone schedule 2 subsequent reloads it may happen that JS thread will <add> // start reading first reload output while the second reload starts writing to the same <add> // file. As this should only be the case in dev mode we leave it as it is. <add> // TODO(6418010): Fix readers-writers problem in debug reload from HTTP server <add> mJSBundleTempFile = new File(applicationContext.getFilesDir(), JS_BUNDLE_FILE_NAME); <add> <add> setDevSupportEnabled(enableOnCreate); <add> } <add> <add> @Override <add> public void handleException(Exception e) { <add> if (mIsDevSupportEnabled) { <add> FLog.e(ReactConstants.TAG, "Exception in native call from JS", e); <add> showNewJavaError(e.getMessage(), e); <add> } else { <add> if (e instanceof RuntimeException) { <add> // Because we are rethrowing the original exception, the original stacktrace will be <add> // preserved <add> throw (RuntimeException) e; <add> } else { <add> throw new RuntimeException(e); <add> } <add> } <add> } <add> <add> public void showNewJavaError(String message, Throwable e) { <add> showNewError(message, StackTraceHelper.convertJavaStackTrace(e), JAVA_ERROR_COOKIE); <add> } <add> <add> /** <add> * Add option item to dev settings dialog displayed by this manager. In the case user select given <add> * option from that dialog, the appropriate handler passed as {@param optionHandler} will be <add> * called. <add> */ <add> public void addCustomDevOption( <add> String optionName, <add> DevOptionHandler optionHandler) { <add> mCustomDevOptions.put(optionName, optionHandler); <add> } <add> <add> public void showNewJSError(String message, ReadableArray details, int errorCookie) { <add> showNewError(message, StackTraceHelper.convertJsStackTrace(details), errorCookie); <add> } <add> <add> public void updateJSError( <add> final String message, <add> final ReadableArray details, <add> final int errorCookie) { <add> UiThreadUtil.runOnUiThread( <add> new Runnable() { <add> @Override <add> public void run() { <add> // Since we only show the first JS error in a succession of JS errors, make sure we only <add> // update the error message for that error message. This assumes that updateJSError <add> // belongs to the most recent showNewJSError <add> if (mRedBoxDialog == null || <add> !mRedBoxDialog.isShowing() || <add> errorCookie != mRedBoxDialog.getErrorCookie()) { <add> return; <add> } <add> mRedBoxDialog.setExceptionDetails( <add> message, <add> StackTraceHelper.convertJsStackTrace(details)); <add> mRedBoxDialog.show(); <add> } <add> }); <add> } <add> <add> private void showNewError( <add> final String message, <add> final StackFrame[] stack, <add> final int errorCookie) { <add> UiThreadUtil.runOnUiThread( <add> new Runnable() { <add> @Override <add> public void run() { <add> if (mRedBoxDialog == null) { <add> mRedBoxDialog = new RedBoxDialog(mApplicationContext, DevSupportManager.this); <add> mRedBoxDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); <add> } <add> if (mRedBoxDialog.isShowing()) { <add> // Sometimes errors cause multiple errors to be thrown in JS in quick succession. Only <add> // show the first and most actionable one. <add> return; <add> } <add> mRedBoxDialog.setExceptionDetails(message, stack); <add> mRedBoxDialog.setErrorCookie(errorCookie); <add> mRedBoxDialog.show(); <add> } <add> }); <add> } <add> <add> public void showDevOptionsDialog() { <add> if (mDevOptionsDialog != null || !mIsDevSupportEnabled) { <add> return; <add> } <add> LinkedHashMap<String, DevOptionHandler> options = new LinkedHashMap<>(); <add> /* register standard options */ <add> options.put( <add> mApplicationContext.getString(R.string.catalyst_reloadjs), new DevOptionHandler() { <add> @Override <add> public void onOptionSelected() { <add> handleReloadJS(); <add> } <add> }); <add> options.put( <add> mIsUsingJSProxy ? <add> mApplicationContext.getString(R.string.catalyst_debugjs_off) : <add> mApplicationContext.getString(R.string.catalyst_debugjs), <add> new DevOptionHandler() { <add> @Override <add> public void onOptionSelected() { <add> mIsUsingJSProxy = !mIsUsingJSProxy; <add> handleReloadJS(); <add> } <add> }); <add> options.put( <add> mDevSettings.isHotModuleReplacementEnabled() <add> ? mApplicationContext.getString(R.string.catalyst_hot_module_replacement_off) <add> : mApplicationContext.getString(R.string.catalyst_hot_module_replacement), <add> new DevOptionHandler() { <add> @Override <add> public void onOptionSelected() { <add> mDevSettings.setHotModuleReplacementEnabled(!mDevSettings.isHotModuleReplacementEnabled()); <add> handleReloadJS(); <add> } <add> }); <add> options.put( <add> mDevSettings.isReloadOnJSChangeEnabled() <add> ? mApplicationContext.getString(R.string.catalyst_live_reload_off) <add> : mApplicationContext.getString(R.string.catalyst_live_reload), <add> new DevOptionHandler() { <add> @Override <add> public void onOptionSelected() { <add> mDevSettings.setReloadOnJSChangeEnabled(!mDevSettings.isReloadOnJSChangeEnabled()); <add> } <add> }); <add> options.put( <add> mDevSettings.isElementInspectorEnabled() <add> ? mApplicationContext.getString(R.string.catalyst_element_inspector_off) <add> : mApplicationContext.getString(R.string.catalyst_element_inspector), <add> new DevOptionHandler() { <add> @Override <add> public void onOptionSelected() { <add> mDevSettings.setElementInspectorEnabled(!mDevSettings.isElementInspectorEnabled()); <add> mReactInstanceCommandsHandler.toggleElementInspector(); <add> } <add> }); <add> options.put( <add> mDevSettings.isFpsDebugEnabled() <add> ? mApplicationContext.getString(R.string.catalyst_perf_monitor_off) <add> : mApplicationContext.getString(R.string.catalyst_perf_monitor), <add> new DevOptionHandler() { <add> @Override <add> public void onOptionSelected() { <add> mDevSettings.setFpsDebugEnabled(!mDevSettings.isFpsDebugEnabled()); <add> } <add> }); <add> if (mCurrentContext != null && <add> mCurrentContext.getCatalystInstance() != null && <add> !mCurrentContext.getCatalystInstance().isDestroyed() && <add> mCurrentContext.getCatalystInstance().supportsProfiling()) { <add> options.put( <add> mApplicationContext.getString( <add> mIsCurrentlyProfiling ? R.string.catalyst_stop_profile : <add> R.string.catalyst_start_profile), <add> new DevOptionHandler() { <add> @Override <add> public void onOptionSelected() { <add> if (mCurrentContext != null && mCurrentContext.hasActiveCatalystInstance()) { <add> String profileName = (Environment.getExternalStorageDirectory().getPath() + <add> "/profile_" + mProfileIndex + ".json"); <add> if (mIsCurrentlyProfiling) { <add> mIsCurrentlyProfiling = false; <add> mProfileIndex++; <add> Debug.stopMethodTracing(); <add> mCurrentContext.getCatalystInstance() <add> .stopProfiler("profile", profileName); <add> Toast.makeText( <add> mCurrentContext, <add> "Profile output to " + profileName, <add> Toast.LENGTH_LONG).show(); <add> } else { <add> mIsCurrentlyProfiling = true; <add> mCurrentContext.getCatalystInstance().startProfiler("profile"); <add> Debug.startMethodTracingSampling( <add> profileName, <add> JAVA_SAMPLING_PROFILE_MEMORY_BYTES, <add> JAVA_SAMPLING_PROFILE_DELTA_US); <add> } <add> } <add> } <add> }); <add> } <add> options.put( <add> mApplicationContext.getString(R.string.catalyst_settings), new DevOptionHandler() { <add> @Override <add> public void onOptionSelected() { <add> Intent intent = new Intent(mApplicationContext, DevSettingsActivity.class); <add> intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); <add> mApplicationContext.startActivity(intent); <add> } <add> }); <add> <add> if (mCustomDevOptions.size() > 0) { <add> options.putAll(mCustomDevOptions); <add> } <add> <add> final DevOptionHandler[] optionHandlers = options.values().toArray(new DevOptionHandler[0]); <add> <add> mDevOptionsDialog = <add> new AlertDialog.Builder(mApplicationContext) <add> .setItems( <add> options.keySet().toArray(new String[0]), <add> new DialogInterface.OnClickListener() { <add> @Override <add> public void onClick(DialogInterface dialog, int which) { <add> optionHandlers[which].onOptionSelected(); <add> mDevOptionsDialog = null; <add> } <add> }) <add> .setOnCancelListener(new DialogInterface.OnCancelListener() { <add> @Override <add> public void onCancel(DialogInterface dialog) { <add> mDevOptionsDialog = null; <add> } <add> }) <add> .create(); <add> mDevOptionsDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); <add> mDevOptionsDialog.show(); <add> } <add> <add> /** <add> * {@link ReactInstanceDevCommandsHandler} is responsible for <add> * enabling/disabling dev support when a React view is attached/detached <add> * or when application state changes (e.g. the application is backgrounded). <add> */ <add> public void setDevSupportEnabled(boolean isDevSupportEnabled) { <add> mIsDevSupportEnabled = isDevSupportEnabled; <add> reload(); <add> } <add> <add> public boolean getDevSupportEnabled() { <add> return mIsDevSupportEnabled; <add> } <add> <add> public DeveloperSettings getDevSettings() { <add> return mDevSettings; <add> } <add> <add> public void onNewReactContextCreated(ReactContext reactContext) { <add> resetCurrentContext(reactContext); <add> } <add> <add> public void onReactInstanceDestroyed(ReactContext reactContext) { <add> if (reactContext == mCurrentContext) { <add> // only call reset context when the destroyed context matches the one that is currently set <add> // for this manager <add> resetCurrentContext(null); <add> } <add> } <add> <add> public String getSourceMapUrl() { <add> if (mJSAppBundleName == null) { <add> return ""; <add> } <add> <add> return mDevServerHelper.getSourceMapUrl(Assertions.assertNotNull(mJSAppBundleName)); <add> } <add> <add> public String getSourceUrl() { <add> if (mJSAppBundleName == null) { <add> return ""; <add> } <add> <add> return mDevServerHelper.getSourceUrl(Assertions.assertNotNull(mJSAppBundleName)); <add> } <add> <add> public String getJSBundleURLForRemoteDebugging() { <add> return mDevServerHelper.getJSBundleURLForRemoteDebugging( <add> Assertions.assertNotNull(mJSAppBundleName)); <add> } <add> <add> public String getDownloadedJSBundleFile() { <add> return mJSBundleTempFile.getAbsolutePath(); <add> } <add> <add> /** <add> * @return {@code true} if {@link ReactInstanceManager} should use downloaded JS bundle file <add> * instead of using JS file from assets. This may happen when app has not been updated since <add> * the last time we fetched the bundle. <add> */ <add> public boolean hasUpToDateJSBundleInCache() { <add> if (mIsDevSupportEnabled && mJSBundleTempFile.exists()) { <add> try { <add> String packageName = mApplicationContext.getPackageName(); <add> PackageInfo thisPackage = mApplicationContext.getPackageManager() <add> .getPackageInfo(packageName, 0); <add> if (mJSBundleTempFile.lastModified() > thisPackage.lastUpdateTime) { <add> // Base APK has not been updated since we donwloaded JS, but if app is using exopackage <add> // it may only be a single dex that has been updated. We check for exopackage dir update <add> // time in that case. <add> File exopackageDir = new File( <add> String.format(Locale.US, EXOPACKAGE_LOCATION_FORMAT, packageName)); <add> if (exopackageDir.exists()) { <add> return mJSBundleTempFile.lastModified() > exopackageDir.lastModified(); <add> } <add> return true; <add> } <add> } catch (PackageManager.NameNotFoundException e) { <add> // Ignore this error and just fallback to loading JS from assets <add> FLog.e(ReactConstants.TAG, "DevSupport is unable to get current app info"); <add> } <add> } <add> return false; <add> } <add> <add> /** <add> * @return {@code true} if JS bundle {@param bundleAssetName} exists, in that case <add> * {@link ReactInstanceManager} should use that file from assets instead of downloading bundle <add> * from dev server <add> */ <add> public boolean hasBundleInAssets(String bundleAssetName) { <add> try { <add> String[] assets = mApplicationContext.getAssets().list(""); <add> for (int i = 0; i < assets.length; i++) { <add> if (assets[i].equals(bundleAssetName)) { <add> return true; <add> } <add> } <add> } catch (IOException e) { <add> // Ignore this error and just fallback to downloading JS from devserver <add> FLog.e(ReactConstants.TAG, "Error while loading assets list"); <add> } <add> return false; <add> } <add> <add> private void resetCurrentContext(@Nullable ReactContext reactContext) { <add> if (mCurrentContext == reactContext) { <add> // new context is the same as the old one - do nothing <add> return; <add> } <add> <add> // if currently profiling stop and write the profile file <add> if (mIsCurrentlyProfiling) { <add> mIsCurrentlyProfiling = false; <add> String profileName = (Environment.getExternalStorageDirectory().getPath() + <add> "/profile_" + mProfileIndex + ".json"); <add> mProfileIndex++; <add> Debug.stopMethodTracing(); <add> mCurrentContext.getCatalystInstance().stopProfiler("profile", profileName); <add> } <add> <add> mCurrentContext = reactContext; <add> <add> // Recreate debug overlay controller with new CatalystInstance object <add> if (mDebugOverlayController != null) { <add> mDebugOverlayController.setFpsDebugViewVisible(false); <add> } <add> if (reactContext != null) { <add> mDebugOverlayController = new DebugOverlayController(reactContext); <add> } <add> <add> reloadSettings(); <add> } <add> <add> /* package */ void reloadSettings() { <add> reload(); <add> } <add> <add> public void handleReloadJS() { <add> UiThreadUtil.assertOnUiThread(); <add> <add> // dismiss redbox if exists <add> if (mRedBoxDialog != null) { <add> mRedBoxDialog.dismiss(); <add> } <add> <add> ProgressDialog progressDialog = new ProgressDialog(mApplicationContext); <add> progressDialog.setTitle(R.string.catalyst_jsload_title); <add> progressDialog.setMessage(mApplicationContext.getString( <add> mIsUsingJSProxy ? R.string.catalyst_remotedbg_message : R.string.catalyst_jsload_message)); <add> progressDialog.setIndeterminate(true); <add> progressDialog.setCancelable(false); <add> progressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); <add> progressDialog.show(); <add> <add> if (mIsUsingJSProxy) { <add> reloadJSInProxyMode(progressDialog); <add> } else { <add> reloadJSFromServer(progressDialog); <add> } <add> } <add> <add> public void isPackagerRunning(DevServerHelper.PackagerStatusCallback callback) { <add> mDevServerHelper.isPackagerRunning(callback); <add> } <add> <add> private void reloadJSInProxyMode(final ProgressDialog progressDialog) { <add> // When using js proxy, there is no need to fetch JS bundle as proxy executor will do that <add> // anyway <add> mDevServerHelper.launchChromeDevtools(); <add> <add> JavaJSExecutor.Factory factory = new JavaJSExecutor.Factory() { <add> @Override <add> public JavaJSExecutor create() throws Exception { <add> WebsocketJavaScriptExecutor executor = new WebsocketJavaScriptExecutor(); <add> SimpleSettableFuture<Boolean> future = new SimpleSettableFuture<>(); <add> executor.connect( <add> mDevServerHelper.getWebsocketProxyURL(), <add> getExecutorConnectCallback(progressDialog, future)); <add> // TODO(t9349129) Don't use timeout <add> try { <add> future.get(90, TimeUnit.SECONDS); <add> return executor; <add> } catch (ExecutionException e) { <add> throw (Exception) e.getCause(); <add> } catch (InterruptedException | TimeoutException e) { <add> throw new RuntimeException(e); <add> } <add> } <add> }; <add> mReactInstanceCommandsHandler.onReloadWithJSDebugger(factory); <add> } <add> <add> private WebsocketJavaScriptExecutor.JSExecutorConnectCallback getExecutorConnectCallback( <add> final ProgressDialog progressDialog, <add> final SimpleSettableFuture<Boolean> future) { <add> return new WebsocketJavaScriptExecutor.JSExecutorConnectCallback() { <add> @Override <add> public void onSuccess() { <add> future.set(true); <add> progressDialog.dismiss(); <add> } <add> <add> @Override <add> public void onFailure(final Throwable cause) { <add> progressDialog.dismiss(); <add> FLog.e(ReactConstants.TAG, "Unable to connect to remote debugger", cause); <add> future.setException( <add> new IOException( <add> mApplicationContext.getString(R.string.catalyst_remotedbg_error), cause)); <add> } <add> }; <add> } <add> <add> private void reloadJSFromServer(final ProgressDialog progressDialog) { <add> mDevServerHelper.downloadBundleFromURL( <add> new DevServerHelper.BundleDownloadCallback() { <add> @Override <add> public void onSuccess() { <add> progressDialog.dismiss(); <add> UiThreadUtil.runOnUiThread( <add> new Runnable() { <add> @Override <add> public void run() { <add> mReactInstanceCommandsHandler.onJSBundleLoadedFromServer(); <add> } <add> }); <add> } <add> <add> @Override <add> public void onFailure(final Exception cause) { <add> progressDialog.dismiss(); <add> FLog.e(ReactConstants.TAG, "Unable to download JS bundle", cause); <add> UiThreadUtil.runOnUiThread( <add> new Runnable() { <add> @Override <add> public void run() { <add> if (cause instanceof DebugServerException) { <add> DebugServerException debugServerException = (DebugServerException) cause; <add> showNewJavaError(debugServerException.description, cause); <add> } else { <add> showNewJavaError( <add> mApplicationContext.getString(R.string.catalyst_jsload_error), <add> cause); <add> } <add> } <add> }); <add> } <add> }, <add> Assertions.assertNotNull(mJSAppBundleName), <add> mJSBundleTempFile); <add> progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { <add> @Override <add> public void onCancel(DialogInterface dialog) { <add> mDevServerHelper.cancelDownloadBundleFromURL(); <add> } <add> }); <add> progressDialog.setCancelable(true); <add> } <add> <add> private void reload() { <add> // reload settings, show/hide debug overlay if required & start/stop shake detector <add> if (mIsDevSupportEnabled) { <add> // update visibility of FPS debug overlay depending on the settings <add> if (mDebugOverlayController != null) { <add> mDebugOverlayController.setFpsDebugViewVisible(mDevSettings.isFpsDebugEnabled()); <add> } <add> <add> // start shake gesture detector <add> if (!mIsShakeDetectorStarted) { <add> mShakeDetector.start( <add> (SensorManager) mApplicationContext.getSystemService(Context.SENSOR_SERVICE)); <add> mIsShakeDetectorStarted = true; <add> } <add> <add> // register reload app broadcast receiver <add> if (!mIsReceiverRegistered) { <add> IntentFilter filter = new IntentFilter(); <add> filter.addAction(DevServerHelper.getReloadAppAction(mApplicationContext)); <add> mApplicationContext.registerReceiver(mReloadAppBroadcastReceiver, filter); <add> mIsReceiverRegistered = true; <add> } <add> <add> if (mDevSettings.isReloadOnJSChangeEnabled()) { <add> mDevServerHelper.startPollingOnChangeEndpoint( <add> new DevServerHelper.OnServerContentChangeListener() { <add> @Override <add> public void onServerContentChanged() { <add> handleReloadJS(); <add> } <add> }); <add> } else { <add> mDevServerHelper.stopPollingOnChangeEndpoint(); <add> } <add> } else { <add> // hide FPS debug overlay <add> if (mDebugOverlayController != null) { <add> mDebugOverlayController.setFpsDebugViewVisible(false); <add> } <add> <add> // stop shake gesture detector <add> if (mIsShakeDetectorStarted) { <add> mShakeDetector.stop(); <add> mIsShakeDetectorStarted = false; <add> } <add> <add> // unregister app reload broadcast receiver <add> if (mIsReceiverRegistered) { <add> mApplicationContext.unregisterReceiver(mReloadAppBroadcastReceiver); <add> mIsReceiverRegistered = false; <add> } <add> <add> // hide redbox dialog <add> if (mRedBoxDialog != null) { <add> mRedBoxDialog.dismiss(); <add> } <add> <add> // hide dev options dialog <add> if (mDevOptionsDialog != null) { <add> mDevOptionsDialog.dismiss(); <add> } <add> <add> mDevServerHelper.stopPollingOnChangeEndpoint(); <add> } <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> */ <del> <del>package com.facebook.react.devsupport; <del> <del>import javax.annotation.Nullable; <del> <del>import java.io.File; <del>import java.io.IOException; <del>import java.util.LinkedHashMap; <del>import java.util.Locale; <del>import java.util.concurrent.ExecutionException; <del>import java.util.concurrent.TimeUnit; <del>import java.util.concurrent.TimeoutException; <del> <del>import android.app.AlertDialog; <del>import android.app.ProgressDialog; <del>import android.content.BroadcastReceiver; <del>import android.content.Context; <del>import android.content.DialogInterface; <del>import android.content.Intent; <del>import android.content.IntentFilter; <del>import android.content.pm.PackageInfo; <del>import android.content.pm.PackageManager; <del>import android.hardware.SensorManager; <del>import android.os.Debug; <del>import android.os.Environment; <del>import android.view.WindowManager; <del>import android.widget.Toast; <del> <del>import com.facebook.common.logging.FLog; <del>import com.facebook.infer.annotation.Assertions; <del>import com.facebook.react.R; <del>import com.facebook.react.bridge.CatalystInstance; <del>import com.facebook.react.bridge.DefaultNativeModuleCallExceptionHandler; <del>import com.facebook.react.bridge.JavaJSExecutor; <del>import com.facebook.react.bridge.NativeModuleCallExceptionHandler; <del>import com.facebook.react.bridge.ReactContext; <del>import com.facebook.react.bridge.ReadableArray; <del>import com.facebook.react.bridge.UiThreadUtil; <del>import com.facebook.react.bridge.WebsocketJavaScriptExecutor; <del>import com.facebook.react.common.ReactConstants; <del>import com.facebook.react.common.ShakeDetector; <del>import com.facebook.react.common.futures.SimpleSettableFuture; <del>import com.facebook.react.devsupport.StackTraceHelper.StackFrame; <del>import com.facebook.react.modules.debug.DeveloperSettings; <del> <del>/** <del> * Interface for accessing and interacting with development features. Following features <del> * are supported through this manager class: <del> * 1) Displaying JS errors (aka RedBox) <del> * 2) Displaying developers menu (Reload JS, Debug JS) <del> * 3) Communication with developer server in order to download updated JS bundle <del> * 4) Starting/stopping broadcast receiver for js reload signals <del> * 5) Starting/stopping motion sensor listener that recognize shake gestures which in turn may <del> * trigger developers menu. <del> * 6) Launching developers settings view <del> * <del> * This class automatically monitors the state of registered views and activities to which they are <del> * bound to make sure that we don't display overlay or that we we don't listen for sensor events <del> * when app is backgrounded. <del> * <del> * {@link ReactInstanceDevCommandsHandler} implementation is responsible for instantiating this <del> * instance and for populating with an instance of {@link CatalystInstance} whenever instance <del> * manager recreates it (through {@link #onNewCatalystContextCreated}). Also, instance manager is <del> * responsible for enabling/disabling dev support in case when app is backgrounded or when all the <del> * views has been detached from the instance (through {@link #setDevSupportEnabled} method). <del> * <del> * IMPORTANT: In order for developer support to work correctly it is required that the <del> * manifest of your application contain the following entries: <del> * {@code <activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>} <del> * {@code <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>} <del> */ <del>public class DevSupportManagerImpl implements DevSupportManager { <del> <del> private static final int JAVA_ERROR_COOKIE = -1; <del> private static final String JS_BUNDLE_FILE_NAME = "ReactNativeDevBundle.js"; <del> <del> private static final String EXOPACKAGE_LOCATION_FORMAT <del> = "/data/local/tmp/exopackage/%s//secondary-dex"; <del> <del> private static final int JAVA_SAMPLING_PROFILE_MEMORY_BYTES = 8 * 1024 * 1024; <del> private static final int JAVA_SAMPLING_PROFILE_DELTA_US = 100; <del> <del> private final Context mApplicationContext; <del> private final ShakeDetector mShakeDetector; <del> private final BroadcastReceiver mReloadAppBroadcastReceiver; <del> private final DevServerHelper mDevServerHelper; <del> private final LinkedHashMap<String, DevOptionHandler> mCustomDevOptions = <del> new LinkedHashMap<>(); <del> private final ReactInstanceDevCommandsHandler mReactInstanceCommandsHandler; <del> private final @Nullable String mJSAppBundleName; <del> private final File mJSBundleTempFile; <del> private final DefaultNativeModuleCallExceptionHandler mDefaultNativeModuleCallExceptionHandler; <del> <del> private @Nullable RedBoxDialog mRedBoxDialog; <del> private @Nullable AlertDialog mDevOptionsDialog; <del> private @Nullable DebugOverlayController mDebugOverlayController; <del> private @Nullable ReactContext mCurrentContext; <del> private DevInternalSettings mDevSettings; <del> private boolean mIsUsingJSProxy = false; <del> private boolean mIsReceiverRegistered = false; <del> private boolean mIsShakeDetectorStarted = false; <del> private boolean mIsDevSupportEnabled = false; <del> private boolean mIsCurrentlyProfiling = false; <del> private int mProfileIndex = 0; <del> <del> public DevSupportManagerImpl( <del> Context applicationContext, <del> ReactInstanceDevCommandsHandler reactInstanceCommandsHandler, <del> @Nullable String packagerPathForJSBundleName, <del> boolean enableOnCreate) { <del> mReactInstanceCommandsHandler = reactInstanceCommandsHandler; <del> mApplicationContext = applicationContext; <del> mJSAppBundleName = packagerPathForJSBundleName; <del> mDevSettings = new DevInternalSettings(applicationContext, this); <del> mDevServerHelper = new DevServerHelper(mDevSettings); <del> <del> // Prepare shake gesture detector (will be started/stopped from #reload) <del> mShakeDetector = new ShakeDetector(new ShakeDetector.ShakeListener() { <del> @Override <del> public void onShake() { <del> showDevOptionsDialog(); <del> } <del> }); <del> <del> // Prepare reload APP broadcast receiver (will be registered/unregistered from #reload) <del> mReloadAppBroadcastReceiver = new BroadcastReceiver() { <del> @Override <del> public void onReceive(Context context, Intent intent) { <del> String action = intent.getAction(); <del> if (DevServerHelper.getReloadAppAction(context).equals(action)) { <del> if (intent.getBooleanExtra(DevServerHelper.RELOAD_APP_EXTRA_JS_PROXY, false)) { <del> mIsUsingJSProxy = true; <del> mDevServerHelper.launchChromeDevtools(); <del> } else { <del> mIsUsingJSProxy = false; <del> } <del> handleReloadJS(); <del> } <del> } <del> }; <del> <del> // We store JS bundle loaded from dev server in a single destination in app's data dir. <del> // In case when someone schedule 2 subsequent reloads it may happen that JS thread will <del> // start reading first reload output while the second reload starts writing to the same <del> // file. As this should only be the case in dev mode we leave it as it is. <del> // TODO(6418010): Fix readers-writers problem in debug reload from HTTP server <del> mJSBundleTempFile = new File(applicationContext.getFilesDir(), JS_BUNDLE_FILE_NAME); <del> <del> mDefaultNativeModuleCallExceptionHandler = new DefaultNativeModuleCallExceptionHandler(); <del> <del> setDevSupportEnabled(enableOnCreate); <del> } <del> <del> @Override <del> public void handleException(Exception e) { <del> if (mIsDevSupportEnabled) { <del> FLog.e(ReactConstants.TAG, "Exception in native call from JS", e); <del> showNewJavaError(e.getMessage(), e); <del> } else { <del> mDefaultNativeModuleCallExceptionHandler.handleException(e); <del> } <del> } <del> <del> @Override <del> public void showNewJavaError(String message, Throwable e) { <del> showNewError(message, StackTraceHelper.convertJavaStackTrace(e), JAVA_ERROR_COOKIE); <del> } <del> <del> /** <del> * Add option item to dev settings dialog displayed by this manager. In the case user select given <del> * option from that dialog, the appropriate handler passed as {@param optionHandler} will be <del> * called. <del> */ <del> @Override <del> public void addCustomDevOption( <del> String optionName, <del> DevOptionHandler optionHandler) { <del> mCustomDevOptions.put(optionName, optionHandler); <del> } <del> <del> @Override <del> public void showNewJSError(String message, ReadableArray details, int errorCookie) { <del> showNewError(message, StackTraceHelper.convertJsStackTrace(details), errorCookie); <del> } <del> <del> @Override <del> public void updateJSError( <del> final String message, <del> final ReadableArray details, <del> final int errorCookie) { <del> UiThreadUtil.runOnUiThread( <del> new Runnable() { <del> @Override <del> public void run() { <del> // Since we only show the first JS error in a succession of JS errors, make sure we only <del> // update the error message for that error message. This assumes that updateJSError <del> // belongs to the most recent showNewJSError <del> if (mRedBoxDialog == null || <del> !mRedBoxDialog.isShowing() || <del> errorCookie != mRedBoxDialog.getErrorCookie()) { <del> return; <del> } <del> mRedBoxDialog.setExceptionDetails( <del> message, <del> StackTraceHelper.convertJsStackTrace(details)); <del> mRedBoxDialog.show(); <del> } <del> }); <del> } <del> <del> private void showNewError( <del> final String message, <del> final StackFrame[] stack, <del> final int errorCookie) { <del> UiThreadUtil.runOnUiThread( <del> new Runnable() { <del> @Override <del> public void run() { <del> if (mRedBoxDialog == null) { <del> mRedBoxDialog = new RedBoxDialog(mApplicationContext, DevSupportManagerImpl.this); <del> mRedBoxDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); <del> } <del> if (mRedBoxDialog.isShowing()) { <del> // Sometimes errors cause multiple errors to be thrown in JS in quick succession. Only <del> // show the first and most actionable one. <del> return; <del> } <del> mRedBoxDialog.setExceptionDetails(message, stack); <del> mRedBoxDialog.setErrorCookie(errorCookie); <del> mRedBoxDialog.show(); <del> } <del> }); <del> } <del> <del> @Override <del> public void showDevOptionsDialog() { <del> if (mDevOptionsDialog != null || !mIsDevSupportEnabled) { <del> return; <del> } <del> LinkedHashMap<String, DevOptionHandler> options = new LinkedHashMap<>(); <del> /* register standard options */ <del> options.put( <del> mApplicationContext.getString(R.string.catalyst_reloadjs), new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> handleReloadJS(); <del> } <del> }); <del> options.put( <del> mIsUsingJSProxy ? <del> mApplicationContext.getString(R.string.catalyst_debugjs_off) : <del> mApplicationContext.getString(R.string.catalyst_debugjs), <del> new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> mIsUsingJSProxy = !mIsUsingJSProxy; <del> handleReloadJS(); <del> } <del> }); <del> options.put( <del> mDevSettings.isHotModuleReplacementEnabled() <del> ? mApplicationContext.getString(R.string.catalyst_hot_module_replacement_off) <del> : mApplicationContext.getString(R.string.catalyst_hot_module_replacement), <del> new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> mDevSettings.setHotModuleReplacementEnabled(!mDevSettings.isHotModuleReplacementEnabled()); <del> handleReloadJS(); <del> } <del> }); <del> options.put( <del> mDevSettings.isReloadOnJSChangeEnabled() <del> ? mApplicationContext.getString(R.string.catalyst_live_reload_off) <del> : mApplicationContext.getString(R.string.catalyst_live_reload), <del> new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> mDevSettings.setReloadOnJSChangeEnabled(!mDevSettings.isReloadOnJSChangeEnabled()); <del> } <del> }); <del> options.put( <del> mDevSettings.isElementInspectorEnabled() <del> ? mApplicationContext.getString(R.string.catalyst_element_inspector_off) <del> : mApplicationContext.getString(R.string.catalyst_element_inspector), <del> new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> mDevSettings.setElementInspectorEnabled(!mDevSettings.isElementInspectorEnabled()); <del> mReactInstanceCommandsHandler.toggleElementInspector(); <del> } <del> }); <del> options.put( <del> mDevSettings.isFpsDebugEnabled() <del> ? mApplicationContext.getString(R.string.catalyst_perf_monitor_off) <del> : mApplicationContext.getString(R.string.catalyst_perf_monitor), <del> new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> mDevSettings.setFpsDebugEnabled(!mDevSettings.isFpsDebugEnabled()); <del> } <del> }); <del> if (mCurrentContext != null && <del> mCurrentContext.getCatalystInstance() != null && <del> !mCurrentContext.getCatalystInstance().isDestroyed() && <del> mCurrentContext.getCatalystInstance().supportsProfiling()) { <del> options.put( <del> mApplicationContext.getString( <del> mIsCurrentlyProfiling ? R.string.catalyst_stop_profile : <del> R.string.catalyst_start_profile), <del> new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> if (mCurrentContext != null && mCurrentContext.hasActiveCatalystInstance()) { <del> String profileName = (Environment.getExternalStorageDirectory().getPath() + <del> "/profile_" + mProfileIndex + ".json"); <del> if (mIsCurrentlyProfiling) { <del> mIsCurrentlyProfiling = false; <del> mProfileIndex++; <del> Debug.stopMethodTracing(); <del> mCurrentContext.getCatalystInstance() <del> .stopProfiler("profile", profileName); <del> Toast.makeText( <del> mCurrentContext, <del> "Profile output to " + profileName, <del> Toast.LENGTH_LONG).show(); <del> } else { <del> mIsCurrentlyProfiling = true; <del> mCurrentContext.getCatalystInstance().startProfiler("profile"); <del> Debug.startMethodTracingSampling( <del> profileName, <del> JAVA_SAMPLING_PROFILE_MEMORY_BYTES, <del> JAVA_SAMPLING_PROFILE_DELTA_US); <del> } <del> } <del> } <del> }); <del> } <del> options.put( <del> mApplicationContext.getString(R.string.catalyst_settings), new DevOptionHandler() { <del> @Override <del> public void onOptionSelected() { <del> Intent intent = new Intent(mApplicationContext, DevSettingsActivity.class); <del> intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); <del> mApplicationContext.startActivity(intent); <del> } <del> }); <del> <del> if (mCustomDevOptions.size() > 0) { <del> options.putAll(mCustomDevOptions); <del> } <del> <del> final DevOptionHandler[] optionHandlers = options.values().toArray(new DevOptionHandler[0]); <del> <del> mDevOptionsDialog = <del> new AlertDialog.Builder(mApplicationContext) <del> .setItems( <del> options.keySet().toArray(new String[0]), <del> new DialogInterface.OnClickListener() { <del> @Override <del> public void onClick(DialogInterface dialog, int which) { <del> optionHandlers[which].onOptionSelected(); <del> mDevOptionsDialog = null; <del> } <del> }) <del> .setOnCancelListener(new DialogInterface.OnCancelListener() { <del> @Override <del> public void onCancel(DialogInterface dialog) { <del> mDevOptionsDialog = null; <del> } <del> }) <del> .create(); <del> mDevOptionsDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); <del> mDevOptionsDialog.show(); <del> } <del> <del> /** <del> * {@link ReactInstanceDevCommandsHandler} is responsible for <del> * enabling/disabling dev support when a React view is attached/detached <del> * or when application state changes (e.g. the application is backgrounded). <del> */ <del> @Override <del> public void setDevSupportEnabled(boolean isDevSupportEnabled) { <del> mIsDevSupportEnabled = isDevSupportEnabled; <del> reload(); <del> } <del> <del> @Override <del> public boolean getDevSupportEnabled() { <del> return mIsDevSupportEnabled; <del> } <del> <del> @Override <del> public DeveloperSettings getDevSettings() { <del> return mDevSettings; <del> } <del> <del> @Override <del> public void onNewReactContextCreated(ReactContext reactContext) { <del> resetCurrentContext(reactContext); <del> } <del> <del> @Override <del> public void onReactInstanceDestroyed(ReactContext reactContext) { <del> if (reactContext == mCurrentContext) { <del> // only call reset context when the destroyed context matches the one that is currently set <del> // for this manager <del> resetCurrentContext(null); <del> } <del> } <del> <del> @Override <del> public String getSourceMapUrl() { <del> if (mJSAppBundleName == null) { <del> return ""; <del> } <del> <del> return mDevServerHelper.getSourceMapUrl(Assertions.assertNotNull(mJSAppBundleName)); <del> } <del> <del> @Override <del> public String getSourceUrl() { <del> if (mJSAppBundleName == null) { <del> return ""; <del> } <del> <del> return mDevServerHelper.getSourceUrl(Assertions.assertNotNull(mJSAppBundleName)); <del> } <del> <del> @Override <del> public String getJSBundleURLForRemoteDebugging() { <del> return mDevServerHelper.getJSBundleURLForRemoteDebugging( <del> Assertions.assertNotNull(mJSAppBundleName)); <del> } <del> <del> @Override <del> public String getDownloadedJSBundleFile() { <del> return mJSBundleTempFile.getAbsolutePath(); <del> } <del> <del> /** <del> * @return {@code true} if {@link ReactInstanceManager} should use downloaded JS bundle file <del> * instead of using JS file from assets. This may happen when app has not been updated since <del> * the last time we fetched the bundle. <del> */ <del> @Override <del> public boolean hasUpToDateJSBundleInCache() { <del> if (mIsDevSupportEnabled && mJSBundleTempFile.exists()) { <del> try { <del> String packageName = mApplicationContext.getPackageName(); <del> PackageInfo thisPackage = mApplicationContext.getPackageManager() <del> .getPackageInfo(packageName, 0); <del> if (mJSBundleTempFile.lastModified() > thisPackage.lastUpdateTime) { <del> // Base APK has not been updated since we donwloaded JS, but if app is using exopackage <del> // it may only be a single dex that has been updated. We check for exopackage dir update <del> // time in that case. <del> File exopackageDir = new File( <del> String.format(Locale.US, EXOPACKAGE_LOCATION_FORMAT, packageName)); <del> if (exopackageDir.exists()) { <del> return mJSBundleTempFile.lastModified() > exopackageDir.lastModified(); <del> } <del> return true; <del> } <del> } catch (PackageManager.NameNotFoundException e) { <del> // Ignore this error and just fallback to loading JS from assets <del> FLog.e(ReactConstants.TAG, "DevSupport is unable to get current app info"); <del> } <del> } <del> return false; <del> } <del> <del> /** <del> * @return {@code true} if JS bundle {@param bundleAssetName} exists, in that case <del> * {@link ReactInstanceManager} should use that file from assets instead of downloading bundle <del> * from dev server <del> */ <del> public boolean hasBundleInAssets(String bundleAssetName) { <del> try { <del> String[] assets = mApplicationContext.getAssets().list(""); <del> for (int i = 0; i < assets.length; i++) { <del> if (assets[i].equals(bundleAssetName)) { <del> return true; <del> } <del> } <del> } catch (IOException e) { <del> // Ignore this error and just fallback to downloading JS from devserver <del> FLog.e(ReactConstants.TAG, "Error while loading assets list"); <del> } <del> return false; <del> } <del> <del> private void resetCurrentContext(@Nullable ReactContext reactContext) { <del> if (mCurrentContext == reactContext) { <del> // new context is the same as the old one - do nothing <del> return; <del> } <del> <del> // if currently profiling stop and write the profile file <del> if (mIsCurrentlyProfiling) { <del> mIsCurrentlyProfiling = false; <del> String profileName = (Environment.getExternalStorageDirectory().getPath() + <del> "/profile_" + mProfileIndex + ".json"); <del> mProfileIndex++; <del> Debug.stopMethodTracing(); <del> mCurrentContext.getCatalystInstance().stopProfiler("profile", profileName); <del> } <del> <del> mCurrentContext = reactContext; <del> <del> // Recreate debug overlay controller with new CatalystInstance object <del> if (mDebugOverlayController != null) { <del> mDebugOverlayController.setFpsDebugViewVisible(false); <del> } <del> if (reactContext != null) { <del> mDebugOverlayController = new DebugOverlayController(reactContext); <del> } <del> <del> reloadSettings(); <del> } <del> <del> @Override <del> public void reloadSettings() { <del> reload(); <del> } <del> <del> @Override <del> public void handleReloadJS() { <del> UiThreadUtil.assertOnUiThread(); <del> <del> // dismiss redbox if exists <del> if (mRedBoxDialog != null) { <del> mRedBoxDialog.dismiss(); <del> } <del> <del> ProgressDialog progressDialog = new ProgressDialog(mApplicationContext); <del> progressDialog.setTitle(R.string.catalyst_jsload_title); <del> progressDialog.setMessage(mApplicationContext.getString( <del> mIsUsingJSProxy ? R.string.catalyst_remotedbg_message : R.string.catalyst_jsload_message)); <del> progressDialog.setIndeterminate(true); <del> progressDialog.setCancelable(false); <del> progressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); <del> progressDialog.show(); <del> <del> if (mIsUsingJSProxy) { <del> reloadJSInProxyMode(progressDialog); <del> } else { <del> reloadJSFromServer(progressDialog); <del> } <del> } <del> <del> @Override <del> public void isPackagerRunning(DevServerHelper.PackagerStatusCallback callback) { <del> mDevServerHelper.isPackagerRunning(callback); <del> } <del> <del> private void reloadJSInProxyMode(final ProgressDialog progressDialog) { <del> // When using js proxy, there is no need to fetch JS bundle as proxy executor will do that <del> // anyway <del> mDevServerHelper.launchChromeDevtools(); <del> <del> JavaJSExecutor.Factory factory = new JavaJSExecutor.Factory() { <del> @Override <del> public JavaJSExecutor create() throws Exception { <del> WebsocketJavaScriptExecutor executor = new WebsocketJavaScriptExecutor(); <del> SimpleSettableFuture<Boolean> future = new SimpleSettableFuture<>(); <del> executor.connect( <del> mDevServerHelper.getWebsocketProxyURL(), <del> getExecutorConnectCallback(progressDialog, future)); <del> // TODO(t9349129) Don't use timeout <del> try { <del> future.get(90, TimeUnit.SECONDS); <del> return executor; <del> } catch (ExecutionException e) { <del> throw (Exception) e.getCause(); <del> } catch (InterruptedException | TimeoutException e) { <del> throw new RuntimeException(e); <del> } <del> } <del> }; <del> mReactInstanceCommandsHandler.onReloadWithJSDebugger(factory); <del> } <del> <del> private WebsocketJavaScriptExecutor.JSExecutorConnectCallback getExecutorConnectCallback( <del> final ProgressDialog progressDialog, <del> final SimpleSettableFuture<Boolean> future) { <del> return new WebsocketJavaScriptExecutor.JSExecutorConnectCallback() { <del> @Override <del> public void onSuccess() { <del> future.set(true); <del> progressDialog.dismiss(); <del> } <del> <del> @Override <del> public void onFailure(final Throwable cause) { <del> progressDialog.dismiss(); <del> FLog.e(ReactConstants.TAG, "Unable to connect to remote debugger", cause); <del> future.setException( <del> new IOException( <del> mApplicationContext.getString(R.string.catalyst_remotedbg_error), cause)); <del> } <del> }; <del> } <del> <del> private void reloadJSFromServer(final ProgressDialog progressDialog) { <del> mDevServerHelper.downloadBundleFromURL( <del> new DevServerHelper.BundleDownloadCallback() { <del> @Override <del> public void onSuccess() { <del> progressDialog.dismiss(); <del> UiThreadUtil.runOnUiThread( <del> new Runnable() { <del> @Override <del> public void run() { <del> mReactInstanceCommandsHandler.onJSBundleLoadedFromServer(); <del> } <del> }); <del> } <del> <del> @Override <del> public void onFailure(final Exception cause) { <del> progressDialog.dismiss(); <del> FLog.e(ReactConstants.TAG, "Unable to download JS bundle", cause); <del> UiThreadUtil.runOnUiThread( <del> new Runnable() { <del> @Override <del> public void run() { <del> if (cause instanceof DebugServerException) { <del> DebugServerException debugServerException = (DebugServerException) cause; <del> showNewJavaError(debugServerException.description, cause); <del> } else { <del> showNewJavaError( <del> mApplicationContext.getString(R.string.catalyst_jsload_error), <del> cause); <del> } <del> } <del> }); <del> } <del> }, <del> Assertions.assertNotNull(mJSAppBundleName), <del> mJSBundleTempFile); <del> progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { <del> @Override <del> public void onCancel(DialogInterface dialog) { <del> mDevServerHelper.cancelDownloadBundleFromURL(); <del> } <del> }); <del> progressDialog.setCancelable(true); <del> } <del> <del> private void reload() { <del> // reload settings, show/hide debug overlay if required & start/stop shake detector <del> if (mIsDevSupportEnabled) { <del> // update visibility of FPS debug overlay depending on the settings <del> if (mDebugOverlayController != null) { <del> mDebugOverlayController.setFpsDebugViewVisible(mDevSettings.isFpsDebugEnabled()); <del> } <del> <del> // start shake gesture detector <del> if (!mIsShakeDetectorStarted) { <del> mShakeDetector.start( <del> (SensorManager) mApplicationContext.getSystemService(Context.SENSOR_SERVICE)); <del> mIsShakeDetectorStarted = true; <del> } <del> <del> // register reload app broadcast receiver <del> if (!mIsReceiverRegistered) { <del> IntentFilter filter = new IntentFilter(); <del> filter.addAction(DevServerHelper.getReloadAppAction(mApplicationContext)); <del> mApplicationContext.registerReceiver(mReloadAppBroadcastReceiver, filter); <del> mIsReceiverRegistered = true; <del> } <del> <del> if (mDevSettings.isReloadOnJSChangeEnabled()) { <del> mDevServerHelper.startPollingOnChangeEndpoint( <del> new DevServerHelper.OnServerContentChangeListener() { <del> @Override <del> public void onServerContentChanged() { <del> handleReloadJS(); <del> } <del> }); <del> } else { <del> mDevServerHelper.stopPollingOnChangeEndpoint(); <del> } <del> } else { <del> // hide FPS debug overlay <del> if (mDebugOverlayController != null) { <del> mDebugOverlayController.setFpsDebugViewVisible(false); <del> } <del> <del> // stop shake gesture detector <del> if (mIsShakeDetectorStarted) { <del> mShakeDetector.stop(); <del> mIsShakeDetectorStarted = false; <del> } <del> <del> // unregister app reload broadcast receiver <del> if (mIsReceiverRegistered) { <del> mApplicationContext.unregisterReceiver(mReloadAppBroadcastReceiver); <del> mIsReceiverRegistered = false; <del> } <del> <del> // hide redbox dialog <del> if (mRedBoxDialog != null) { <del> mRedBoxDialog.dismiss(); <del> } <del> <del> // hide dev options dialog <del> if (mDevOptionsDialog != null) { <del> mDevOptionsDialog.dismiss(); <del> } <del> <del> mDevServerHelper.stopPollingOnChangeEndpoint(); <del> } <del> } <del>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DisabledDevSupportManager.java <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> */ <del> <del>package com.facebook.react.devsupport; <del> <del>import com.facebook.react.bridge.ReactContext; <del>import com.facebook.react.bridge.ReadableArray; <del>import com.facebook.react.modules.debug.DeveloperSettings; <del> <del>/** <del> * A dummy implementation of {@link DevSupportManager} to be used in production mode where <del> * development features aren't needed. <del> */ <del>public class DisabledDevSupportManager implements DevSupportManager { <del> <del> @Override <del> public void showNewJavaError(String message, Throwable e) { <del> <del> } <del> <del> @Override <del> public void addCustomDevOption(String optionName, DevOptionHandler optionHandler) { <del> <del> } <del> <del> @Override <del> public void showNewJSError(String message, ReadableArray details, int errorCookie) { <del> <del> } <del> <del> @Override <del> public void updateJSError(String message, ReadableArray details, int errorCookie) { <del> <del> } <del> <del> @Override <del> public void showDevOptionsDialog() { <del> <del> } <del> <del> @Override <del> public void setDevSupportEnabled(boolean isDevSupportEnabled) { <del> <del> } <del> <del> @Override <del> public boolean getDevSupportEnabled() { <del> return false; <del> } <del> <del> @Override <del> public DeveloperSettings getDevSettings() { <del> return null; <del> } <del> <del> @Override <del> public void onNewReactContextCreated(ReactContext reactContext) { <del> <del> } <del> <del> @Override <del> public void onReactInstanceDestroyed(ReactContext reactContext) { <del> <del> } <del> <del> @Override <del> public String getSourceMapUrl() { <del> return null; <del> } <del> <del> @Override <del> public String getSourceUrl() { <del> return null; <del> } <del> <del> @Override <del> public String getJSBundleURLForRemoteDebugging() { <del> return null; <del> } <del> <del> @Override <del> public String getDownloadedJSBundleFile() { <del> return null; <del> } <del> <del> @Override <del> public boolean hasUpToDateJSBundleInCache() { <del> return false; <del> } <del> <del> @Override <del> public void reloadSettings() { <del> <del> } <del> <del> @Override <del> public void handleReloadJS() { <del> <del> } <del> <del> @Override <del> public void isPackagerRunning(DevServerHelper.PackagerStatusCallback callback) { <del> <del> } <del> <del> @Override <del> public void handleException(Exception e) { <del> <del> } <del>}
5
PHP
PHP
fix bug in events
a303d66ae0de84c94d9b09a00b8f9e881f5d6342
<ide><path>laravel/event.php <ide> public static function flush($queue) <ide> // We will simply spin through each payload registered for the event and <ide> // fire the flusher, passing each payloads as we go. This allows all <ide> // the events on the queue to be processed by the flusher easily. <add> if ( ! isset(static::$queued[$queue])) continue; <add> <ide> foreach (static::$queued[$queue] as $key => $payload) <ide> { <ide> array_unshift($payload, $key);
1
Javascript
Javascript
replace class with a factory function
0623cf4dffd49d3bae987764beef2047c6822b58
<ide><path>src/Store.js <del>import invariant from 'invariant'; <del>import isPlainObject from './utils/isPlainObject'; <del> <del>// Don't ever try to handle these action types in your code. They are private. <del>// For any unknown actions, you must return the current state. <del>// If the current state is undefined, you must return the initial state. <del>export const ActionTypes = { <del> INIT: '@@redux/INIT' <del>}; <del> <del>export default class Store { <del> constructor(reducer, initialState) { <del> invariant( <del> typeof reducer === 'function', <del> 'Expected the reducer to be a function.' <del> ); <del> <del> this.state = initialState; <del> this.listeners = []; <del> this.replaceReducer(reducer); <del> } <del> <del> getReducer() { <del> return this.reducer; <del> } <del> <del> replaceReducer(nextReducer) { <del> this.reducer = nextReducer; <del> this.dispatch({ type: ActionTypes.INIT }); <del> } <del> <del> dispatch(action) { <del> invariant( <del> isPlainObject(action), <del> 'Actions must be plain objects. Use custom middleware for async actions.' <del> ); <del> <del> const { reducer } = this; <del> this.state = reducer(this.state, action); <del> this.listeners.forEach(listener => listener()); <del> return action; <del> } <del> <del> getState() { <del> return this.state; <del> } <del> <del> subscribe(listener) { <del> const { listeners } = this; <del> listeners.push(listener); <del> <del> return function unsubscribe() { <del> const index = listeners.indexOf(listener); <del> listeners.splice(index, 1); <del> }; <del> } <del>} <ide><path>src/createStore.js <del>import Store from './Store'; <add>import invariant from 'invariant'; <add>import isPlainObject from './utils/isPlainObject'; <add> <add>// Don't ever try to handle these action types in your code. They are private. <add>// For any unknown actions, you must return the current state. <add>// If the current state is undefined, you must return the initial state. <add>export const ActionTypes = { <add> INIT: '@@redux/INIT' <add>}; <ide> <ide> export default function createStore(reducer, initialState) { <del> const store = new Store(reducer, initialState); <add> invariant( <add> typeof reducer === 'function', <add> 'Expected the reducer to be a function.' <add> ); <add> <add> let currentReducer = null; <add> let currentState = initialState; <add> let listeners = []; <add> <add> function getState() { <add> return currentState; <add> } <add> <add> function subscribe(listener) { <add> listeners.push(listener); <add> <add> return function unsubscribe() { <add> const index = listeners.indexOf(listener); <add> listeners.splice(index, 1); <add> }; <add> } <add> <add> function dispatch(action) { <add> invariant( <add> isPlainObject(action), <add> 'Actions must be plain objects. Use custom middleware for async actions.' <add> ); <add> <add> currentState = currentReducer(currentState, action); <add> listeners.forEach(listener => listener()); <add> return action; <add> } <add> <add> function getReducer() { <add> return currentReducer; <add> } <add> <add> function replaceReducer(nextReducer) { <add> currentReducer = nextReducer; <add> dispatch({ type: ActionTypes.INIT }); <add> } <add> <add> replaceReducer(reducer); <ide> <ide> return { <del> dispatch: ::store.dispatch, <del> subscribe: ::store.subscribe, <del> getState: ::store.getState, <del> getReducer: ::store.getReducer, <del> replaceReducer: ::store.replaceReducer <add> dispatch, <add> subscribe, <add> getState, <add> getReducer, <add> replaceReducer <ide> }; <ide> } <ide><path>src/utils/combineReducers.js <ide> import mapValues from '../utils/mapValues'; <ide> import pick from '../utils/pick'; <ide> import invariant from 'invariant'; <del>import { ActionTypes } from '../Store'; <add>import { ActionTypes } from '../createStore'; <ide> <ide> function getErrorMessage(key, action) { <ide> const actionType = action && action.type; <ide><path>test/utils/combineReducers.spec.js <ide> import expect from 'expect'; <ide> import { combineReducers } from '../../src'; <del>import { ActionTypes } from '../../src/Store'; <add>import { ActionTypes } from '../../src/createStore'; <ide> <ide> describe('Utils', () => { <ide> describe('combineReducers', () => {
4
PHP
PHP
fix some of the ordering issues in postgres
ecd6ca64922f55345d3817ce3e10ec40009cd9ae
<ide><path>tests/Fixture/TagFixture.php <ide> class TagFixture extends TestFixture { <ide> * @var array <ide> */ <ide> public $fields = array( <del> 'id' => ['type' => 'integer'], <add> 'id' => ['type' => 'integer', 'null' => false], <ide> 'name' => ['type' => 'string', 'null' => false], <ide> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]] <ide> ); <ide><path>tests/TestCase/Shell/Task/ModelTaskTest.php <ide> class ModelTaskTest extends TestCase { <ide> public $fixtures = array( <ide> 'core.bake_article', 'core.bake_comment', 'core.bake_articles_bake_tag', <ide> 'core.bake_tag', 'core.user', 'core.category_thread', 'core.number_tree', <del> 'core.counter_cache_user', 'core.counter_cache_post', 'core.articles_tag' <add> 'core.counter_cache_user', 'core.counter_cache_post', <add> 'core.tag', 'core.articles_tag' <ide> ); <ide> <ide> /** <ide><path>tests/TestCase/Shell/Task/TestTaskTest.php <ide> class TestTaskTest extends TestCase { <ide> 'core.article', <ide> 'core.author', <ide> 'core.comment', <del> 'core.articles_tag', <ide> 'core.tag', <add> 'core.articles_tag', <ide> ]; <ide> <ide> /**
3
Python
Python
ignore more np.distutils.log imports
2df41fd07ac43d97c2dfb3c038947d53b82cd4eb
<ide><path>numpy/tests/test_public_api.py <ide> def test_all_modules_are_expected(): <ide> SKIP_LIST_2 = [ <ide> 'numpy.math', <ide> 'numpy.distutils.log.sys', <add> 'numpy.distutils.log.logging', <add> 'numpy.distutils.log.warnings', <ide> 'numpy.doc.constants.re', <ide> 'numpy.doc.constants.textwrap', <ide> 'numpy.lib.emath',
1
Javascript
Javascript
create synthetic events lazily
480626a9e920d5e04194c793a828318102ea4ff4
<ide><path>packages/react-dom/src/events/DOMPluginEventSystem.js <ide> function createDispatchListener( <ide> }; <ide> } <ide> <del>function createDispatchEntry( <del> event: ReactSyntheticEvent, <del> listeners: Array<DispatchListener>, <del>): DispatchEntry { <del> return { <del> event, <del> listeners, <del> }; <del>} <del> <ide> export function accumulateSinglePhaseListeners( <ide> targetFiber: Fiber | null, <del> dispatchQueue: DispatchQueue, <del> event: ReactSyntheticEvent, <add> reactName: string | null, <add> nativeEventType: string, <ide> inCapturePhase: boolean, <ide> accumulateTargetOnly: boolean, <del>): void { <del> const bubbleName = event._reactName; <del> const captureName = bubbleName !== null ? bubbleName + 'Capture' : null; <del> const reactEventName = inCapturePhase ? captureName : bubbleName; <add>): Array<DispatchListener> { <add> const captureName = reactName !== null ? reactName + 'Capture' : null; <add> const reactEventName = inCapturePhase ? captureName : reactName; <ide> const listeners: Array<DispatchListener> = []; <ide> <ide> let instance = targetFiber; <ide> let lastHostComponent = null; <del> const targetType = event.nativeEvent.type; <ide> <ide> // Accumulate all instances and listeners via the target -> root path. <ide> while (instance !== null) { <ide> export function accumulateSinglePhaseListeners( <ide> ); <ide> if (eventHandlerListeners !== null) { <ide> eventHandlerListeners.forEach(entry => { <del> if (entry.type === targetType && entry.capture === inCapturePhase) { <add> if ( <add> entry.type === nativeEventType && <add> entry.capture === inCapturePhase <add> ) { <ide> listeners.push( <ide> createDispatchListener( <ide> instance, <ide> export function accumulateSinglePhaseListeners( <ide> ); <ide> if (eventHandlerListeners !== null) { <ide> eventHandlerListeners.forEach(entry => { <del> if (entry.type === targetType && entry.capture === inCapturePhase) { <add> if ( <add> entry.type === nativeEventType && <add> entry.capture === inCapturePhase <add> ) { <ide> listeners.push( <ide> createDispatchListener( <ide> instance, <ide> export function accumulateSinglePhaseListeners( <ide> } <ide> instance = instance.return; <ide> } <del> if (listeners.length !== 0) { <del> dispatchQueue.push(createDispatchEntry(event, listeners)); <del> } <add> return listeners; <ide> } <ide> <ide> // We should only use this function for: <ide> export function accumulateSinglePhaseListeners( <ide> // phase event listeners (via emulation). <ide> export function accumulateTwoPhaseListeners( <ide> targetFiber: Fiber | null, <del> dispatchQueue: DispatchQueue, <del> event: ReactSyntheticEvent, <del>): void { <del> const bubbleName = event._reactName; <del> const captureName = bubbleName !== null ? bubbleName + 'Capture' : null; <add> reactName: string, <add>): Array<DispatchListener> { <add> const captureName = reactName + 'Capture'; <ide> const listeners: Array<DispatchListener> = []; <ide> let instance = targetFiber; <ide> <ide> export function accumulateTwoPhaseListeners( <ide> // Handle listeners that are on HostComponents (i.e. <div>) <ide> if (tag === HostComponent && stateNode !== null) { <ide> const currentTarget = stateNode; <del> // Standard React on* listeners, i.e. onClick prop <del> if (captureName !== null) { <del> const captureListener = getListener(instance, captureName); <del> if (captureListener != null) { <del> listeners.unshift( <del> createDispatchListener(instance, captureListener, currentTarget), <del> ); <del> } <add> const captureListener = getListener(instance, captureName); <add> if (captureListener != null) { <add> listeners.unshift( <add> createDispatchListener(instance, captureListener, currentTarget), <add> ); <ide> } <del> if (bubbleName !== null) { <del> const bubbleListener = getListener(instance, bubbleName); <del> if (bubbleListener != null) { <del> listeners.push( <del> createDispatchListener(instance, bubbleListener, currentTarget), <del> ); <del> } <add> const bubbleListener = getListener(instance, reactName); <add> if (bubbleListener != null) { <add> listeners.push( <add> createDispatchListener(instance, bubbleListener, currentTarget), <add> ); <ide> } <ide> } <ide> instance = instance.return; <ide> } <del> if (listeners.length !== 0) { <del> dispatchQueue.push(createDispatchEntry(event, listeners)); <del> } <add> return listeners; <ide> } <ide> <ide> function getParent(inst: Fiber | null): Fiber | null { <ide> function accumulateEnterLeaveListenersForEvent( <ide> instance = instance.return; <ide> } <ide> if (listeners.length !== 0) { <del> dispatchQueue.push(createDispatchEntry(event, listeners)); <add> dispatchQueue.push({event, listeners}); <ide> } <ide> } <ide> <ide> export function accumulateEnterLeaveTwoPhaseListeners( <ide> } <ide> <ide> export function accumulateEventHandleNonManagedNodeListeners( <del> dispatchQueue: DispatchQueue, <del> event: ReactSyntheticEvent, <add> reactEventType: DOMEventName, <ide> currentTarget: EventTarget, <ide> inCapturePhase: boolean, <del>): void { <add>): Array<DispatchListener> { <ide> const listeners: Array<DispatchListener> = []; <ide> <ide> const eventListeners = getEventHandlerListeners(currentTarget); <ide> if (eventListeners !== null) { <del> const targetType = ((event.type: any): DOMEventName); <ide> eventListeners.forEach(entry => { <del> if (entry.type === targetType && entry.capture === inCapturePhase) { <add> if (entry.type === reactEventType && entry.capture === inCapturePhase) { <ide> listeners.push( <ide> createDispatchListener(null, entry.callback, currentTarget), <ide> ); <ide> } <ide> }); <ide> } <del> if (listeners.length !== 0) { <del> dispatchQueue.push(createDispatchEntry(event, listeners)); <del> } <add> return listeners; <ide> } <ide> <ide> export function getListenerSetKey( <ide><path>packages/react-dom/src/events/plugins/BeforeInputEventPlugin.js <ide> function extractCompositionEvent( <ide> } <ide> } <ide> <del> const event = new SyntheticCompositionEvent( <del> eventType, <del> domEventName, <del> null, <del> nativeEvent, <del> nativeEventTarget, <del> ); <del> accumulateTwoPhaseListeners(targetInst, dispatchQueue, event); <del> <del> if (fallbackData) { <del> // Inject data generated from fallback path into the synthetic event. <del> // This matches the property of native CompositionEventInterface. <del> event.data = fallbackData; <del> } else { <del> const customData = getDataFromCustomEvent(nativeEvent); <del> if (customData !== null) { <del> event.data = customData; <add> const listeners = accumulateTwoPhaseListeners(targetInst, eventType); <add> if (listeners.length > 0) { <add> const event = new SyntheticCompositionEvent( <add> eventType, <add> domEventName, <add> null, <add> nativeEvent, <add> nativeEventTarget, <add> ); <add> dispatchQueue.push({event, listeners}); <add> if (fallbackData) { <add> // Inject data generated from fallback path into the synthetic event. <add> // This matches the property of native CompositionEventInterface. <add> event.data = fallbackData; <add> } else { <add> const customData = getDataFromCustomEvent(nativeEvent); <add> if (customData !== null) { <add> event.data = customData; <add> } <ide> } <ide> } <ide> } <ide> function extractBeforeInputEvent( <ide> return null; <ide> } <ide> <del> const event = new SyntheticInputEvent( <del> 'onBeforeInput', <del> 'beforeinput', <del> null, <del> nativeEvent, <del> nativeEventTarget, <del> ); <del> accumulateTwoPhaseListeners(targetInst, dispatchQueue, event); <del> event.data = chars; <add> const listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput'); <add> if (listeners.length > 0) { <add> const event = new SyntheticInputEvent( <add> 'onBeforeInput', <add> 'beforeinput', <add> null, <add> nativeEvent, <add> nativeEventTarget, <add> ); <add> dispatchQueue.push({event, listeners}); <add> event.data = chars; <add> } <ide> } <ide> <ide> /** <ide><path>packages/react-dom/src/events/plugins/ChangeEventPlugin.js <ide> function createAndAccumulateChangeEvent( <ide> nativeEvent, <ide> target, <ide> ) { <del> const event = new SyntheticEvent( <del> 'onChange', <del> 'change', <del> null, <del> nativeEvent, <del> target, <del> ); <ide> // Flag this event loop as needing state restore. <ide> enqueueStateRestore(((target: any): Node)); <del> accumulateTwoPhaseListeners(inst, dispatchQueue, event); <add> const listeners = accumulateTwoPhaseListeners(inst, 'onChange'); <add> if (listeners.length > 0) { <add> const event = new SyntheticEvent( <add> 'onChange', <add> 'change', <add> null, <add> nativeEvent, <add> target, <add> ); <add> dispatchQueue.push({event, listeners}); <add> } <ide> } <ide> /** <ide> * For IE shims <ide><path>packages/react-dom/src/events/plugins/SelectEventPlugin.js <ide> function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) { <ide> if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { <ide> lastSelection = currentSelection; <ide> <del> const syntheticEvent = new SyntheticEvent( <del> 'onSelect', <del> 'select', <del> null, <del> nativeEvent, <del> nativeEventTarget, <del> ); <del> syntheticEvent.target = activeElement; <del> <del> accumulateTwoPhaseListeners( <add> const listeners = accumulateTwoPhaseListeners( <ide> activeElementInst, <del> dispatchQueue, <del> syntheticEvent, <add> 'onSelect', <ide> ); <add> if (listeners.length > 0) { <add> const event = new SyntheticEvent( <add> 'onSelect', <add> 'select', <add> null, <add> nativeEvent, <add> nativeEventTarget, <add> ); <add> dispatchQueue.push({event, listeners}); <add> event.target = activeElement; <add> } <ide> } <ide> } <ide> <ide><path>packages/react-dom/src/events/plugins/SimpleEventPlugin.js <ide> function extractEvents( <ide> return; <ide> } <ide> let SyntheticEventCtor = SyntheticEvent; <del> let reactEventType = domEventName; <add> let reactEventType: string = domEventName; <ide> switch (domEventName) { <ide> case 'keypress': <ide> // Firefox creates a keypress event for function keys too. This removes <ide> function extractEvents( <ide> // Unknown event. This is used by createEventHandle. <ide> break; <ide> } <del> const event = new SyntheticEventCtor( <del> reactName, <del> reactEventType, <del> null, <del> nativeEvent, <del> nativeEventTarget, <del> ); <ide> <ide> const inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; <ide> if ( <ide> enableCreateEventHandleAPI && <ide> eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE <ide> ) { <del> accumulateEventHandleNonManagedNodeListeners( <del> dispatchQueue, <del> event, <add> const listeners = accumulateEventHandleNonManagedNodeListeners( <add> // TODO: this cast may not make sense for events like <add> // "focus" where React listens to e.g. "focusin". <add> ((reactEventType: any): DOMEventName), <ide> targetContainer, <ide> inCapturePhase, <ide> ); <add> if (listeners.length > 0) { <add> // Intentionally create event lazily. <add> const event = new SyntheticEventCtor( <add> reactName, <add> reactEventType, <add> null, <add> nativeEvent, <add> nativeEventTarget, <add> ); <add> dispatchQueue.push({event, listeners}); <add> } <ide> } else { <ide> // Some events don't bubble in the browser. <ide> // In the past, React has always bubbled them, but this can be surprising. <ide> function extractEvents( <ide> // This is a breaking change that can wait until React 18. <ide> domEventName === 'scroll'; <ide> <del> accumulateSinglePhaseListeners( <add> const listeners = accumulateSinglePhaseListeners( <ide> targetInst, <del> dispatchQueue, <del> event, <add> reactName, <add> nativeEvent.type, <ide> inCapturePhase, <ide> accumulateTargetOnly, <ide> ); <add> if (listeners.length > 0) { <add> // Intentionally create event lazily. <add> const event = new SyntheticEventCtor( <add> reactName, <add> reactEventType, <add> null, <add> nativeEvent, <add> nativeEventTarget, <add> ); <add> dispatchQueue.push({event, listeners}); <add> } <ide> } <ide> } <ide>
5
Javascript
Javascript
fix art after native -> host rename
769ab715c23f6f1e2e8a917029ea7892f8b36ae9
<ide><path>gulpfile.js <ide> var paths = { <ide> '!src/**/__benchmarks__/**/*.js', <ide> '!src/**/__tests__/**/*.js', <ide> '!src/**/__mocks__/**/*.js', <add> '!src/renderers/art/**/*.js', <ide> '!src/shared/vendor/**/*.js', <ide> ], <ide> lib: 'build/modules', <ide><path>src/renderers/art/ReactART.js <ide> * LICENSE file in the root directory of this source tree. An additional grant <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> * <del> * @providesModule ReactARTFifteen <add> * @providesModule ReactART <ide> */ <ide> <ide> 'use strict'; <ide><path>src/renderers/art/__tests__/ReactART-test.js <ide> 'use strict'; <ide> <ide> jest <del> .unmock('ReactARTFifteen'); <add> .unmock('ReactART'); <ide> <ide> var React = require('React'); <ide> var ReactDOM = require('ReactDOM'); <ide> var TestComponent; <ide> <ide> var Missing = {}; <ide> <del>var ReactART = require('ReactARTFifteen'); <add>var ReactART = require('ReactART'); <ide> var ARTSVGMode = require('art/modes/svg'); <ide> var ARTCurrentMode = require('art/modes/current'); <ide> <ide><path>src/renderers/shared/stack/reconciler/ReactMultiChild.js <ide> if (__DEV__) { <ide> return inst._debugID; <ide> }; <ide> setParentForInstrumentation = function(child) { <del> invariant(child._debugID != null, 'mooooooooooooooooooo'); <ide> if (child._debugID !== 0) { <ide> ReactInstrumentation.debugTool.onSetParent( <ide> child._debugID, <del> getDebugID(this._debugID) <add> getDebugID(this) <ide> ); <ide> } <ide> }; <ide><path>src/renderers/shared/stack/reconciler/instantiateReactComponent.js <ide> function instantiateReactComponent(node) { <ide> // representations. I.e. ART. Once those are updated to use the string <ide> // representation, we can drop this code path. <ide> instance = new element.type(element); <add> <add> // We renamed this. Allow the old name for compat. :( <add> if (!instance.getHostNode) { <add> instance.getHostNode = instance.getNativeNode; <add> } <ide> } else { <ide> instance = new ReactCompositeComponentWrapper(element); <ide> }
5
Ruby
Ruby
create active symlinks for installed formula
f02d81ecbf636aea7bcb842ef6350afe947a4839
<ide><path>Library/Homebrew/build.rb <ide> def install f <ide> f.recursive_deps.uniq.each do |dep| <ide> dep = Formula.factory dep <ide> if dep.keg_only? <del> ENV.prepend 'LDFLAGS', "-L#{dep.lib}" <del> ENV.prepend 'CPPFLAGS', "-I#{dep.include}" <del> ENV.prepend 'PATH', "#{dep.bin}", ':' <add> opt = HOMEBREW_PREFIX/:opt/dep.name <ide> <del> pcdir = dep.lib/'pkgconfig' <add> raise "#{opt} not present\nReinstall #{dep}." unless opt.directory? <add> <add> ENV.prepend 'LDFLAGS', "-L#{opt}/lib" <add> ENV.prepend 'CPPFLAGS', "-I#{opt}/include" <add> ENV.prepend 'PATH', "#{opt}/bin", ':' <add> <add> pcdir = opt/'lib/pkgconfig' <ide> ENV.prepend 'PKG_CONFIG_PATH', pcdir, ':' if pcdir.directory? <ide> <del> acdir = dep.share/'aclocal' <add> acdir = opt/'share/aclocal' <ide> ENV.prepend 'ACLOCAL_PATH', acdir, ':' if acdir.directory? <ide> end <ide> end <ide><path>Library/Homebrew/cmd/uninstall.rb <ide> def uninstall <ide> puts "Uninstalling #{keg}..." <ide> keg.unlink <ide> keg.uninstall <add> rm_opt_link keg.fname <ide> end <ide> else <ide> ARGV.named.each do |name| <ide> def uninstall <ide> end <ide> rack.rmtree <ide> end <add> <add> rm_opt_link name <ide> end <ide> end <ide> rescue MultipleVersionsInstalledError => e <ide> ofail e <ide> puts "Use `brew remove --force #{e.name}` to remove all versions." <ide> end <add> <add> def rm_opt_link name <add> optlink = HOMEBREW_PREFIX/:opt/name <add> optlink.unlink if optlink.symlink? <add> end <add> <ide> end <ide><path>Library/Homebrew/formula.rb <ide> def build <ide> self.class.build <ide> end <ide> <add> def opt_prefix; HOMEBREW_PREFIX/:opt/name end <add> <ide> # Use the @active_spec to detect the download strategy. <ide> # Can be overriden to force a custom download strategy <ide> def download_strategy <ide><path>Library/Homebrew/formula_installer.rb <ide> def caveats <ide> def finish <ide> ohai 'Finishing up' if ARGV.verbose? <ide> <del> unless f.keg_only? <add> if f.keg_only? <add> begin <add> Keg.new(f.prefix).optlink <add> rescue Exception => e <add> onoe "Failed to create: #{f.opt_prefix}" <add> puts "Things that depend on #{f} will probably not build." <add> end <add> else <ide> link <del> check_PATH <add> check_PATH unless f.keg_only? <ide> end <add> <ide> fix_install_names <ide> <ide> ohai "Summary" if ARGV.verbose? or show_summary_heading <ide><path>Library/Homebrew/keg.rb <ide> def unlink <ide> Find.prune if src.directory? <ide> end <ide> end <del> linked_keg_record.unlink if linked_keg_record.exist? <add> linked_keg_record.unlink if linked_keg_record.symlink? <ide> n <ide> end <ide> <ide> def link mode=nil <ide> <ide> linked_keg_record.make_relative_symlink(self) unless mode == :dryrun <ide> <add> optlink unless mode == :dryrun <add> <ide> return $n + $d <add> rescue Exception <add> opoo "Could not link #{fname}. Unlinking..." <add> unlink <add> raise <add> end <add> <add> def optlink <add> from = HOMEBREW_PREFIX/:opt/fname <add> if from.symlink? <add> from.delete <add> elsif from.directory? <add> from.rmdir <add> elsif from.exist? <add> from.delete <add> end <add> from.make_relative_symlink(self) <ide> end <ide> <ide> protected <ide><path>Library/Homebrew/keg_fix_install_names.rb <ide> def bad_install_names_for file <ide> end <ide> <ide> # the shortpath ensures that library upgrades don’t break installed tools <del> shortpath = HOMEBREW_PREFIX + Pathname.new(file).relative_path_from(self) <del> id = if shortpath.exist? then shortpath else file end <add> relative_path = Pathname.new(file).relative_path_from(self) <add> shortpath = HOMEBREW_PREFIX.join(relative_path) <add> id = if shortpath.exist? <add> shortpath <add> else <add> "#{HOMEBREW_PREFIX}/opt/#{fname}/#{relative_path}" <add> end <ide> <ide> yield id, install_names <ide> end
6
Javascript
Javascript
add unit tests for `ember-glimmer/utils/iterable`
30cf11aba1f8cbc0827ec42b600e14fb1b5b49b9
<ide><path>packages/ember-glimmer/tests/unit/utils/iterable-test.js <add>import Ember from 'ember'; <add>import { moduleFor, TestCase } from 'ember-glimmer/tests/utils/test-case'; <add>import iterableFor from 'ember-glimmer/utils/iterable'; <add>import { UpdatableReference } from 'ember-glimmer/utils/references'; <add>import eachIn from 'ember-glimmer/helpers/each-in'; <add>import { EvaluatedPositionalArgs } from 'glimmer-runtime'; <add> <add>const ITERATOR_KEY_GUID = 'be277757-bbbe-4620-9fcb-213ef433cca2'; <add> <add>moduleFor('Iterable', class extends TestCase { <add> ['@test iterates over an array']() { <add> let iterator = iteratorForArray(['foo', 'bar']); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'foo', memo: 0, value: 'foo' }); <add> this.assert.deepEqual(iterator.next(), { key: 'bar', memo: 1, value: 'bar' }); <add> } <add> <add> ['@test iterates over an `Ember.A`']() { <add> let iterator = iteratorForArray(Ember.A(['foo', 'bar'])); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'foo', memo: 0, value: 'foo' }); <add> this.assert.deepEqual(iterator.next(), { key: 'bar', memo: 1, value: 'bar' }); <add> } <add> <add> ['@test returns `null` when out of items']() { <add> let iterator = iteratorForArray(['foo']); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'foo', memo: 0, value: 'foo' }); <add> this.assert.deepEqual(iterator.next(), null); <add> } <add> <add> ['@test iterates over an array with indices as keys']() { <add> let iterator = iteratorForArray(['foo', 'bar'], '@index'); <add> <add> this.assert.deepEqual(iterator.next(), { key: '0', memo: 0, value: 'foo' }); <add> this.assert.deepEqual(iterator.next(), { key: '1', memo: 1, value: 'bar' }); <add> } <add> <add> ['@test iterates over an array with identities as keys']() { <add> let iterator = iteratorForArray(['foo', 'bar'], '@identity'); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'foo', memo: 0, value: 'foo' }); <add> this.assert.deepEqual(iterator.next(), { key: 'bar', memo: 1, value: 'bar' }); <add> } <add> <add> ['@test iterates over an array with arbitrary properties as keys']() { <add> let iterator = iteratorForArray([{ k: 'first', v: 'foo' }, { k: 'second', v: 'bar' }], 'k'); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'first', memo: 0, value: { k: 'first', v: 'foo' } }); <add> this.assert.deepEqual(iterator.next(), { key: 'second', memo: 1, value: { k: 'second', v: 'bar' } }); <add> } <add> <add> ['@test errors on `#next` with an undefined ref']() { <add> let iterator = iteratorForArray(undefined); <add> <add> this.assert.expect(1); <add> <add> try { <add> iterator.next(); <add> } catch({ message }) { <add> this.assert.equal(message, 'Cannot call next() on an empty iterator'); <add> } <add> } <add> <add> ['@test errors on `#next` with a null ref']() { <add> let iterator = iteratorForArray(null); <add> <add> this.assert.expect(1); <add> <add> try { <add> iterator.next(); <add> } catch({ message }) { <add> this.assert.equal(message, 'Cannot call next() on an empty iterator'); <add> } <add> } <add> <add> ['@test errors on `#next` with an invalid ref type']() { <add> let iterator = iteratorForArray('string'); <add> <add> this.assert.expect(1); <add> <add> try { <add> iterator.next(); <add> } catch({ message }) { <add> this.assert.equal(message, 'Cannot call next() on an empty iterator'); <add> } <add> } <add> <add> ['@test errors on `#next` with an empty array']() { <add> let iterator = iteratorForArray([]); <add> <add> this.assert.expect(1); <add> <add> try { <add> iterator.next(); <add> } catch({ message }) { <add> this.assert.equal(message, 'Cannot call next() on an empty iterator'); <add> } <add> } <add> <add> ['@test iterates over an object\'s own properties']() { <add> let iterator = iteratorForObject({ first: 'foo', second: 'bar' }); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'first', memo: 'first', value: 'foo' }); <add> this.assert.deepEqual(iterator.next(), { key: 'second', memo: 'second', value: 'bar' }); <add> } <add> <add> ['@test iterates over an object\'s own properties with indices as keys']() { <add> let iterator = iteratorForObject({ first: 'foo', second: 'bar' }, '@index'); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'first', memo: 'first', value: 'foo' }); <add> this.assert.deepEqual(iterator.next(), { key: 'second', memo: 'second', value: 'bar' }); <add> } <add> <add> ['@test iterates over an object\'s own properties with identities as keys']() { <add> let iterator = iteratorForObject({ first: 'foo', second: 'bar' }, '@identity'); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'foo', memo: 'first', value: 'foo' }); <add> this.assert.deepEqual(iterator.next(), { key: 'bar', memo: 'second', value: 'bar' }); <add> } <add> <add> ['@test iterates over an object\'s own properties with arbitrary properties as keys']() { <add> let iterator = iteratorForObject({ first: { k: 'uno', v: 'foo' }, second: { k: 'dos', v: 'bar' } }, 'k'); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'uno', memo: 'first', value: { k: 'uno', v: 'foo' } }); <add> this.assert.deepEqual(iterator.next(), { key: 'dos', memo: 'second', value: { k: 'dos', v: 'bar' } }); <add> } <add> <add> ['@test each-in errors on `#next` with an undefined ref']() { <add> let iterator = iteratorForObject(undefined); <add> <add> this.assert.expect(1); <add> <add> try { <add> iterator.next(); <add> } catch({ message }) { <add> this.assert.equal(message, 'Cannot call next() on an empty iterator'); <add> } <add> } <add> <add> ['@test each-in errors on `#next` with a null ref']() { <add> let iterator = iteratorForObject(null); <add> <add> this.assert.expect(1); <add> <add> try { <add> iterator.next(); <add> } catch({ message }) { <add> this.assert.equal(message, 'Cannot call next() on an empty iterator'); <add> } <add> } <add> <add> ['@test each-in errors on `#next` with an invalid ref type']() { <add> let iterator = iteratorForObject('string'); <add> <add> this.assert.expect(1); <add> <add> try { <add> iterator.next(); <add> } catch({ message }) { <add> this.assert.equal(message, 'Cannot call next() on an empty iterator'); <add> } <add> } <add> <add> ['@test ensures keys are unique']() { <add> let iterator = iteratorForArray([{ k: 'qux', v: 'foo' }, { k: 'qux', v: 'bar' }, { k: 'qux', v: 'baz' }], 'k'); <add> <add> this.assert.deepEqual(iterator.next(), { key: 'qux', memo: 0, value: { k: 'qux', v: 'foo' } }); <add> this.assert.deepEqual(iterator.next(), { key: `qux${ITERATOR_KEY_GUID}1`, memo: 1, value: { k: 'qux', v: 'bar' } }); <add> this.assert.deepEqual(iterator.next(), { key: `qux${ITERATOR_KEY_GUID}2`, memo: 2, value: { k: 'qux', v: 'baz' } }); <add> } <add>}); <add> <add>function iteratorForArray(arr, keyPath) { <add> let ref = new UpdatableReference(arr); <add> let iterable = iterableFor(ref, keyPath); <add> <add> return iterable.iterate(); <add>} <add> <add>function iteratorForObject(obj, keyPath) { <add> let vm = null; <add> let positionalArgs = EvaluatedPositionalArgs.create([new UpdatableReference(obj)]); <add> let ref = eachIn(vm, { positional: positionalArgs }); <add> let iterable = iterableFor(ref, keyPath); <add> <add> return iterable.iterate(); <add>}
1
Javascript
Javascript
update varriable names
ae85dbe2e0bbf7835486b56550a3a20e5a36c6bd
<ide><path>src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl.js <ide> export default /* glsl */` <ide> #if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) <ide> <del> if ( skipLogDepth == 1.0 ) { <del> <del> gl_FragDepthEXT = gl_FragCoord.z; <del> <del> } else { <del> <del> gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5; <del> <del> } <add> gl_FragDepthEXT = vIsPerspective == 1.0 ? log2( vFragDepth ) * logDepthBufFC * 0.5 : gl_FragCoord.z; <ide> <ide> #endif <ide> `; <ide><path>src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl.js <ide> export default /* glsl */` <ide> <ide> uniform float logDepthBufFC; <ide> varying float vFragDepth; <del> varying float skipLogDepth; <add> varying float vIsPerspective; <ide> <ide> #endif <ide> `; <ide><path>src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl.js <ide> export default /* glsl */` <ide> #ifdef USE_LOGDEPTHBUF_EXT <ide> <ide> varying float vFragDepth; <del> varying float skipLogDepth; <add> varying float vIsPerspective; <ide> <ide> #else <ide> <ide><path>src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl.js <ide> export default /* glsl */` <ide> #ifdef USE_LOGDEPTHBUF_EXT <ide> <ide> vFragDepth = 1.0 + gl_Position.w; <del> skipLogDepth = isPerspectiveMatrix( projectionMatrix ) ? 0.0 : 1.0; <add> vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); <ide> <ide> #else <ide>
4
PHP
PHP
fix doc block sentence
67927833606e68e964c196edd39abe374bb48e8c
<ide><path>src/Filesystem/File.php <ide> public function copy($dest, $overwrite = true) <ide> } <ide> <ide> /** <del> * Get the mime type of the file. Uses the finfo extension if <del> * its available, otherwise falls back to mime_content_type <add> * Gets the mime type of the file. Uses the finfo extension if <add> * it's available, otherwise falls back to mime_content_type(). <ide> * <ide> * @return false|string The mimetype of the file, or false if reading fails. <ide> */
1
Javascript
Javascript
remove chai from a body
83ef4ebee13be4900aa94318df91f147b531c387
<ide><path>client/gatsby-ssr.js <ide> export const onRenderBody = ({ setHeadComponents, setPostBodyComponents }) => { <ide> /> <ide> ) : null, <ide> /* eslint-enable max-len */ <del> <script <del> async={true} <del> key='chai-CDN' <del> src='https://cdnjs.cloudflare.com/ajax/libs/chai/4.1.2/chai.min.js' <del> />, <ide> <script <ide> async={true} <ide> key='gtag-script'
1
Javascript
Javascript
check asset existence to detect gltf version
6bf789c618fa7fc67b34419496135ff2d14718e4
<ide><path>examples/js/loaders/GLTF2Loader.js <ide> THREE.GLTF2Loader = ( function () { <ide> <ide> var json = JSON.parse( content ); <ide> <del> if ( json.asset.version[0] < 2 ) { <add> if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { <ide> <ide> onError( new Error( 'THREE.GLTF2Loader: Legacy glTF detected. Use THREE.GLTFLoader instead.' ) ); <ide> return;
1
Text
Text
improve wording in documentation change
de51b0e70728396c5adffde39ebb55c10cc61204
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> The best way to be sure that your application still works after upgrading is to <ide> <ide> ### The Upgrade Process <ide> <del>When changing Rails versions, it's best to move slowly, one minor version at a time, in order to make good use of the deprecation warnings. Rails version numbers are in the form Major.Minor.Patch. Major and Minor versions change the API which means you will probably need to change your code. Patch versions are just bug fixes that don't change the API. <add>When changing Rails versions, it's best to move slowly, one minor version at a time, in order to make good use of the deprecation warnings. Rails version numbers are in the form Major.Minor.Patch. Major and Minor versions are allowed to make changes to the public API, so this may cause errors in your application. Patch versions only include bug fixes, and don't change any public API. <ide> <ide> The process should go as follows: <ide> <ide> The process should go as follows: <ide> 1. Fix tests and deprecated features <ide> 1. Move to the latest patch version of the next minor version <ide> <del>Repeat this process until you reach your target Rails version. Each time you move versions, you will need to change the Rails version number in the Gemfile (and possibly other Gem versions) and run `bundle update`. Then run the Update rake task mentioned below to update configuration files, then run your tests. <add>Repeat this process until you reach your target Rails version. Each time you move versions, you will need to change the Rails version number in the Gemfile (and possibly other gem versions) and run `bundle update`. Then run the Update rake task mentioned below to update configuration files, then run your tests. <ide> <del>You can find a list of all the Rails Gem versions [here](https://rubygems.org/gems/rails/versions). <add>You can find a list of all released Rails versions [here](https://rubygems.org/gems/rails/versions). <ide> <ide> ### Ruby Versions <ide>
1
Text
Text
fix typo in readme
3c33499f8739fb953733c76a2fced1ee943f8b90
<ide><path>README.md <ide> The repository further comprises: <ide> - [`run_lm_finetuning.py`](./examples/run_lm_finetuning.py) - Show how to fine-tune an instance of `BertForPretraining' on a target text corpus. <ide> <ide> - One example on how to use **OpenAI GPT** (in the [`examples` folder](./examples)): <del> - [`openai_gpt_train.py`](./examples/openai_gpt_train.py) - Show how to fine-tune an instance of `OpenGPTDoubleHeadsModel` on the RocStories task. <add> - [`run_openai_gpt.py`](./examples/run_openai_gpt.py) - Show how to fine-tune an instance of `OpenGPTDoubleHeadsModel` on the RocStories task. <ide> <del>- Two examples on how to use **Transformer-XL** (in the [`examples` folder](./examples)): <del> - [`transfo_xl_train.py`](./examples/transfo_xl_train.py) - Show how to train and exaluate an instance of `TransfoXLModel` on WikiText 103, <del> - [`transfo_xl_eval.py`](./examples/transfo_xl_eval.py) - Simply exaluate a pre-trained model of `TransfoXLModel` on WikiText 103. <add>- One example on how to use **Transformer-XL** (in the [`examples` folder](./examples)): <add> - [`run_transfo_xl.py`](./examples/run_transfo_xl.py) - Show how to load and evaluate a pre-trained model of `TransfoXLLMHeadModel` on WikiText 103. <ide> <ide> These examples are detailed in the [Examples](#examples) section of this readme. <ide>
1
Javascript
Javascript
test no-op rerender
25cc24018b02c9fd826ea52a84acc3a3b5910a4c
<ide><path>packages/ember-glimmer/tests/integration/helpers/concat-test.js <ide> moduleFor('Helpers test: {{concat}}', class extends RenderingTest { <ide> <ide> this.assertText('onetwo'); <ide> <add> this.inZone(() => this.rerender()); <add> <add> this.assertText('onetwo'); <add> <ide> this.inZone(() => set(this.context, 'first', 'three')); <ide> <ide> this.assertText('threetwo'); <ide> moduleFor('Helpers test: {{concat}}', class extends RenderingTest { <ide> <ide> this.assertText('onetwothreefour'); <ide> <add> this.inZone(() => this.rerender()); <add> <add> this.assertText('onetwothreefour'); <add> <ide> this.inZone(() => { <ide> set(this.context, 'first', 'five'); <ide> set(this.context, 'third', 'six'); <ide> moduleFor('Helpers test: {{concat}}', class extends RenderingTest { <ide> <ide> this.assertText('Truthy!'); <ide> <add> this.inZone(() => this.rerender()); <add> <add> this.assertText('Truthy!'); <add> <ide> this.inZone(() => set(this.context, 'first', 'three')); <ide> <ide> this.assertText('False');
1
Ruby
Ruby
show fs leak result
ebd0f345619b6fd76751275b43a97d5ac5e11b76
<ide><path>Library/Homebrew/cmd/tests.rb <ide> def tests <ide> system("bundle", "install", "--path", "vendor/bundle") <ide> system "bundle", "exec", "rake", "test" <ide> Homebrew.failed = !$?.success? <add> if (fs_leak_log = HOMEBREW_LIBRARY/"Homebrew/test/fs_leak_log").file? <add> fs_leak_log_content = fs_leak_log.read <add> unless fs_leak_log_content.empty? <add> opoo "File leak is detected" <add> puts fs_leak_log_content <add> Homebrew.failed = true <add> end <add> end <ide> end <ide> end <ide> end
1
PHP
PHP
add missing import
1e597bede5d5e78ccf598b6ab18bdeeb72fc8ffb
<ide><path>src/TestSuite/TestCase.php <ide> use Cake\Utility\Inflector; <ide> use PHPUnit\Framework\TestCase as BaseTestCase; <ide> use ReflectionClass; <add>use ReflectionException; <ide> use RuntimeException; <ide> <ide> /**
1
Ruby
Ruby
define ruby_path for tests
9013b3a0c9c35411ae8c788ab5e104735a99fde2
<ide><path>Library/Homebrew/global.rb <ide> def mkpath <ide> <ide> HOMEBREW_LOGS = Pathname.new('~/Library/Logs/Homebrew/').expand_path <ide> <del>RUBY_CONFIG = RbConfig::CONFIG <del>RUBY_BIN = Pathname.new("#{RUBY_CONFIG['bindir']}") <del>RUBY_PATH = RUBY_BIN/RUBY_CONFIG['ruby_install_name'] + RUBY_CONFIG['EXEEXT'] <add>RUBY_BIN = Pathname.new("#{RbConfig::CONFIG['bindir']}") <add>RUBY_PATH = RUBY_BIN + RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'] <ide> <ide> if RUBY_PLATFORM =~ /darwin/ <ide> MACOS_FULL_VERSION = `/usr/bin/sw_vers -productVersion`.chomp <ide><path>Library/Homebrew/test/testing_env.rb <ide> require 'extend/string' <ide> require 'exceptions' <ide> require 'utils' <add>require 'rbconfig' <ide> <ide> # Constants normally defined in global.rb <ide> HOMEBREW_PREFIX = Pathname.new('/private/tmp/testbrew/prefix') <ide> HOMEBREW_CURL_ARGS = '-fsLA' <ide> HOMEBREW_VERSION = '0.9-test' <ide> <add>RUBY_BIN = Pathname.new("#{RbConfig::CONFIG['bindir']}") <add>RUBY_PATH = RUBY_BIN + RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'] <add> <ide> MACOS = true <ide> MACOS_VERSION = ENV.fetch('MACOS_VERSION', 10.6) <ide> MACOS_FULL_VERSION = '10.6.8'
2
Python
Python
add full_output to f2py.compile
9fa7fee0ad8d23bd36ef51b0ec02cf2811f1eec6
<ide><path>numpy/f2py/__init__.py <ide> def compile(source, <ide> extra_args='', <ide> verbose=True, <ide> source_fn=None, <del> extension='.f' <add> extension='.f', <add> full_output=False <ide> ): <ide> """ <ide> Build extension module from a Fortran 77 source string with f2py. <ide> def compile(source, <ide> <ide> .. versionadded:: 1.11.0 <ide> <add> full_output : bool, optional <add> If True, return a `subprocess.CompletedProcess` containing <add> the stdout and stderr of the compile process, instead of just <add> the status code. <add> <add> .. versionadded:: 1.20.0 <add> <add> <ide> Returns <ide> ------- <del> result : int <del> 0 on success <add> result : int or `subprocess.CompletedProcess` <add> 0 on success, or a `subprocess.CompletedProcess` if <add> ``full_output=True`` <ide> <ide> Examples <ide> -------- <ide> def compile(source, <ide> '-c', <ide> 'import numpy.f2py as f2py2e;f2py2e.main()'] + args <ide> try: <del> output = subprocess.check_output(c) <del> except subprocess.CalledProcessError as exc: <del> status = exc.returncode <del> output = '' <add> cp = subprocess.run(c, stdout=subprocess.PIPE, <add> stderr=subprocess.PIPE) <ide> except OSError: <ide> # preserve historic status code used by exec_command() <del> status = 127 <del> output = '' <del> else: <del> status = 0 <del> output = output.decode() <add> cp = subprocess.CompletedProcess(c, 127, stdout='', stderr='') <ide> if verbose: <del> print(output) <add> print(cp.stdout.decode()) <ide> finally: <ide> if source_fn is None: <ide> os.remove(fname) <del> return status <add> <add> if full_output: <add> return cp <add> else: <add> return cp.returncode <ide> <ide> from numpy._pytesttester import PytestTester <ide> test = PytestTester(__name__)
1
Javascript
Javascript
fix historylocation test for static site testing
cdb81fab3e9697404666c98fdaf087f616d8113f
<ide><path>packages/ember/tests/routing/basic_test.js <ide> test("Router accounts for rootURL on page load when using history location", fun <ide> <ide> test("HistoryLocation has the correct rootURL on initState and webkit doesn't fire popstate on page load", function() { <ide> expect(2); <del> var rootURL = window.location.pathname + 'app', <add> var rootURL = window.location.pathname, <ide> history, <ide> HistoryTestLocation; <ide>
1
PHP
PHP
remove message from assertsame
11967881bd88a543702277129af1719f0750f1cd
<ide><path>tests/TestCase/Routing/Route/RedirectRouteTest.php <ide> public function testSetStatus() <ide> { <ide> $route = new RedirectRoute('/home', ['controller' => 'posts']); <ide> $result = $route->setStatus(302); <del> $this->assertSame($result, $route, 'Should return this'); <add> $this->assertSame($result, $route); <ide> $this->assertEquals(302, $route->options['status']); <ide> } <ide> }
1
Ruby
Ruby
fix rubocop warnings
00f5aa81f2b2e5c29d6afdeb7a4025a4620e7df7
<ide><path>Library/Homebrew/os/mac/version.rb <ide> class Version < ::Version <ide> :lion => "10.7", <ide> :snow_leopard => "10.6", <ide> :leopard => "10.5", <del> :tiger => "10.4" <del> } <add> :tiger => "10.4", <add> }.freeze <ide> <ide> def self.from_symbol(sym) <ide> str = SYMBOLS.fetch(sym) do
1