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 |
|---|---|---|---|---|---|
Text | Text | remove a wrong remark in the buffer.md | ae2b19687bd33804f48b74129c3d51994a984c60 | <ide><path>doc/api/buffer.md
<ide> added: v6.0.0
<ide> -->
<ide>
<ide> * `value` {String | Buffer | Integer} What to search for
<del>* `byteOffset` {Integer} Where to begin searching in `buf` (not inclusive).
<add>* `byteOffset` {Integer} Where to begin searching in `buf`.
<ide> **Default:** [`buf.length`]
<ide> * `encoding` {String} If `value` is a string, this is its encoding.
<ide> **Default:** `'utf8'` | 1 |
Javascript | Javascript | rebuild example modules | 912f8c5d83dc65a93055156efbf482c45cc3be3a | <ide><path>examples/jsm/controls/OrbitControls.js
<ide> var OrbitControls = function ( object, domElement ) {
<ide> document.removeEventListener( 'mousemove', onMouseMove, false );
<ide> document.removeEventListener( 'mouseup', onMouseUp, false );
<ide>
<del> window.removeEventListener( 'keydown', onKeyDown, false );
<add> scope.domElement.removeEventListener( 'keydown', onKeyDown, false );
<ide>
<ide> //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
<ide>
<ide> var OrbitControls = function ( object, domElement ) {
<ide> scope.domElement.addEventListener( 'touchend', onTouchEnd, false );
<ide> scope.domElement.addEventListener( 'touchmove', onTouchMove, false );
<ide>
<del> window.addEventListener( 'keydown', onKeyDown, false );
<add> scope.domElement.addEventListener( 'keydown', onKeyDown, false );
<add>
<add> // make sure element can receive keys.
<add>
<add> if ( scope.domElement.tabIndex === -1 ) {
<add>
<add> scope.domElement.tabIndex = 0;
<add>
<add> }
<ide>
<ide> // force an update at start
<ide> | 1 |
Javascript | Javascript | fix ie11 prefetching | 69a34dd7787dc44bd4731c9f9816ee428dbaccd3 | <ide><path>packages/next/client/page-loader.js
<ide> import mitt from '../next-server/lib/mitt'
<ide>
<del>function hasPrefetch(link) {
<add>function hasRel(rel, link) {
<ide> try {
<ide> link = document.createElement('link')
<del> return link.relList.supports('prefetch')
<add> return link.relList.supports(rel)
<ide> } catch {}
<ide> }
<ide>
<del>const relPrefetch = hasPrefetch()
<del> ? // https://caniuse.com/#feat=link-rel-prefetch
<del> // IE 11, Edge 12+, nearly all evergreen
<del> 'prefetch'
<del> : // https://caniuse.com/#feat=link-rel-preload
<del> // macOS and iOS (Safari does not support prefetch)
<del> 'preload'
<add>const relPrefetch =
<add> hasRel('preload') && !hasRel('prefetch')
<add> ? // https://caniuse.com/#feat=link-rel-preload
<add> // macOS and iOS (Safari does not support prefetch)
<add> 'preload'
<add> : // https://caniuse.com/#feat=link-rel-prefetch
<add> // IE 11, Edge 12+, nearly all evergreen
<add> 'prefetch'
<ide>
<ide> const hasNoModule = 'noModule' in document.createElement('script')
<ide> | 1 |
Python | Python | introduce a mobilenetv2+fpn backbone for centernet | 04c56a0354f7471d1ece5defcabea56f471b3454 | <ide><path>research/object_detection/builders/model_builder.py
<ide> if tf_version.is_tf2():
<ide> from object_detection.models import center_net_hourglass_feature_extractor
<ide> from object_detection.models import center_net_mobilenet_v2_feature_extractor
<add> from object_detection.models import center_net_mobilenet_v2_fpn_feature_extractor
<ide> from object_detection.models import center_net_resnet_feature_extractor
<ide> from object_detection.models import center_net_resnet_v1_fpn_feature_extractor
<ide> from object_detection.models import faster_rcnn_inception_resnet_v2_keras_feature_extractor as frcnn_inc_res_keras
<ide> }
<ide>
<ide> CENTER_NET_EXTRACTOR_FUNCTION_MAP = {
<del> 'resnet_v2_50': center_net_resnet_feature_extractor.resnet_v2_50,
<del> 'resnet_v2_101': center_net_resnet_feature_extractor.resnet_v2_101,
<add> 'resnet_v2_50':
<add> center_net_resnet_feature_extractor.resnet_v2_50,
<add> 'resnet_v2_101':
<add> center_net_resnet_feature_extractor.resnet_v2_101,
<ide> 'resnet_v1_18_fpn':
<ide> center_net_resnet_v1_fpn_feature_extractor.resnet_v1_18_fpn,
<ide> 'resnet_v1_34_fpn':
<ide> center_net_hourglass_feature_extractor.hourglass_104,
<ide> 'mobilenet_v2':
<ide> center_net_mobilenet_v2_feature_extractor.mobilenet_v2,
<add> 'mobilenet_v2_fpn':
<add> center_net_mobilenet_v2_fpn_feature_extractor.mobilenet_v2_fpn,
<ide> }
<ide>
<ide> FEATURE_EXTRACTOR_MAPS = [
<ide><path>research/object_detection/models/center_net_mobilenet_v2_feature_extractor.py
<ide> def __init__(self,
<ide>
<ide> output = self._network(self._network.input)
<ide>
<del> # TODO(nkhadke): Try out MobileNet+FPN next (skip connections are cheap and
<del> # should help with performance).
<ide> # MobileNet by itself transforms a 224x224x3 volume into a 7x7x1280, which
<ide> # leads to a stride of 32. We perform upsampling to get it to a target
<ide> # stride of 4.
<ide><path>research/object_detection/models/center_net_mobilenet_v2_fpn_feature_extractor.py
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""MobileNet V2[1] + FPN[2] feature extractor for CenterNet[3] meta architecture.
<add>
<add>[1]: https://arxiv.org/abs/1801.04381
<add>[2]: https://arxiv.org/abs/1612.03144.
<add>[3]: https://arxiv.org/abs/1904.07850
<add>"""
<add>
<add>import tensorflow.compat.v1 as tf
<add>
<add>from object_detection.meta_architectures import center_net_meta_arch
<add>from object_detection.models.keras_models import mobilenet_v2 as mobilenetv2
<add>
<add>
<add>_MOBILENET_V2_FPN_SKIP_LAYERS = [
<add> 'block_2_add', 'block_5_add', 'block_9_add', 'out_relu'
<add>]
<add>
<add>
<add>class CenterNetMobileNetV2FPNFeatureExtractor(
<add> center_net_meta_arch.CenterNetFeatureExtractor):
<add> """The MobileNet V2 with FPN skip layers feature extractor for CenterNet."""
<add>
<add> def __init__(self,
<add> mobilenet_v2_net,
<add> channel_means=(0., 0., 0.),
<add> channel_stds=(1., 1., 1.),
<add> bgr_ordering=False):
<add> """Intializes the feature extractor.
<add>
<add> Args:
<add> mobilenet_v2_net: The underlying mobilenet_v2 network to use.
<add> channel_means: A tuple of floats, denoting the mean of each channel
<add> which will be subtracted from it.
<add> channel_stds: A tuple of floats, denoting the standard deviation of each
<add> channel. Each channel will be divided by its standard deviation value.
<add> bgr_ordering: bool, if set will change the channel ordering to be in the
<add> [blue, red, green] order.
<add> """
<add>
<add> super(CenterNetMobileNetV2FPNFeatureExtractor, self).__init__(
<add> channel_means=channel_means,
<add> channel_stds=channel_stds,
<add> bgr_ordering=bgr_ordering)
<add> self._network = mobilenet_v2_net
<add>
<add> output = self._network(self._network.input)
<add>
<add> # Add pyramid feature network on every layer that has stride 2.
<add> skip_outputs = [
<add> self._network.get_layer(skip_layer_name).output
<add> for skip_layer_name in _MOBILENET_V2_FPN_SKIP_LAYERS
<add> ]
<add> self._fpn_model = tf.keras.models.Model(
<add> inputs=self._network.input, outputs=skip_outputs)
<add> fpn_outputs = self._fpn_model(self._network.input)
<add>
<add> # Construct the top-down feature maps -- we start with an output of
<add> # 7x7x1280, which we continually upsample, apply a residual on and merge.
<add> # This results in a 56x56x24 output volume.
<add> top_layer = fpn_outputs[-1]
<add> residual_op = tf.keras.layers.Conv2D(
<add> filters=64, kernel_size=1, strides=1, padding='same')
<add> top_down = residual_op(top_layer)
<add>
<add> num_filters_list = [64, 32, 24]
<add> for i, num_filters in enumerate(num_filters_list):
<add> level_ind = len(num_filters_list) - 1 - i
<add> # Upsample.
<add> upsample_op = tf.keras.layers.UpSampling2D(2, interpolation='nearest')
<add> top_down = upsample_op(top_down)
<add>
<add> # Residual (skip-connection) from bottom-up pathway.
<add> residual_op = tf.keras.layers.Conv2D(
<add> filters=num_filters, kernel_size=1, strides=1, padding='same')
<add> residual = residual_op(fpn_outputs[level_ind])
<add>
<add> # Merge.
<add> top_down = top_down + residual
<add> next_num_filters = num_filters_list[i + 1] if i + 1 <= 2 else 24
<add> conv = tf.keras.layers.Conv2D(
<add> filters=next_num_filters, kernel_size=3, strides=1, padding='same')
<add> top_down = conv(top_down)
<add> top_down = tf.keras.layers.BatchNormalization()(top_down)
<add> top_down = tf.keras.layers.ReLU()(top_down)
<add>
<add> output = top_down
<add>
<add> self._network = tf.keras.models.Model(
<add> inputs=self._network.input, outputs=output)
<add>
<add> def preprocess(self, resized_inputs):
<add> resized_inputs = super(CenterNetMobileNetV2FPNFeatureExtractor,
<add> self).preprocess(resized_inputs)
<add> return tf.keras.applications.mobilenet_v2.preprocess_input(resized_inputs)
<add>
<add> def load_feature_extractor_weights(self, path):
<add> self._network.load_weights(path)
<add>
<add> def get_base_model(self):
<add> return self._network
<add>
<add> def call(self, inputs):
<add> return [self._network(inputs)]
<add>
<add> @property
<add> def out_stride(self):
<add> """The stride in the output image of the network."""
<add> return 4
<add>
<add> @property
<add> def num_feature_outputs(self):
<add> """The number of feature outputs returned by the feature extractor."""
<add> return 1
<add>
<add> def get_model(self):
<add> return self._network
<add>
<add>
<add>def mobilenet_v2_fpn(channel_means, channel_stds, bgr_ordering):
<add> """The MobileNetV2+FPN backbone for CenterNet."""
<add>
<add> # Set to is_training to True for now.
<add> network = mobilenetv2.mobilenet_v2(True, include_top=False)
<add> return CenterNetMobileNetV2FPNFeatureExtractor(
<add> network,
<add> channel_means=channel_means,
<add> channel_stds=channel_stds,
<add> bgr_ordering=bgr_ordering)
<ide><path>research/object_detection/models/center_net_mobilenet_v2_fpn_feature_extractor_tf2_test.py
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Testing mobilenet_v2+FPN feature extractor for CenterNet."""
<add>import unittest
<add>import numpy as np
<add>import tensorflow.compat.v1 as tf
<add>
<add>from object_detection.models import center_net_mobilenet_v2_fpn_feature_extractor
<add>from object_detection.models.keras_models import mobilenet_v2
<add>from object_detection.utils import test_case
<add>from object_detection.utils import tf_version
<add>
<add>
<add>@unittest.skipIf(tf_version.is_tf1(), 'Skipping TF2.X only test.')
<add>class CenterNetMobileNetV2FPNFeatureExtractorTest(test_case.TestCase):
<add>
<add> def test_center_net_mobilenet_v2_fpn_feature_extractor(self):
<add>
<add> net = mobilenet_v2.mobilenet_v2(True, include_top=False)
<add>
<add> model = center_net_mobilenet_v2_fpn_feature_extractor.CenterNetMobileNetV2FPNFeatureExtractor(
<add> net)
<add>
<add> def graph_fn():
<add> img = np.zeros((8, 224, 224, 3), dtype=np.float32)
<add> processed_img = model.preprocess(img)
<add> return model(processed_img)
<add>
<add> outputs = self.execute(graph_fn, [])
<add> self.assertEqual(outputs.shape, (8, 56, 56, 24))
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main() | 4 |
Ruby | Ruby | remove redundant cflags | 95eb1b4a5d79463bca362386029a46a2f8d13414 | <ide><path>Library/Homebrew/extend/ENV.rb
<ide>
<ide> module HomebrewEnvExtension
<ide> # -w: keep signal to noise high
<del> # -fomit-frame-pointer: we are not debugging this software, we are using it
<del> SAFE_CFLAGS_FLAGS = "-w -pipe -fomit-frame-pointer"
<add> SAFE_CFLAGS_FLAGS = "-w -pipe"
<ide>
<ide> def setup_build_environment
<ide> # Clear CDPATH to avoid make issues that depend on changing directories
<ide> ENV.delete('CDPATH')
<ide>
<del> ENV['MACOSX_DEPLOYMENT_TARGET']=MACOS_VERSION.to_s
<ide> ENV['MAKEFLAGS']="-j#{Hardware.processor_count}"
<ide>
<ide> unless HOMEBREW_PREFIX.to_s == '/usr/local'
<ide> def setup_build_environment
<ide>
<ide> ENV['CC'] = "#{prefix}/usr/llvm-gcc-4.2/bin/llvm-gcc-4.2"
<ide> ENV['CXX'] = "#{prefix}/usr/llvm-gcc-4.2/bin/llvm-g++-4.2"
<del> cflags = ['-O4'] # O4 baby!
<add> cflags = %w{-O4} # link time optimisation baby!
<ide> else
<ide> ENV['CC']="gcc-4.2"
<ide> ENV['CXX']="g++-4.2"
<ide> def setup_build_environment
<ide> cflags<<"-msse3"
<ide> end
<ide>
<del> ENV['CFLAGS']=ENV['CXXFLAGS']="#{cflags*' '} #{SAFE_CFLAGS_FLAGS} -mmacosx-version-min=#{MACOS_VERSION}"
<add> ENV['CFLAGS'] = ENV['CXXFLAGS'] = "#{cflags*' '} #{SAFE_CFLAGS_FLAGS}"
<ide> end
<ide>
<ide> def deparallelize
<ide> def deparallelize
<ide>
<ide> def O3
<ide> # Sometimes O4 just takes fucking forever
<del> remove_from_cflags '-O4'
<add> remove_from_cflags /-O./
<ide> append_to_cflags '-O3'
<ide> end
<ide> def O2
<ide> # Sometimes O3 doesn't work or produces bad binaries
<del> remove_from_cflags '-O4'
<del> remove_from_cflags '-O3'
<add> remove_from_cflags /-O./
<ide> append_to_cflags '-O2'
<ide> end
<add> def Os
<add> # Sometimes you just want a small one
<add> remove_from_cflags /-O./
<add> append_to_cflags '-Os'
<add> end
<ide>
<ide> def gcc_4_0_1
<ide> case MACOS_VERSION
<ide> def minimal_optimization
<ide> def no_optimization
<ide> self['CFLAGS']=self['CXXFLAGS'] = SAFE_CFLAGS_FLAGS
<ide> end
<add>
<ide> def libxml2
<ide> append_to_cflags ' -I/usr/include/libxml2'
<ide> end
<ide> def m32
<ide> # i386 and x86_64 only, no PPC
<ide> def universal_binary
<ide> append_to_cflags '-arch i386 -arch x86_64'
<del> if self['CFLAGS'].include? '-O4'
<del> # O4 seems to cause the build to fail
<del> remove_from_cflags '-O4'
<del> append_to_cflags '-O3'
<del> end
<add> ENV.O3 if self['CFLAGS'].include? '-O4' # O4 seems to cause the build to fail
<ide> end
<ide>
<ide> def prepend key, value, separator = ' ' | 1 |
Python | Python | allow parallel build in runtests.py | da54c08b0336222fda128d2652eb867609add101 | <ide><path>runtests.py
<ide> def main(argv):
<ide> help="Start Unix shell with PYTHONPATH set")
<ide> parser.add_argument("--debug", "-g", action="store_true",
<ide> help="Debug build")
<add> parser.add_argument("--parallel", "-j", type=int, default=0,
<add> help="Number of parallel jobs during build")
<ide> parser.add_argument("--show-build-log", action="store_true",
<ide> help="Show build output rather than using a log file")
<ide> parser.add_argument("--bench", action="store_true",
<ide> def build_project(args):
<ide> env['F90'] = 'gfortran --coverage '
<ide> env['LDSHARED'] = cvars['LDSHARED'] + ' --coverage'
<ide> env['LDFLAGS'] = " ".join(cvars['LDSHARED'].split()[1:]) + ' --coverage'
<del> cmd += ["build"]
<ide>
<add> cmd += ["build"]
<add> if args.parallel > 1:
<add> cmd += ["-j", str(args.parallel)]
<ide> cmd += ['install', '--prefix=' + dst_dir]
<ide>
<ide> log_filename = os.path.join(ROOT_DIR, 'build.log') | 1 |
Javascript | Javascript | keep minimum volume after unmuting above 0.1 | 16c1e0adc0ba7dc7676b3ae151802fc3ab225f44 | <ide><path>src/js/control-bar/mute-toggle.js
<ide> class MuteToggle extends Button {
<ide> const lastVolume = this.player_.lastVolume_();
<ide>
<ide> if (vol === 0) {
<del> this.player_.volume(lastVolume);
<add> const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
<add>
<add> this.player_.volume(volumeToSet);
<ide> this.player_.muted(false);
<ide> } else {
<ide> this.player_.muted(this.player_.muted() ? false : true);
<ide><path>test/unit/controls.test.js
<ide> if (Html5.isSupported()) {
<ide> assert.equal(player.muted(), false, 'muted is set to false');
<ide> });
<ide>
<add> QUnit.test('Clicking MuteToggle when volume is 0, lastVolume is less than 0.1, and muted is true sets volume to 0.1 and muted to false', function(assert) {
<add> const player = TestHelpers.makePlayer({ techOrder: ['html5'] });
<add> const muteToggle = new MuteToggle(player);
<add>
<add> player.volume(0);
<add> player.muted(true);
<add> player.lastVolume_(0.05);
<add>
<add> muteToggle.handleClick();
<add>
<add> assert.equal(player.volume(), 0.1, 'since lastVolume is less than 0.1, volume is set to 0.1');
<add> assert.equal(player.muted(), false, 'muted is set to false');
<add> });
<add>
<ide> QUnit.test('ARIA value of VolumeBar should start at 100', function(assert) {
<ide> const player = TestHelpers.makePlayer({ techOrder: ['html5'] });
<ide> const volumeBar = new VolumeBar(player);
<ide> if (Html5.isSupported()) {
<ide> assert.equal(player.muted(), true, 'Muted is true');
<ide> assert.equal(volumeBar.el_.getAttribute('aria-valuenow'), 0, 'ARIA value of VolumeBar is 0');
<ide> });
<del>
<ide> } | 2 |
Javascript | Javascript | get flashes from ssr | 5a32585ddd8754325fd4c0f95b803426aefc242f | <ide><path>client/index.js
<ide> import { render } from 'redux-epic';
<ide> import createHistory from 'history/createBrowserHistory';
<ide> import useLangRoutes from './utils/use-lang-routes';
<ide> import sendPageAnalytics from './utils/send-page-analytics';
<del>import flashToToast from './utils/flash-to-toast';
<ide>
<ide> import { App, createApp, provideStore } from '../common/app';
<ide> import { getLangFromPath } from '../common/app/utils/lang';
<add>import flashReducer, { messagesFoundOnBoot } from '../common/app/Flash/redux';
<ide>
<ide> // client specific epics
<ide> import epics from './epics';
<ide> const {
<ide> document,
<ide> ga,
<ide> __fcc__: {
<del> flash = [],
<add> flash = {},
<ide> data: ssrState = {},
<ide> csrf: {
<ide> token: csrfToken
<ide> const defaultState = isColdStored() ?
<ide> const primaryLang = getLangFromPath(location.pathname);
<ide>
<ide> defaultState.app.csrfToken = csrfToken;
<del>defaultState.toasts = flashToToast(flash);
<add>defaultState.flash = flashReducer(
<add> defaultState.flash,
<add> messagesFoundOnBoot(flash)
<add>);
<ide>
<ide> const serviceOptions = { xhrPath: '/services', context: { _csrf: csrfToken } };
<ide>
<ide> createApp({
<ide> });
<ide> }
<ide> })
<del> .doOnNext(() => log('rendering'))
<add> .do(() => log('rendering'))
<ide> .flatMap(({ store }) => render(provideStore(App, store), DOMContainer))
<ide> .subscribe(
<ide> () => debug('react rendered'),
<ide><path>common/app/Flash/redux/index.js
<ide> import {
<ide>
<ide> import ns from '../ns.json';
<ide>
<del>export const types = createTypes([
<del> 'clickOnClose'
<del>], ns);
<del>
<del>export const clickOnClose = createAction(types.clickOnClose, _.noop);
<del>
<ide> export const alertTypes = _.keyBy(_.identity)([
<ide> 'success',
<ide> 'info',
<ide> 'warning',
<ide> 'danger'
<ide> ]);
<add>export const normalizeAlertType = _.get(alertTypes, 'info');
<ide>
<ide> export const getFlashAction = _.flow(
<ide> _.property('meta'),
<ide> export const isFlashAction = _.flow(
<ide> Boolean
<ide> );
<ide>
<add>export const types = createTypes([
<add> 'clickOnClose',
<add> 'messagesFoundOnBoot'
<add>], ns);
<add>
<add>export const clickOnClose = createAction(types.clickOnClose, _.noop);
<add>export const messagesFoundOnBoot = createAction(types.messagesFoundOnBoot);
<add>
<add>export const expressToStack = _.flow(
<add> _.toPairs,
<add> _.flatMap(([ type, messages ]) => messages.map(({ msg }) => ({
<add> message: msg,
<add> alertType: normalizeAlertType(type)
<add> })))
<add>);
<add>
<ide> const defaultState = {
<del> stack: [{ alertType: 'danger', message: 'foo bar' }]
<add> stack: [{ alertType: 'danger', message: 'foo nar' }]
<ide> };
<ide>
<ide> const getNS = _.property(ns);
<ide> export default composeReducers(
<ide> [types.clickOnClose]: (state) => ({
<ide> ...state,
<ide> stack: _.tail(state.stack)
<add> }),
<add> [types.messagesFoundOnBoot]: (state, { payload }) => ({
<add> ...state,
<add> stack: [...state.stack, ...expressToStack(payload)]
<ide> })
<ide> }),
<ide> defaultState,
<ide> export default composeReducers(
<ide> stack: [
<ide> ...state.stack,
<ide> {
<del> alertType: alertTypes[alertType] || 'info',
<add> alertType: normalizeAlertType(alertType),
<ide> message: _.escape(message)
<ide> }
<ide> ] | 2 |
PHP | PHP | add missing class alias | 84870da68b3e2d6eff333fe763b9d06fcf6d3d8c | <ide><path>src/Routing/Exception/MissingControllerException.php
<ide> <?php
<ide> declare(strict_types=1);
<ide>
<del>class_exists('Cake\Http\Exception\MissingControllerException');
<add>class_alias(
<add> 'Cake\Http\Exception\MissingControllerException',
<add> 'Cake\Routing\Exception\MissingControllerException',
<add>);
<ide> deprecationWarning(
<ide> 'Use Cake\Http\Exception\MissingControllerException instead of Cake\Routing\Exception\MissingControllerException.'
<ide> ); | 1 |
Javascript | Javascript | fix lint issues | 40eff8d5ccfc10e767363446ca21fcbc18157acf | <ide><path>server/component-passport.js
<ide> PassportConfigurator.prototype.init = function passportInit(noSession) {
<ide> if (err || !user) {
<ide> return done(err, user);
<ide> }
<del> this.app.dataSources.db.connector
<add> return this.app.dataSources.db.connector
<ide> .collection('user')
<ide> .aggregate([
<ide> { $match: { _id: user.id } },
<ide> { $project: { points: { $size: '$progressTimestamps' } } }
<ide> ], function(err, { points = 1 } = {}) {
<ide> if (err) { return done(err); }
<ide> user.points = points;
<del> done(null, user);
<add> return done(null, user);
<ide> });
<ide> });
<ide> }); | 1 |
Ruby | Ruby | change logic for renamed formulae | 2cc6b9032965fed9e937da7b1c723e4b2cfd60a0 | <ide><path>Library/Homebrew/formulary.rb
<ide> require "digest/md5"
<add>require "formula_renames"
<ide>
<ide> # The Formulary is responsible for creating instances of Formula.
<ide> # It is not meant to be used directy from formulae.
<ide> class TapLoader < FormulaLoader
<ide> def initialize(tapped_name)
<ide> user, repo, name = tapped_name.split("/", 3).map(&:downcase)
<ide> @tap = Tap.new user, repo.sub(/^homebrew-/, "")
<add> name = @tap.formula_renames.fetch(name, name)
<ide> path = @tap.formula_files.detect { |file| file.basename(".rb").to_s == name }
<ide> path ||= @tap.path/"#{name}.rb"
<ide>
<ide> def self.loader_for(ref)
<ide> when Pathname::BOTTLE_EXTNAME_RX
<ide> return BottleLoader.new(ref)
<ide> when HOMEBREW_CORE_FORMULA_REGEX
<del> return FormulaLoader.new($1, core_path($1))
<add> name = $1
<add> formula_with_that_name = core_path(name)
<add> if (newname = FORMULA_RENAMES[name]) && !formula_with_that_name.file?
<add> return FormulaLoader.new(newname, core_path(newname))
<add> else
<add> return FormulaLoader.new(name, formula_with_that_name)
<add> end
<ide> when HOMEBREW_TAP_FORMULA_REGEX
<ide> return TapLoader.new(ref)
<ide> end
<ide> def self.loader_for(ref)
<ide> return AliasLoader.new(possible_alias)
<ide> end
<ide>
<del> possible_tap_formulae = tap_paths(ref)
<add> possible_tap_formulae = tap_paths(ref)
<ide> if possible_tap_formulae.size > 1
<ide> raise TapFormulaAmbiguityError.new(ref, possible_tap_formulae)
<ide> elsif possible_tap_formulae.size == 1
<ide> return FormulaLoader.new(ref, possible_tap_formulae.first)
<ide> end
<ide>
<add> if newref = FORMULA_RENAMES[ref]
<add> formula_with_that_oldname = core_path(newref)
<add> if formula_with_that_oldname.file?
<add> return FormulaLoader.new(newref, formula_with_that_oldname)
<add> end
<add> end
<add>
<add> possible_tap_newname_formulae = []
<add> Tap.each do |tap|
<add> if newref = tap.formula_renames[ref]
<add> possible_tap_newname_formulae << "#{tap.name}/#{newref}"
<add> end
<add> end
<add>
<add> if possible_tap_newname_formulae.size > 1
<add> raise TapFormulaWithOldnameAmbiguityError.new(ref, possible_tap_newname_formulae)
<add> elsif !possible_tap_newname_formulae.empty?
<add> return TapLoader.new(possible_tap_newname_formulae.first)
<add> end
<add>
<ide> possible_cached_formula = Pathname.new("#{HOMEBREW_CACHE_FORMULA}/#{ref}.rb")
<ide> if possible_cached_formula.file?
<ide> return FormulaLoader.new(ref, possible_cached_formula) | 1 |
Python | Python | fix head masking for tft5 | 8d79e5ca49ea27ded98de927d220d830f34b7124 | <ide><path>src/transformers/models/t5/modeling_tf_t5.py
<ide> def project(hidden_states, proj_layer, key_value_states, past_key_value):
<ide>
<ide> # Mask heads if we want to
<ide> if layer_head_mask is not None:
<del> weights = weights * layer_head_mask
<add> tf.debugging.assert_equal(
<add> shape_list(layer_head_mask),
<add> [self.n_heads],
<add> message=f"Head mask for a single layer should be of size {(self.n_heads)}, but is {shape_list(layer_head_mask)}",
<add> )
<add> weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * weights
<ide>
<ide> attn_output = tf.matmul(weights, value_states) # (batch_size, n_heads, query_length, dim_per_head)
<ide>
<ide> def call(
<ide> else:
<ide> encoder_extended_attention_mask = None
<ide>
<del> assert inputs["head_mask"] is None, "Head mask not supported"
<del> inputs["head_mask"] = [None] * self.num_hidden_layers
<del> assert inputs["encoder_head_mask"] is None, "Encoder head mask not supported"
<del> inputs["encoder_head_mask"] = [None] * self.num_hidden_layers
<ide> present_key_value_states = () if inputs["use_cache"] and self.is_decoder else None
<ide> all_hidden_states = () if inputs["output_hidden_states"] else None
<ide> all_attentions = () if inputs["output_attentions"] else None
<ide> def call(
<ide>
<ide> hidden_states = self.dropout(inputs["inputs_embeds"], training=inputs["training"])
<ide>
<del> for i, (layer_module, past_key_value) in enumerate(zip(self.block, inputs["past_key_values"])):
<add> for idx, (layer_module, past_key_value) in enumerate(zip(self.block, inputs["past_key_values"])):
<ide> if inputs["output_hidden_states"]:
<ide> all_hidden_states = all_hidden_states + (hidden_states,)
<ide> layer_outputs = layer_module(
<ide> def call(
<ide> encoder_hidden_states=inputs["encoder_hidden_states"],
<ide> encoder_attention_mask=encoder_extended_attention_mask,
<ide> encoder_decoder_position_bias=encoder_decoder_position_bias,
<del> layer_head_mask=inputs["head_mask"][i],
<del> encoder_layer_head_mask=inputs["encoder_head_mask"][i],
<add> layer_head_mask=inputs["head_mask"][idx] if inputs["head_mask"] is not None else None,
<add> encoder_layer_head_mask=inputs["encoder_head_mask"][idx]
<add> if inputs["encoder_head_mask"] is not None
<add> else None,
<ide> past_key_value=past_key_value,
<ide> use_cache=inputs["use_cache"],
<ide> output_attentions=inputs["output_attentions"],
<ide> def _shift_right(self, input_ids):
<ide> behaviors between training and evaluation).
<ide> """
<ide>
<del>__HEAD_MASK_WARNING_MSG = """
<add>_HEAD_MASK_WARNING_MSG = """
<ide> The input argument `head_mask` was split into two arguments `head_mask` and `decoder_head_mask`. Currently,
<ide> `decoder_head_mask` is set to copy `head_mask`, but this feature is deprecated and will be removed in future versions.
<ide> If you do not want to use any `decoder_head_mask` now, please set `decoder_head_mask = tf.ones((num_layers,
<ide> def call(
<ide> """
<ide> # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
<ide> if head_mask is not None and decoder_head_mask is None:
<del> warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)
<add> warnings.warn(_HEAD_MASK_WARNING_MSG, FutureWarning)
<ide> decoder_head_mask = head_mask
<ide>
<ide> inputs = input_processing(
<ide> def call(
<ide> """
<ide> # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
<ide> if head_mask is not None and decoder_head_mask is None:
<del> warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)
<add> warnings.warn(_HEAD_MASK_WARNING_MSG, FutureWarning)
<ide> decoder_head_mask = head_mask
<ide>
<ide> inputs = input_processing(
<ide><path>tests/test_modeling_tf_t5.py
<ide> class TFT5ModelTest(TFModelTesterMixin, unittest.TestCase):
<ide> is_encoder_decoder = True
<ide> all_model_classes = (TFT5Model, TFT5ForConditionalGeneration) if is_tf_available() else ()
<ide> all_generative_model_classes = (TFT5ForConditionalGeneration,) if is_tf_available() else ()
<del> test_head_masking = False
<ide> test_onnx = False
<ide>
<ide> def setUp(self):
<ide> def prepare_config_and_inputs_for_common(self):
<ide> class TFT5EncoderOnlyModelTest(TFModelTesterMixin, unittest.TestCase):
<ide> is_encoder_decoder = False
<ide> all_model_classes = (TFT5EncoderModel,) if is_tf_available() else ()
<del> test_head_masking = False
<ide> test_onnx = False
<ide>
<ide> def setUp(self): | 2 |
Text | Text | fix call to super().data | 3a29eff5f868dcfb0a62d2613b8f351e32113e83 | <ide><path>docs/topics/release-notes.md
<ide> You can determine your currently installed version using `pip show`:
<ide> """
<ide> Drop `maybe_none` field if None.
<ide> """
<del> data = super().data()
<add> data = super().data
<ide> if 'maybe_none' in data and data['maybe_none'] is None:
<ide> del data['maybe_none']
<ide> return data | 1 |
Ruby | Ruby | fix the typo [ci skip] | 414f496363de3982e32e69c9fa166707d6f8ee74 | <ide><path>actionview/lib/action_view/helpers/cache_helper.rb
<ide> module Helpers
<ide> module CacheHelper
<ide> # This helper exposes a method for caching fragments of a view
<ide> # rather than an entire action or page. This technique is useful
<del> # caching pieces like menus, lists of newstopics, static HTML
<add> # caching pieces like menus, lists of new topics, static HTML
<ide> # fragments, and so on. This method takes a block that contains
<ide> # the content you wish to cache.
<ide> # | 1 |
Text | Text | fix directive example to match description | f00fa639881a9ef2ab2959f11fa30554396a3dac | <ide><path>docs/reference/builder.md
<ide> directive:
<ide>
<ide> ```Dockerfile
<ide> # About my dockerfile
<del>FROM ImageName
<ide> # directive=value
<add>FROM ImageName
<ide> ```
<ide>
<ide> The unknown directive is treated as a comment due to not being recognized. In | 1 |
Ruby | Ruby | update documentation for abstractadapter#reset! | 3b6743ea3ff00789239632cc96f8d0b42f28f47e | <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def disconnect!
<ide>
<ide> # Reset the state of this connection, directing the DBMS to clear
<ide> # transactions and other connection-related server-side state. Usually a
<del> # database-dependent operation; the default method simply executes a
<del> # ROLLBACK and swallows any exceptions which is probably not enough to
<del> # ensure the connection is clean.
<add> # database-dependent operation.
<add> #
<add> # The default implementation does nothing; the implementation should be
<add> # overridden by concrete adapters.
<ide> def reset!
<ide> # this should be overridden by concrete adapters
<ide> end | 1 |
Javascript | Javascript | show values instead of assertion message | 65b8d2133d89aecd9b044b4bf5f4ac5c5c39ebf2 | <ide><path>test/internet/test-dgram-multicast-multi-process.js
<ide> function launchChildProcess() {
<ide> console.error('[PARENT] %d received %d matching messages.',
<ide> worker.pid, count);
<ide>
<del> assert.strictEqual(count, messages.length,
<del> 'A worker received an invalid multicast message');
<add> assert.strictEqual(count, messages.length);
<ide> });
<ide>
<ide> clearTimeout(timer); | 1 |
Javascript | Javascript | provide link for best practices | 4a0f0522429b1ad8ba6a356ccbed1b917d60e0d9 | <ide><path>src/ng/directive/input.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> * current scope. If the property doesn't already exist on this scope, it will be created
<ide> * implicitly and added to the scope.
<ide> *
<add> * For best practices on using `ngModel`, see:
<add> *
<add> * - {@link https://github.com/angular/angular.js/wiki/Understanding-Scopes}
<add> *
<ide> * For basic examples, how to use `ngModel`, see:
<ide> *
<ide> * - {@link ng.directive:input input} | 1 |
Python | Python | fix displacy test | c90fe92e15165abfe5fb828ab9e74e9b9659a9f2 | <ide><path>spacy/tests/test_misc.py
<ide> def test_displacy_parse_deps(en_vocab):
<ide> words = ["This", "is", "a", "sentence"]
<ide> heads = [1, 0, 1, -2]
<ide> pos = ['DET', 'VERB', 'DET', 'NOUN']
<add> tags = ['DT', 'VBZ', 'DT', 'NN']
<ide> deps = ['nsubj', 'ROOT', 'det', 'attr']
<del> doc = get_doc(en_vocab, words=words, heads=heads, pos=pos, deps=deps)
<add> doc = get_doc(en_vocab, words=words, heads=heads, pos=pos, tags=tags,
<add> deps=deps)
<ide> deps = parse_deps(doc)
<ide> assert isinstance(deps, dict)
<ide> assert deps['words'] == [{'text': 'This', 'tag': 'DET'}, | 1 |
Javascript | Javascript | remove unnecessary haunted house guards | 79af1b457baf6e66fff831e7328e06f823445910 | <ide><path>test/unit/dimensions.js
<del>if ( jQuery.fn.width && jQuery.fn.height ) {
<add>if ( jQuery.fn.width ) {
<ide>
<ide> module("dimensions", { teardown: moduleTeardown });
<ide>
<ide> testIframe( "dimensions/documentSmall", "window vs. small document", function( j
<ide> testIframe( "dimensions/documentLarge", "window vs. large document", function( jQuery, window, document ) {
<ide> expect(2);
<ide>
<del> if ( jQuery.fn.height && jQuery.fn.width ) {
<del> expect(2);
<del> ok( jQuery( document ).height() > jQuery( window ).height(), "document height is larger than window height" );
<del> ok( jQuery( document ).width() > jQuery( window ).width(), "document width is larger than window width" );
<del> } else {
<del> expect(0);
<del> }
<add> ok( jQuery( document ).height() > jQuery( window ).height(), "document height is larger than window height" );
<add> ok( jQuery( document ).width() > jQuery( window ).width(), "document width is larger than window width" );
<ide> });
<ide>
<ide> } | 1 |
Javascript | Javascript | add support for global alert() on android | 1dc56a6758c58ae7608bdc130afb7b831194f7ed | <ide><path>Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js
<ide> function setUpTimers() {
<ide> }
<ide>
<ide> function setUpAlert() {
<del> var RCTAlertManager = require('NativeModules').AlertManager;
<ide> if (!GLOBAL.alert) {
<ide> GLOBAL.alert = function(text) {
<del> var alertOpts = {
<del> title: 'Alert',
<del> message: '' + text,
<del> buttons: [{'cancel': 'OK'}],
<del> };
<del> RCTAlertManager.alertWithArgs(alertOpts, function () {});
<add> // Require Alert on demand. Requiring it too early can lead to issues
<add> // with things like Platform not being fully initialized.
<add> require('Alert').alert('Alert', '' + text);
<ide> };
<ide> }
<ide> } | 1 |
Ruby | Ruby | remove unneeded code | 0a5f3dedf4cead8f6b1ff4ee582be14ffcfa3222 | <ide><path>railties/lib/rails/backtrace_cleaner.rb
<ide> def add_gem_filters
<ide> add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') }
<ide> end
<ide> end
<del>
<del> # For installing the BacktraceCleaner in the test/unit
<del> module BacktraceFilterForTestUnit #:nodoc:
<del> def self.included(klass)
<del> klass.send :alias_method_chain, :filter_backtrace, :cleaning
<del> end
<del>
<del> def filter_backtrace_with_cleaning(backtrace, prefix=nil)
<del> backtrace = filter_backtrace_without_cleaning(backtrace, prefix)
<del> backtrace = backtrace.first.split("\n") if backtrace.size == 1
<del> Rails.backtrace_cleaner.clean(backtrace)
<del> end
<del> end
<ide> end | 1 |
Go | Go | move testcopyvolumeuidgid to integration-cli | 9a7c5be7d1d71d339b857ec20ca03cc09d4bbfa2 | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestState(t *testing.T) {
<ide> }
<ide> logDone("run - test container state.")
<ide> }
<add>
<add>// Test for #1737
<add>func TestCopyVolumeUidGid(t *testing.T) {
<add> name := "testrunvolumesuidgid"
<add> defer deleteImages(name)
<add> defer deleteAllContainers()
<add> _, err := buildImage(name,
<add> `FROM busybox
<add> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<add> RUN echo 'dockerio:x:1001:' >> /etc/group
<add> RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
<add> true)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Test that the uid and gid is copied from the image to the volume
<add> cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
<add> out, _, err := runCommandWithOutput(cmd)
<add> if err != nil {
<add> t.Fatal(err, out)
<add> }
<add> out = strings.TrimSpace(out)
<add> if out != "dockerio:dockerio" {
<add> t.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
<add> }
<add>
<add> logDone("run - copy uid/gid for volume")
<add>}
<ide><path>integration/container_test.go
<ide> func tempDir(t *testing.T) string {
<ide> return tmpDir
<ide> }
<ide>
<del>// Test for #1737
<del>func TestCopyVolumeUidGid(t *testing.T) {
<del> eng := NewTestEngine(t)
<del> r := mkDaemonFromEngine(eng, t)
<del> defer r.Nuke()
<del>
<del> // Add directory not owned by root
<del> container1, _, _ := mkContainer(r, []string{"_", "/bin/sh", "-c", "mkdir -p /hello && touch /hello/test && chown daemon.daemon /hello"}, t)
<del> defer r.Destroy(container1)
<del>
<del> if container1.State.IsRunning() {
<del> t.Errorf("Container shouldn't be running")
<del> }
<del> if err := container1.Run(); err != nil {
<del> t.Fatal(err)
<del> }
<del> if container1.State.IsRunning() {
<del> t.Errorf("Container shouldn't be running")
<del> }
<del>
<del> img, err := r.Commit(container1, "", "", "unit test commited image", "", true, nil)
<del> if err != nil {
<del> t.Error(err)
<del> }
<del>
<del> // Test that the uid and gid is copied from the image to the volume
<del> tmpDir1 := tempDir(t)
<del> defer os.RemoveAll(tmpDir1)
<del> stdout1, _ := runContainer(eng, r, []string{"-v", "/hello", img.ID, "stat", "-c", "%U %G", "/hello"}, t)
<del> if !strings.Contains(stdout1, "daemon daemon") {
<del> t.Fatal("Container failed to transfer uid and gid to volume")
<del> }
<del>
<del> container2, _, _ := mkContainer(r, []string{"_", "/bin/sh", "-c", "mkdir -p /hello && chown daemon.daemon /hello"}, t)
<del> defer r.Destroy(container1)
<del>
<del> if container2.State.IsRunning() {
<del> t.Errorf("Container shouldn't be running")
<del> }
<del> if err := container2.Run(); err != nil {
<del> t.Fatal(err)
<del> }
<del> if container2.State.IsRunning() {
<del> t.Errorf("Container shouldn't be running")
<del> }
<del>
<del> img2, err := r.Commit(container2, "", "", "unit test commited image", "", true, nil)
<del> if err != nil {
<del> t.Error(err)
<del> }
<del>
<del> // Test that the uid and gid is copied from the image to the volume
<del> tmpDir2 := tempDir(t)
<del> defer os.RemoveAll(tmpDir2)
<del> stdout2, _ := runContainer(eng, r, []string{"-v", "/hello", img2.ID, "stat", "-c", "%U %G", "/hello"}, t)
<del> if !strings.Contains(stdout2, "daemon daemon") {
<del> t.Fatal("Container failed to transfer uid and gid to volume")
<del> }
<del>}
<del>
<ide> // Test for #1582
<ide> func TestCopyVolumeContent(t *testing.T) {
<ide> eng := NewTestEngine(t) | 2 |
Python | Python | add more authors | 4cc67551a7d0a1fc8874d36271e9a3cd676a075a | <ide><path>utils/exporters/blender/addons/io_three/__init__.py
<ide>
<ide> bl_info = {
<ide> 'name': "Three.js Format",
<del> 'author': "repsac, mrdoob, yomotsu, mpk, jpweeks, rkusa, tschw",
<add> 'author': "repsac, mrdoob, yomotsu, mpk, jpweeks, rkusa, tschw, jackcaron, bhouston",
<ide> 'version': (1, 5, 0),
<ide> 'blender': (2, 74, 0),
<ide> 'location': "File > Export", | 1 |
Ruby | Ruby | fix deprecation warnings in activeresource | 93387e2e7c66fb34bde5442ad314c9c63729b75b | <ide><path>activeresource/lib/active_resource/base.rb
<ide> class Base
<ide> extend ActiveModel::Naming
<ide> include CustomMethods, Observing, Validations
<ide> include ActiveModel::Conversion
<del> include ActiveModel::Serializers::JSON
<del> include ActiveModel::Serializers::Xml
<add> include ActiveModel::Serializable::JSON
<add> include ActiveModel::Serializable::XML
<ide> end
<ide> end
<ide><path>activeresource/lib/active_resource/custom_methods.rb
<ide> def custom_method_collection_url(method_name, options = {})
<ide> end
<ide> end
<ide>
<del> module InstanceMethods
<del> def get(method_name, options = {})
<del> self.class.format.decode(connection.get(custom_method_element_url(method_name, options), self.class.headers).body)
<del> end
<add> def get(method_name, options = {})
<add> self.class.format.decode(connection.get(custom_method_element_url(method_name, options), self.class.headers).body)
<add> end
<ide>
<del> def post(method_name, options = {}, body = nil)
<del> request_body = body.blank? ? encode : body
<del> if new?
<del> connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers)
<del> else
<del> connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers)
<del> end
<add> def post(method_name, options = {}, body = nil)
<add> request_body = body.blank? ? encode : body
<add> if new?
<add> connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers)
<add> else
<add> connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers)
<ide> end
<add> end
<ide>
<del> def put(method_name, options = {}, body = '')
<del> connection.put(custom_method_element_url(method_name, options), body, self.class.headers)
<del> end
<add> def put(method_name, options = {}, body = '')
<add> connection.put(custom_method_element_url(method_name, options), body, self.class.headers)
<add> end
<ide>
<del> def delete(method_name, options = {})
<del> connection.delete(custom_method_element_url(method_name, options), self.class.headers)
<del> end
<add> def delete(method_name, options = {})
<add> connection.delete(custom_method_element_url(method_name, options), self.class.headers)
<add> end
<ide>
<ide>
<del> private
<del> def custom_method_element_url(method_name, options = {})
<del> "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
<del> end
<add> private
<add> def custom_method_element_url(method_name, options = {})
<add> "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
<add> end
<ide>
<del> def custom_method_new_element_url(method_name, options = {})
<del> "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
<del> end
<del> end
<add> def custom_method_new_element_url(method_name, options = {})
<add> "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
<add> end
<ide> end
<ide> end | 2 |
Javascript | Javascript | update next.config.js rewrites | dee70f02377f6c4a6c99f889c159318b0bed770d | <ide><path>examples/with-zones/home/next.config.js
<ide> const { BLOG_URL } = process.env
<ide>
<ide> module.exports = {
<del> rewrites() {
<add> async rewrites() {
<ide> return [
<add> {
<add> source: '/:path*',
<add> destination: `/:path*`,
<add> },
<ide> {
<ide> source: '/blog',
<ide> destination: `${BLOG_URL}/blog`, | 1 |
Ruby | Ruby | fix flakey test in notifications_test.rb | 763c219539d76be22e589e6a5faf2d6e8937fcfc | <ide><path>activesupport/test/notifications_test.rb
<ide> def test_events_are_initialized_with_details
<ide> event = event(:foo, time, time + 0.01, random_id, {})
<ide>
<ide> assert_equal :foo, event.name
<del> assert_in_delta 10.0, event.duration, 0.0001
<add> assert_in_epsilon 10.0, event.duration, 0.01
<ide> end
<ide>
<ide> def test_event_cpu_time_does_not_raise_error_when_start_or_finished_not_called | 1 |
Javascript | Javascript | use imported `run` | be6a683242662eb9cc2e8af8b8e829465b7c0dd4 | <ide><path>packages/ember-application/lib/system/application.js
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> if (!this.$ || this.$.isReady) {
<ide> run.schedule('actions', this, 'domReady', _instance);
<ide> } else {
<del> this.$().ready(Ember.run.bind(this, 'domReady', _instance));
<add> this.$().ready(run.bind(this, 'domReady', _instance));
<ide> }
<ide> },
<ide> | 1 |
Text | Text | add missing parenthesis in tlssocket section | 4236ef926fdc7264d7b430e0021eb88607f5a5e1 | <ide><path>doc/api/tls.md
<ide> negotiation.
<ide> Instances of `tls.TLSSocket` implement the duplex [Stream][] interface.
<ide>
<ide> Methods that return TLS connection metadata (e.g.
<del>[`tls.TLSSocket.getPeerCertificate()`][] will only return data while the
<add>[`tls.TLSSocket.getPeerCertificate()`][]) will only return data while the
<ide> connection is open.
<ide>
<ide> ### `new tls.TLSSocket(socket[, options])` | 1 |
Javascript | Javascript | improve queuemicrotask performance | cde3928a10627510ae0aee7728e5498a95235482 | <ide><path>lib/async_hooks.js
<ide> class AsyncResource {
<ide> constructor(type, opts = {}) {
<ide> validateString(type, 'type');
<ide>
<del> if (typeof opts === 'number') {
<del> opts = { triggerAsyncId: opts, requireManualDestroy: false };
<del> } else if (opts.triggerAsyncId === undefined) {
<del> opts.triggerAsyncId = getDefaultTriggerAsyncId();
<add> let triggerAsyncId = opts;
<add> let requireManualDestroy = false;
<add> if (typeof opts !== 'number') {
<add> triggerAsyncId = opts.triggerAsyncId === undefined ?
<add> getDefaultTriggerAsyncId() : opts.triggerAsyncId;
<add> requireManualDestroy = !!opts.requireManualDestroy;
<ide> }
<ide>
<ide> // Unlike emitInitScript, AsyncResource doesn't supports null as the
<ide> // triggerAsyncId.
<del> const triggerAsyncId = opts.triggerAsyncId;
<ide> if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
<ide> throw new ERR_INVALID_ASYNC_ID('triggerAsyncId', triggerAsyncId);
<ide> }
<ide> class AsyncResource {
<ide> this[async_id_symbol] = asyncId;
<ide> this[trigger_async_id_symbol] = triggerAsyncId;
<ide>
<del> // This prop name (destroyed) has to be synchronized with C++
<del> const destroyed = { destroyed: false };
<del> this[destroyedSymbol] = destroyed;
<del>
<ide> if (initHooksExist()) {
<ide> emitInit(asyncId, type, triggerAsyncId, this);
<ide> }
<ide>
<del> if (!opts.requireManualDestroy) {
<add> if (!requireManualDestroy) {
<add> // This prop name (destroyed) has to be synchronized with C++
<add> const destroyed = { destroyed: false };
<add> this[destroyedSymbol] = destroyed;
<ide> registerDestroyHook(this, asyncId, destroyed);
<ide> }
<ide> }
<ide> class AsyncResource {
<ide> const asyncId = this[async_id_symbol];
<ide> emitBefore(asyncId, this[trigger_async_id_symbol]);
<ide> try {
<add> if (thisArg === undefined)
<add> return fn(...args);
<ide> return Reflect.apply(fn, thisArg, args);
<ide> } finally {
<ide> emitAfter(asyncId);
<ide> }
<ide> }
<ide>
<ide> emitDestroy() {
<del> this[destroyedSymbol].destroyed = true;
<add> if (this[destroyedSymbol] !== undefined) {
<add> this[destroyedSymbol].destroyed = true;
<add> }
<ide> emitDestroy(this[async_id_symbol]);
<ide> return this;
<ide> }
<ide><path>lib/internal/process/task_queues.js
<ide> function nextTick(callback) {
<ide> }
<ide>
<ide> let AsyncResource;
<add>const defaultMicrotaskResourceOpts = { requireManualDestroy: true };
<ide> function createMicrotaskResource() {
<ide> // Lazy load the async_hooks module
<del> if (!AsyncResource) {
<add> if (AsyncResource === undefined) {
<ide> AsyncResource = require('async_hooks').AsyncResource;
<ide> }
<del> return new AsyncResource('Microtask', {
<del> triggerAsyncId: getDefaultTriggerAsyncId(),
<del> requireManualDestroy: true,
<del> });
<add> return new AsyncResource('Microtask', defaultMicrotaskResourceOpts);
<ide> }
<ide>
<ide> function runMicrotask() { | 2 |
Javascript | Javascript | improve code in test-fs-open.js | 15c71f6c66a8515597f9a4886b35510950c474ef | <ide><path>test/parallel/test-fs-open.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>var assert = require('assert');
<del>var fs = require('fs');
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>
<add>let caughtException = false;
<ide>
<del>var caughtException = false;
<ide> try {
<ide> // should throw ENOENT, not EBADF
<ide> // see https://github.com/joyent/node/pull/1228
<ide> fs.openSync('/path/to/file/that/does/not/exist', 'r');
<ide> } catch (e) {
<del> assert.equal(e.code, 'ENOENT');
<add> assert.strictEqual(e.code, 'ENOENT');
<ide> caughtException = true;
<ide> }
<del>assert.ok(caughtException);
<add>assert.strictEqual(caughtException, true);
<ide>
<del>fs.open(__filename, 'r', common.mustCall(function(err, fd) {
<del> if (err) {
<del> throw err;
<del> }
<add>fs.open(__filename, 'r', common.mustCall((err) => {
<add> assert.ifError(err);
<ide> }));
<ide>
<del>fs.open(__filename, 'rs', common.mustCall(function(err, fd) {
<del> if (err) {
<del> throw err;
<del> }
<add>fs.open(__filename, 'rs', common.mustCall((err) => {
<add> assert.ifError(err);
<ide> })); | 1 |
Python | Python | update v2 check and fix ncf v2 check error logic | 308c79344c144290d431f777fc47deb5c94ccc80 | <ide><path>official/recommendation/ncf_keras_main.py
<ide> def run_ncf(_):
<ide> num_gpus=FLAGS.num_gpus)
<ide> params["distribute_strategy"] = strategy
<ide>
<del> if keras_utils.is_v2_0() and strategy is not None:
<add> if not keras_utils.is_v2_0() and strategy is not None:
<ide> logging.error("NCF Keras only works with distribution strategy in TF 2.0")
<ide> return
<ide> | 1 |
Javascript | Javascript | add missing default 'binary' option to gltfloader | 869cd160f56a46d1ae22b973c107bcc08f79ce0f | <ide><path>examples/js/exporters/GLTFExporter.js
<ide> THREE.GLTFExporter.prototype = {
<ide> parse: function ( input, onDone, options ) {
<ide>
<ide> var DEFAULT_OPTIONS = {
<add> binary: false,
<ide> trs: false,
<ide> onlyVisible: true,
<ide> truncateDrawRange: true, | 1 |
Javascript | Javascript | change promise.done to promise.then | 82f3964f2da8b93b2cd2b6a8d1c9cdb5c2aa6f3a | <ide><path>Libraries/Network/NetInfo.js
<ide> const _isConnectedSubscriptions = new Map();
<ide> * NetInfo exposes info about online/offline status
<ide> *
<ide> * ```
<del> * NetInfo.fetch().done((reach) => {
<add> * NetInfo.fetch().then((reach) => {
<ide> * console.log('Initial: ' + reach);
<ide> * });
<ide> * function handleFirstConnectivityChange(reach) { | 1 |
Mixed | Javascript | allow monitoring uncaughtexception | f4797ff1ef7304659d747d181ec1e7afac408d50 | <ide><path>doc/api/process.md
<ide> nonexistentFunc();
<ide> console.log('This will not run.');
<ide> ```
<ide>
<add>It is possible to monitor `'uncaughtException'` events without overriding the
<add>default behavior to exit the process by installing a
<add>`'uncaughtExceptionMonitor'` listener.
<add>
<ide> #### Warning: Using `'uncaughtException'` correctly
<ide>
<ide> `'uncaughtException'` is a crude mechanism for exception handling
<ide> To restart a crashed application in a more reliable way, whether
<ide> in a separate process to detect application failures and recover or restart as
<ide> needed.
<ide>
<add>### Event: `'uncaughtExceptionMonitor'`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `err` {Error} The uncaught exception.
<add>* `origin` {string} Indicates if the exception originates from an unhandled
<add> rejection or from synchronous errors. Can either be `'uncaughtException'` or
<add> `'unhandledRejection'`.
<add>
<add>The `'uncaughtExceptionMonitor'` event is emitted before an
<add>`'uncaughtException'` event is emitted or a hook installed via
<add>[`process.setUncaughtExceptionCaptureCallback()`][] is called.
<add>
<add>Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior
<add>once an `'uncaughtException'` event is emitted. The process will
<add>still crash if no `'uncaughtException'` listener is installed.
<add>
<add>```js
<add>process.on('uncaughtExceptionMonitor', (err, origin) => {
<add> MyMonitoringTool.logSync(err, origin);
<add>});
<add>
<add>// Intentionally cause an exception, but don't catch it.
<add>nonexistentFunc();
<add>// Still crashes Node.js
<add>```
<add>
<ide> ### Event: `'unhandledRejection'`
<ide> <!-- YAML
<ide> added: v1.4.1
<ide><path>lib/internal/process/execution.js
<ide> function createOnGlobalUncaughtException() {
<ide> }
<ide>
<ide> const type = fromPromise ? 'unhandledRejection' : 'uncaughtException';
<add> process.emit('uncaughtExceptionMonitor', er, type);
<ide> if (exceptionHandlerState.captureFn !== null) {
<ide> exceptionHandlerState.captureFn(er);
<ide> } else if (!process.emit('uncaughtException', er, type)) {
<ide><path>test/fixtures/uncaught-exceptions/uncaught-monitor1.js
<add>'use strict';
<add>
<add>// Keep the event loop alive.
<add>setTimeout(() => {}, 1e6);
<add>
<add>process.on('uncaughtExceptionMonitor', (err) => {
<add> console.log(`Monitored: ${err.message}`);
<add>});
<add>
<add>throw new Error('Shall exit');
<ide><path>test/fixtures/uncaught-exceptions/uncaught-monitor2.js
<add>'use strict';
<add>
<add>// Keep the event loop alive.
<add>setTimeout(() => {}, 1e6);
<add>
<add>process.on('uncaughtExceptionMonitor', (err) => {
<add> console.log(`Monitored: ${err.message}, will throw now`);
<add> missingFunction();
<add>});
<add>
<add>throw new Error('Shall exit');
<ide><path>test/parallel/test-process-uncaught-exception-monitor.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { execFile } = require('child_process');
<add>const fixtures = require('../common/fixtures');
<add>
<add>{
<add> // Verify exit behavior is unchanged
<add> const fixture = fixtures.path('uncaught-exceptions', 'uncaught-monitor1.js');
<add> execFile(
<add> process.execPath,
<add> [fixture],
<add> common.mustCall((err, stdout, stderr) => {
<add> assert.strictEqual(err.code, 1);
<add> assert.strictEqual(Object.getPrototypeOf(err).name, 'Error');
<add> assert.strictEqual(stdout, 'Monitored: Shall exit\n');
<add> const errLines = stderr.trim().split(/[\r\n]+/);
<add> const errLine = errLines.find((l) => /^Error/.exec(l));
<add> assert.strictEqual(errLine, 'Error: Shall exit');
<add> })
<add> );
<add>}
<add>
<add>{
<add> // Verify exit behavior is unchanged
<add> const fixture = fixtures.path('uncaught-exceptions', 'uncaught-monitor2.js');
<add> execFile(
<add> process.execPath,
<add> [fixture],
<add> common.mustCall((err, stdout, stderr) => {
<add> assert.strictEqual(err.code, 7);
<add> assert.strictEqual(Object.getPrototypeOf(err).name, 'Error');
<add> assert.strictEqual(stdout, 'Monitored: Shall exit, will throw now\n');
<add> const errLines = stderr.trim().split(/[\r\n]+/);
<add> const errLine = errLines.find((l) => /^ReferenceError/.exec(l));
<add> assert.strictEqual(
<add> errLine,
<add> 'ReferenceError: missingFunction is not defined'
<add> );
<add> })
<add> );
<add>}
<add>
<add>const theErr = new Error('MyError');
<add>
<add>process.on(
<add> 'uncaughtExceptionMonitor',
<add> common.mustCall((err, origin) => {
<add> assert.strictEqual(err, theErr);
<add> assert.strictEqual(origin, 'uncaughtException');
<add> }, 2)
<add>);
<add>
<add>process.on('uncaughtException', common.mustCall((err, origin) => {
<add> assert.strictEqual(origin, 'uncaughtException');
<add> assert.strictEqual(err, theErr);
<add>}));
<add>
<add>process.nextTick(common.mustCall(() => {
<add> // Test with uncaughtExceptionCaptureCallback installed
<add> process.setUncaughtExceptionCaptureCallback(common.mustCall(
<add> (err) => assert.strictEqual(err, theErr))
<add> );
<add>
<add> throw theErr;
<add>}));
<add>
<add>throw theErr; | 5 |
Java | Java | update the timeout docs | 26a8642a75d4cb039b5e6a2deb76af1c63078c79 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public final Observable<TimeInterval<T>> timeInterval(Scheduler scheduler) {
<ide> }
<ide>
<ide> /**
<del> * Returns an Observable that completes if either the first item emitted by the source
<del> * Observable or any subsequent item don't arrive within time windows defined by other
<del> * Observables.
<add> * Returns an Observable that mirrors the source Observable, but emits a TimeoutException
<add> * if either the first item emitted by the source Observable or any subsequent item
<add> * don't arrive within time windows defined by other Observables.
<ide> * <p>
<ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout5.png">
<ide> *
<ide> public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTi
<ide> }
<ide>
<ide> /**
<del> * Returns an Observable that mirrors the source Observable, but completes if an item emitted by
<add> * Returns an Observable that mirrors the source Observable, but emits a TimeoutException if an item emitted by
<ide> * the source Observable doesn't arrive within a window of time after the emission of the
<ide> * previous item, where that period of time is measured by an Observable that is a function
<ide> * of the previous item.
<ide> * <p>
<ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/timeout3.png">
<ide> * <p>
<del> * The arrival of the first source item is never timed out.
<add> * Note: The arrival of the first source item is never timed out.
<ide> *
<del> * @param <U>
<add> * @param <V>
<ide> * the timeout value type (ignored)
<ide> * @param timeoutSelector
<ide> * a function that returns an observable for each item emitted by the source
<ide> public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>>
<ide> * <p>
<ide> * The arrival of the first source item is never timed out.
<ide> *
<del> * @param <U>
<add> * @param <V>
<ide> * the timeout value type (ignored)
<ide> * @param timeoutSelector
<ide> * a function that returns an observable for each item emitted by the source
<ide><path>rxjava-core/src/main/java/rx/operators/OperatorTimeoutWithSelector.java
<add>/**
<add> * Copyright 2014 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<ide> package rx.operators;
<ide>
<ide> import rx.Observable;
<ide> import rx.util.functions.Func0;
<ide> import rx.util.functions.Func1;
<ide>
<add>/**
<add> * Returns an Observable that mirrors the source Observable. If either the first
<add> * item emitted by the source Observable or any subsequent item don't arrive
<add> * within time windows defined by provided Observables, switch to the
<add> * <code>other</code> Observable if provided, or emit a TimeoutException .
<add> */
<ide> public class OperatorTimeoutWithSelector<T, U, V> extends
<ide> OperatorTimeoutBase<T> {
<ide> | 2 |
Javascript | Javascript | update example to use a module | e293975b1aac9ea08d4c811d92fae43700dd20ff | <ide><path>src/ng/directive/input.js
<ide> var ngModelDirective = function() {
<ide> * in input value.
<ide> *
<ide> * @example
<del> * <example name="ngChange-directive">
<add> * <example name="ngChange-directive" module="changeExample">
<ide> * <file name="index.html">
<ide> * <script>
<del> * function Controller($scope) {
<del> * $scope.counter = 0;
<del> * $scope.change = function() {
<del> * $scope.counter++;
<del> * };
<del> * }
<add> * angular.module('changeExample', [])
<add> * .controller('ExampleController', ['$scope', function($scope) {
<add> * $scope.counter = 0;
<add> * $scope.change = function() {
<add> * $scope.counter++;
<add> * };
<add> * }]);
<ide> * </script>
<del> * <div ng-controller="Controller">
<add> * <div ng-controller="ExampleController">
<ide> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
<ide> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
<ide> * <label for="ng-change-example2">Confirmed</label><br /> | 1 |
Javascript | Javascript | create `usemergerefs` utility | 0b994ac19c1cc377d074f057585621e78aa8682f | <ide><path>Libraries/Utilities/__tests__/useMergeRefs-test.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @emails oncall+react_native
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>import useMergeRefs from '../useMergeRefs';
<add>import * as React from 'react';
<add>import {View} from 'react-native';
<add>import {act, create} from 'react-test-renderer';
<add>
<add>/**
<add> * TestView provide a component execution environment to test hooks.
<add> */
<add>function TestView({name, refs}) {
<add> const mergeRef = useMergeRefs(...refs);
<add> return <View ref={mergeRef} testID={name} />;
<add>}
<add>
<add>/**
<add> * TestViewInstance provides a pretty-printable replacement for React instances.
<add> */
<add>class TestViewInstance {
<add> name: string;
<add>
<add> constructor(name: string) {
<add> this.name = name;
<add> }
<add>
<add> // $FlowIgnore[unclear-type] - Intentional.
<add> static fromValue(value: any): ?TestViewInstance {
<add> const testID = value?.props?.testID;
<add> return testID == null ? null : new TestViewInstance(testID);
<add> }
<add>
<add> static named(name: string) {
<add> // $FlowIssue[prop-missing] - Flow does not support type augmentation.
<add> return expect.testViewInstance(name);
<add> }
<add>}
<add>
<add>/**
<add> * extend.testViewInstance makes it easier to assert expected values. But use
<add> * TestViewInstance.named instead of extend.testViewInstance because of Flow.
<add> */
<add>expect.extend({
<add> testViewInstance(received, name) {
<add> const pass = received instanceof TestViewInstance && received.name === name;
<add> return {pass};
<add> },
<add>});
<add>
<add>/**
<add> * Creates a registry that records the values assigned to the mock refs created
<add> * by either of the two returned callbacks.
<add> */
<add>function mockRefRegistry<T>(): {
<add> mockCallbackRef: (name: string) => T => mixed,
<add> mockObjectRef: (name: string) => {current: T, ...},
<add> registry: $ReadOnlyArray<{[string]: T}>,
<add>} {
<add> const registry = [];
<add> return {
<add> mockCallbackRef: (name: string): (T => mixed) => current => {
<add> registry.push({[name]: TestViewInstance.fromValue(current)});
<add> },
<add> mockObjectRef: (name: string): {current: T, ...} => ({
<add> // $FlowIgnore[unsafe-getters-setters] - Intentional.
<add> set current(current) {
<add> registry.push({[name]: TestViewInstance.fromValue(current)});
<add> },
<add> }),
<add> registry,
<add> };
<add>}
<add>
<add>test('accepts a callback ref', () => {
<add> let root;
<add>
<add> const {mockCallbackRef, registry} = mockRefRegistry();
<add> const refA = mockCallbackRef('refA');
<add>
<add> act(() => {
<add> root = create(<TestView name="foo" refs={[refA]} />);
<add> });
<add>
<add> expect(registry).toEqual([{refA: TestViewInstance.named('foo')}]);
<add>
<add> act(() => {
<add> root = create(<TestView name="bar" refs={[refA]} />);
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refA: TestViewInstance.named('bar')},
<add> ]);
<add>
<add> act(() => {
<add> root.unmount();
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refA: TestViewInstance.named('bar')},
<add> {refA: null},
<add> ]);
<add>});
<add>
<add>test('accepts an object ref', () => {
<add> let root;
<add>
<add> const {mockObjectRef, registry} = mockRefRegistry();
<add> const refA = mockObjectRef('refA');
<add>
<add> act(() => {
<add> root = create(<TestView name="foo" refs={[refA]} />);
<add> });
<add>
<add> expect(registry).toEqual([{refA: TestViewInstance.named('foo')}]);
<add>
<add> act(() => {
<add> root = create(<TestView name="bar" refs={[refA]} />);
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refA: TestViewInstance.named('bar')},
<add> ]);
<add>
<add> act(() => {
<add> root.unmount();
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refA: TestViewInstance.named('bar')},
<add> {refA: null},
<add> ]);
<add>});
<add>
<add>test('invokes refs in order', () => {
<add> let root;
<add>
<add> const {mockCallbackRef, mockObjectRef, registry} = mockRefRegistry();
<add> const refA = mockCallbackRef('refA');
<add> const refB = mockObjectRef('refB');
<add> const refC = mockCallbackRef('refC');
<add> const refD = mockObjectRef('refD');
<add>
<add> act(() => {
<add> root = create(<TestView name="foo" refs={[refA, refB, refC, refD]} />);
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refB: TestViewInstance.named('foo')},
<add> {refC: TestViewInstance.named('foo')},
<add> {refD: TestViewInstance.named('foo')},
<add> ]);
<add>
<add> act(() => {
<add> root.unmount();
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refB: TestViewInstance.named('foo')},
<add> {refC: TestViewInstance.named('foo')},
<add> {refD: TestViewInstance.named('foo')},
<add> {refA: null},
<add> {refB: null},
<add> {refC: null},
<add> {refD: null},
<add> ]);
<add>});
<add>
<add>// This is actually undesirable behavior, but it's what we have so let's make
<add>// sure it does not change unexpectedly.
<add>test('invokes all refs if any ref changes', () => {
<add> let root;
<add>
<add> const {mockCallbackRef, registry} = mockRefRegistry();
<add> const refA = mockCallbackRef('refA');
<add> const refB = mockCallbackRef('refB');
<add>
<add> act(() => {
<add> root = create(<TestView name="foo" refs={[refA, refB]} />);
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refB: TestViewInstance.named('foo')},
<add> ]);
<add>
<add> const refAPrime = mockCallbackRef('refAPrime');
<add> act(() => {
<add> root.update(<TestView name="foo" refs={[refAPrime, refB]} />);
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refB: TestViewInstance.named('foo')},
<add> {refA: null},
<add> {refB: null},
<add> {refAPrime: TestViewInstance.named('foo')},
<add> {refB: TestViewInstance.named('foo')},
<add> ]);
<add>
<add> act(() => {
<add> root.unmount();
<add> });
<add>
<add> expect(registry).toEqual([
<add> {refA: TestViewInstance.named('foo')},
<add> {refB: TestViewInstance.named('foo')},
<add> {refA: null},
<add> {refB: null},
<add> {refAPrime: TestViewInstance.named('foo')},
<add> {refB: TestViewInstance.named('foo')},
<add> {refAPrime: null},
<add> {refB: null},
<add> ]);
<add>});
<ide><path>Libraries/Utilities/useMergeRefs.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict
<add> * @format
<add> */
<add>
<add>import {useCallback} from 'react';
<add>
<add>type CallbackRef<T> = T => mixed;
<add>type ObjectRef<T> = {current: T, ...};
<add>
<add>type Ref<T> = CallbackRef<T> | ObjectRef<T>;
<add>
<add>/**
<add> * Constructs a new ref that forwards new values to each of the given refs. The
<add> * given refs will always be invoked in the order that they are supplied.
<add> *
<add> * WARNING: A known problem of merging refs using this approach is that if any
<add> * of the given refs change, the returned callback ref will also be changed. If
<add> * the returned callback ref is supplied as a `ref` to a React element, this may
<add> * lead to problems with the given refs being invoked more times than desired.
<add> */
<add>export default function useMergeRefs<T>(
<add> ...refs: $ReadOnlyArray<?Ref<T>>
<add>): CallbackRef<T> {
<add> return useCallback(
<add> (current: T) => {
<add> for (const ref of refs) {
<add> if (ref != null) {
<add> if (typeof ref === 'function') {
<add> ref(current);
<add> } else {
<add> ref.current = current;
<add> }
<add> }
<add> }
<add> },
<add> [...refs], // eslint-disable-line react-hooks/exhaustive-deps
<add> );
<add>} | 2 |
PHP | PHP | remove incorrect `static` modifier | 7f67ce97f663cfc01f572f0b5b039f99eae7c4a5 | <ide><path>src/Illuminate/Support/DateFactory.php
<ide> * @see https://carbon.nesbot.com/docs/
<ide> * @see https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Factory.php
<ide> *
<del> * @method static Carbon create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null)
<del> * @method static Carbon createFromDate($year = null, $month = null, $day = null, $tz = null)
<del> * @method static Carbon|false createFromFormat($format, $time, $tz = null)
<del> * @method static Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null)
<del> * @method static Carbon createFromTimeString($time, $tz = null)
<del> * @method static Carbon createFromTimestamp($timestamp, $tz = null)
<del> * @method static Carbon createFromTimestampMs($timestamp, $tz = null)
<del> * @method static Carbon createFromTimestampUTC($timestamp)
<del> * @method static Carbon createMidnightDate($year = null, $month = null, $day = null, $tz = null)
<del> * @method static Carbon|false createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
<del> * @method static Carbon disableHumanDiffOption($humanDiffOption)
<del> * @method static Carbon enableHumanDiffOption($humanDiffOption)
<del> * @method static mixed executeWithLocale($locale, $func)
<del> * @method static Carbon fromSerialized($value)
<del> * @method static array getAvailableLocales()
<del> * @method static array getDays()
<del> * @method static int getHumanDiffOptions()
<del> * @method static array getIsoUnits()
<del> * @method static Carbon getLastErrors()
<del> * @method static string getLocale()
<del> * @method static int getMidDayAt()
<del> * @method static Carbon getTestNow()
<del> * @method static \Symfony\Component\Translation\TranslatorInterface getTranslator()
<del> * @method static int getWeekEndsAt()
<del> * @method static int getWeekStartsAt()
<del> * @method static array getWeekendDays()
<del> * @method static bool hasFormat($date, $format)
<del> * @method static bool hasMacro($name)
<del> * @method static bool hasRelativeKeywords($time)
<del> * @method static bool hasTestNow()
<del> * @method static Carbon instance($date)
<del> * @method static bool isImmutable()
<del> * @method static bool isModifiableUnit($unit)
<del> * @method static Carbon isMutable()
<del> * @method static bool isStrictModeEnabled()
<del> * @method static bool localeHasDiffOneDayWords($locale)
<del> * @method static bool localeHasDiffSyntax($locale)
<del> * @method static bool localeHasDiffTwoDayWords($locale)
<del> * @method static bool localeHasPeriodSyntax($locale)
<del> * @method static bool localeHasShortUnits($locale)
<del> * @method static void macro($name, $macro)
<del> * @method static Carbon|null make($var)
<del> * @method static Carbon maxValue()
<del> * @method static Carbon minValue()
<del> * @method static void mixin($mixin)
<del> * @method static Carbon now($tz = null)
<del> * @method static Carbon parse($time = null, $tz = null)
<del> * @method static string pluralUnit(string $unit)
<del> * @method static void resetMonthsOverflow()
<del> * @method static void resetToStringFormat()
<del> * @method static void resetYearsOverflow()
<del> * @method static void serializeUsing($callback)
<del> * @method static Carbon setHumanDiffOptions($humanDiffOptions)
<del> * @method static bool setLocale($locale)
<del> * @method static void setMidDayAt($hour)
<del> * @method static void setTestNow($testNow = null)
<del> * @method static void setToStringFormat($format)
<del> * @method static void setTranslator(\Symfony\Component\Translation\TranslatorInterface $translator)
<del> * @method static Carbon setUtf8($utf8)
<del> * @method static void setWeekEndsAt($day)
<del> * @method static void setWeekStartsAt($day)
<del> * @method static void setWeekendDays($days)
<del> * @method static bool shouldOverflowMonths()
<del> * @method static bool shouldOverflowYears()
<del> * @method static string singularUnit(string $unit)
<del> * @method static Carbon today($tz = null)
<del> * @method static Carbon tomorrow($tz = null)
<del> * @method static void useMonthsOverflow($monthsOverflow = true)
<del> * @method static Carbon useStrictMode($strictModeEnabled = true)
<del> * @method static void useYearsOverflow($yearsOverflow = true)
<del> * @method static Carbon yesterday($tz = null)
<add> * @method Carbon create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null)
<add> * @method Carbon createFromDate($year = null, $month = null, $day = null, $tz = null)
<add> * @method Carbon|false createFromFormat($format, $time, $tz = null)
<add> * @method Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null)
<add> * @method Carbon createFromTimeString($time, $tz = null)
<add> * @method Carbon createFromTimestamp($timestamp, $tz = null)
<add> * @method Carbon createFromTimestampMs($timestamp, $tz = null)
<add> * @method Carbon createFromTimestampUTC($timestamp)
<add> * @method Carbon createMidnightDate($year = null, $month = null, $day = null, $tz = null)
<add> * @method Carbon|false createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
<add> * @method Carbon disableHumanDiffOption($humanDiffOption)
<add> * @method Carbon enableHumanDiffOption($humanDiffOption)
<add> * @method mixed executeWithLocale($locale, $func)
<add> * @method Carbon fromSerialized($value)
<add> * @method array getAvailableLocales()
<add> * @method array getDays()
<add> * @method int getHumanDiffOptions()
<add> * @method array getIsoUnits()
<add> * @method Carbon getLastErrors()
<add> * @method string getLocale()
<add> * @method int getMidDayAt()
<add> * @method Carbon getTestNow()
<add> * @method \Symfony\Component\Translation\TranslatorInterface getTranslator()
<add> * @method int getWeekEndsAt()
<add> * @method int getWeekStartsAt()
<add> * @method array getWeekendDays()
<add> * @method bool hasFormat($date, $format)
<add> * @method bool hasMacro($name)
<add> * @method bool hasRelativeKeywords($time)
<add> * @method bool hasTestNow()
<add> * @method Carbon instance($date)
<add> * @method bool isImmutable()
<add> * @method bool isModifiableUnit($unit)
<add> * @method Carbon isMutable()
<add> * @method bool isStrictModeEnabled()
<add> * @method bool localeHasDiffOneDayWords($locale)
<add> * @method bool localeHasDiffSyntax($locale)
<add> * @method bool localeHasDiffTwoDayWords($locale)
<add> * @method bool localeHasPeriodSyntax($locale)
<add> * @method bool localeHasShortUnits($locale)
<add> * @method void macro($name, $macro)
<add> * @method Carbon|null make($var)
<add> * @method Carbon maxValue()
<add> * @method Carbon minValue()
<add> * @method void mixin($mixin)
<add> * @method Carbon now($tz = null)
<add> * @method Carbon parse($time = null, $tz = null)
<add> * @method string pluralUnit(string $unit)
<add> * @method void resetMonthsOverflow()
<add> * @method void resetToStringFormat()
<add> * @method void resetYearsOverflow()
<add> * @method void serializeUsing($callback)
<add> * @method Carbon setHumanDiffOptions($humanDiffOptions)
<add> * @method bool setLocale($locale)
<add> * @method void setMidDayAt($hour)
<add> * @method void setTestNow($testNow = null)
<add> * @method void setToStringFormat($format)
<add> * @method void setTranslator(\Symfony\Component\Translation\TranslatorInterface $translator)
<add> * @method Carbon setUtf8($utf8)
<add> * @method void setWeekEndsAt($day)
<add> * @method void setWeekStartsAt($day)
<add> * @method void setWeekendDays($days)
<add> * @method bool shouldOverflowMonths()
<add> * @method bool shouldOverflowYears()
<add> * @method string singularUnit(string $unit)
<add> * @method Carbon today($tz = null)
<add> * @method Carbon tomorrow($tz = null)
<add> * @method void useMonthsOverflow($monthsOverflow = true)
<add> * @method Carbon useStrictMode($strictModeEnabled = true)
<add> * @method void useYearsOverflow($yearsOverflow = true)
<add> * @method Carbon yesterday($tz = null)
<ide> */
<ide> class DateFactory
<ide> { | 1 |
Python | Python | remove exec_command() from f2py init | 0a61f7f425c890f6e757b7ceedf00ba34501e052 | <ide><path>numpy/f2py/__init__.py
<ide> __all__ = ['run_main', 'compile', 'f2py_testing']
<ide>
<ide> import sys
<add>import subprocess
<add>import os
<add>
<add>import numpy as np
<ide>
<ide> from . import f2py2e
<ide> from . import f2py_testing
<ide> def compile(source,
<ide> Fortran source of module / subroutine to compile
<ide> modulename : str, optional
<ide> The name of the compiled python module
<del> extra_args : str, optional
<add> extra_args : str or list, optional
<ide> Additional parameters passed to f2py
<add>
<add> .. versionchanged:: 1.16.0
<add> A list of args may also be provided.
<add>
<ide> verbose : bool, optional
<ide> Print f2py output to screen
<ide> source_fn : str, optional
<ide> def compile(source,
<ide> .. versionadded:: 1.11.0
<ide>
<ide> """
<del> from numpy.distutils.exec_command import exec_command
<ide> import tempfile
<add> import shlex
<add>
<ide> if source_fn is None:
<del> f = tempfile.NamedTemporaryFile(suffix=extension)
<add> f, fname = tempfile.mkstemp(suffix=extension)
<add> # f is a file descriptor so need to close it
<add> # carefully -- not with .close() directly
<add> os.close(f)
<ide> else:
<del> f = open(source_fn, 'w')
<add> fname = source_fn
<ide>
<ide> try:
<del> f.write(source)
<del> f.flush()
<add> with open(fname, 'w') as f:
<add> f.write(str(source))
<add>
<add> args = ['-c', '-m', modulename, f.name]
<add>
<add> if isinstance(extra_args, np.compat.basestring):
<add> is_posix = (os.name == 'posix')
<add> extra_args = shlex.split(extra_args, posix=is_posix)
<add>
<add> args.extend(extra_args)
<ide>
<del> args = ' -c -m {} {} {}'.format(modulename, f.name, extra_args)
<del> c = '{} -c "import numpy.f2py as f2py2e;f2py2e.main()" {}'
<del> c = c.format(sys.executable, args)
<del> status, output = exec_command(c)
<add> c = [sys.executable,
<add> '-c',
<add> 'import numpy.f2py as f2py2e;f2py2e.main()'] + args
<add> try:
<add> output = subprocess.check_output(c)
<add> except subprocess.CalledProcessError as exc:
<add> status = exc.returncode
<add> output = ''
<add> except OSError:
<add> # preserve historic status code used by exec_command()
<add> status = 127
<add> output = ''
<add> else:
<add> status = 0
<ide> if verbose:
<ide> print(output)
<ide> finally:
<del> f.close()
<add> if source_fn is None:
<add> os.remove(fname)
<ide> return status
<ide>
<ide> from numpy._pytesttester import PytestTester
<ide><path>numpy/f2py/tests/test_quoted_character.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import sys
<add>import os
<add>import uuid
<add>from importlib import import_module
<ide> import pytest
<ide>
<add>import numpy.f2py
<add>
<ide> from numpy.testing import assert_equal
<ide> from . import util
<ide>
<ide> class TestQuotedCharacter(util.F2PyTest):
<ide> reason='Fails with MinGW64 Gfortran (Issue #9673)')
<ide> def test_quoted_character(self):
<ide> assert_equal(self.module.foo(), (b"'", b'"', b';', b'!', b'(', b')'))
<add>
<add>@pytest.mark.xfail(sys.version_info[0] < 3 and os.name == 'nt',
<add> reason="our Appveyor CI configuration does not"
<add> " have Fortran compilers available for"
<add> " Python 2.x")
<add>@pytest.mark.parametrize("extra_args", [
<add> # extra_args can be a list as of gh-11937
<add> ['--noopt', '--debug'],
<add> # test for string as well, using the same
<add> # fcompiler options
<add> '--noopt --debug',
<add> # also test absence of extra_args
<add> '',
<add> ])
<add>def test_f2py_init_compile(extra_args):
<add> # flush through the f2py __init__
<add> # compile() function code path
<add> # as a crude test for input handling
<add> # following migration from exec_command()
<add> # to subprocess.check_output() in gh-11937
<add>
<add> # the Fortran 77 syntax requires 6 spaces
<add> # before any commands, but more space may
<add> # be added; gfortran can also compile
<add> # with --ffree-form to remove the indentation
<add> # requirement; here, the Fortran source is
<add> # formatted to roughly match an example from
<add> # the F2PY User Guide
<add> fsource = '''
<add> integer function foo()
<add> foo = 10 + 5
<add> return
<add> end
<add> '''
<add> # use various helper functions in util.py to
<add> # enable robust build / compile and
<add> # reimport cycle in test suite
<add> d = util.get_module_dir()
<add> modulename = util.get_temp_module_name()
<add>
<add> cwd = os.getcwd()
<add> target = os.path.join(d, str(uuid.uuid4()) + '.f')
<add> # try running compile() with and without a
<add> # source_fn provided so that the code path
<add> # where a temporary file for writing Fortran
<add> # source is created is also explored
<add> for source_fn in [target, None]:
<add>
<add> # mimic the path changing behavior used
<add> # by build_module() in util.py, but don't
<add> # actually use build_module() because it
<add> # has its own invocation of subprocess
<add> # that circumvents the f2py.compile code
<add> # block under test
<add> try:
<add> os.chdir(d)
<add> ret_val = numpy.f2py.compile(fsource,
<add> modulename=modulename,
<add> extra_args=extra_args,
<add> source_fn=source_fn)
<add> finally:
<add> os.chdir(cwd)
<add>
<add> # check for compile success return value
<add> assert_equal(ret_val, 0)
<add>
<add> # we are not currently able to import the
<add> # Python-Fortran interface module on Windows /
<add> # Appveyor, even though we do get successful
<add> # compilation on that platform with Python 3.x
<add> if os.name != 'nt':
<add> # check for sensible result of Fortran function;
<add> # that means we can import the module name in Python
<add> # and retrieve the result of the sum operation
<add> return_check = import_module(modulename)
<add> calc_result = return_check.foo()
<add> assert_equal(calc_result, 15)
<add>
<add>def test_f2py_init_compile_failure():
<add> # verify an appropriate integer status
<add> # value returned by f2py.compile() when
<add> # invalid Fortran is provided
<add> ret_val = numpy.f2py.compile(b"invalid")
<add> assert_equal(ret_val, 1)
<add>
<add>def test_f2py_init_compile_bad_cmd():
<add> # verify that usage of invalid command in
<add> # f2py.compile() returns status value of 127
<add> # for historic consistency with exec_command()
<add> # error handling
<add>
<add> # patch the sys Python exe path temporarily to
<add> # induce an OSError downstream
<add> # NOTE: how bad of an idea is this patching?
<add> try:
<add> temp = sys.executable
<add> sys.executable = 'does not exist'
<add>
<add> # the OSError should take precedence over the invalid
<add> # Fortran
<add> ret_val = numpy.f2py.compile(b"invalid")
<add>
<add> assert_equal(ret_val, 127)
<add> finally:
<add> sys.executable = temp | 2 |
PHP | PHP | move getter above setter | 71980d06dc175170dd81a3b5e064ab1c93af12b7 | <ide><path>src/Illuminate/Http/JsonResponse.php
<ide> public function setData($data = array())
<ide> return $this->update();
<ide> }
<ide>
<add> /**
<add> * Get the JSON encoding options.
<add> *
<add> * @return int
<add> */
<add> public function getJsonOptions()
<add> {
<add> return $this->jsonOptions;
<add> }
<add>
<ide> /**
<ide> * Set the JSON encoding options.
<ide> *
<ide> public function setJsonOptions($options)
<ide> return $this->setData($this->getData());
<ide> }
<ide>
<del> /**
<del> * Get the JSON encoding options.
<del> *
<del> * @return int
<del> */
<del> public function getJsonOptions()
<del> {
<del> return $this->jsonOptions;
<del> }
<del>
<ide> } | 1 |
Javascript | Javascript | add ember.handlebars action helper | 60c55e3085b5c36569328be4414faa0383c5e3ba | <ide><path>packages/ember-handlebars/lib/helpers.js
<ide> require("ember-handlebars/helpers/unbound");
<ide> require("ember-handlebars/helpers/debug");
<ide> require("ember-handlebars/helpers/each");
<ide> require("ember-handlebars/helpers/template");
<add>require("ember-handlebars/helpers/action");
<ide>\ No newline at end of file
<ide><path>packages/ember-handlebars/lib/helpers/action.js
<add>require('ember-handlebars/ext');
<add>
<add>var EmberHandlebars = Ember.Handlebars, getPath = Ember.Handlebars.getPath;
<add>
<add>var ActionHelper = EmberHandlebars.ActionHelper = {};
<add>
<add>ActionHelper.registerAction = function(actionName, eventName, target, view) {
<add> var actionId = (++jQuery.uuid).toString(),
<add> existingHandler = view[eventName],
<add> originalRerender = view.rerender,
<add> handler;
<add>
<add> if (existingHandler) {
<add> var handler = function(event) {
<add> if ($(event.target).closest('[data-ember-action]').attr('data-ember-action') === actionId) {
<add> return target[actionName](event);
<add> } else if (existingHandler) {
<add> return existingHandler.call(view, event);
<add> }
<add> };
<add> } else {
<add> var handler = function(event) {
<add> if ($(event.target).closest('[data-ember-action]').attr('data-ember-action') === actionId) {
<add> return target[actionName](event);
<add> }
<add> };
<add> }
<add>
<add> view[eventName] = handler;
<add>
<add> view.rerender = function() {
<add> if (existingHandler) {
<add> view[eventName] = existingHandler;
<add> } else {
<add> view[eventName] = null;
<add> }
<add> originalRerender.call(this);
<add> };
<add>
<add> return actionId;
<add>};
<add>
<add>EmberHandlebars.registerHelper('action', function(actionName, options) {
<add> var hash = options.hash || {},
<add> eventName = options.hash.on || "click",
<add> view = options.data.view,
<add> target;
<add>
<add> if (view.isVirtual) { view = view.get('parentView'); }
<add> target = options.hash.target ? getPath(this, options.hash.target) : view;
<add>
<add> var actionId = ActionHelper.registerAction(actionName, eventName, target, view);
<add> return new EmberHandlebars.SafeString('data-ember-action="' + actionId + '"');
<add>});
<ide><path>packages/ember-handlebars/tests/helpers/action_test.js
<add>var application, view,
<add> ActionHelper = Ember.Handlebars.ActionHelper,
<add> originalRegisterAction = ActionHelper.registerAction;
<add>
<add>var appendView = function() {
<add> Ember.run(function() { view.appendTo('#qunit-fixture'); });
<add>};
<add>
<add>module("Ember.Handlebars - action helper", {
<add> setup: function() {
<add> application = Ember.Application.create();
<add> },
<add>
<add> teardown: function() {
<add> Ember.run(function() {
<add> view.destroy();
<add> application.destroy();
<add> });
<add> }
<add>});
<add>
<add>test("should output a data attribute with a guid", function() {
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<a href="#" {{action "edit"}}>')
<add> });
<add>
<add> appendView();
<add>
<add> ok(view.$('a').attr('data-ember-action').match(/\d+/), "A data-ember-action attribute with a guid was added");
<add>});
<add>
<add>test("should by default register a click event", function() {
<add> var registeredEventName;
<add>
<add> ActionHelper.registerAction = function(_, eventName) {
<add> registeredEventName = eventName;
<add> };
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<a href="#" {{action "edit"}}>')
<add> });
<add>
<add> appendView();
<add>
<add> equals(registeredEventName, 'click', "The click event was properly registered");
<add>
<add> ActionHelper.registerAction = originalRegisterAction;
<add>});
<add>
<add>test("should allow alternative events to be handled", function() {
<add> var registeredEventName;
<add>
<add> ActionHelper.registerAction = function(_, eventName) {
<add> registeredEventName = eventName;
<add> };
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<a href="#" {{action "edit" on="mouseUp"}}>')
<add> });
<add>
<add> appendView();
<add>
<add> equals(registeredEventName, 'mouseUp', "The alternative mouseUp event was properly registered");
<add>
<add> ActionHelper.registerAction = originalRegisterAction;
<add>});
<add>
<add>test("should by default target the parent view", function() {
<add> var registeredTarget;
<add>
<add> ActionHelper.registerAction = function(_, _, target) {
<add> registeredTarget = target;
<add> };
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<a href="#" {{action "edit"}}>')
<add> });
<add>
<add> appendView();
<add>
<add> equals(registeredTarget, view, "The parent view was registered as the target");
<add>
<add> ActionHelper.registerAction = originalRegisterAction;
<add>});
<add>
<add>test("should allow a target to be specified", function() {
<add> var registeredTarget;
<add>
<add> ActionHelper.registerAction = function(_, _, target) {
<add> registeredTarget = target;
<add> };
<add>
<add> var anotherTarget = Ember.View.create();
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<a href="#" {{action "edit" target="anotherTarget"}}>'),
<add> anotherTarget: anotherTarget
<add> });
<add>
<add> appendView();
<add>
<add> equals(registeredTarget, anotherTarget, "The specified target was registered");
<add>
<add> ActionHelper.registerAction = originalRegisterAction;
<add>});
<add>
<add>test("should attach an event handler on the parent view", function() {
<add> var eventHandlerWasCalled = false;
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<a href="#" {{action "edit"}}>click me</a>'),
<add> edit: function() { eventHandlerWasCalled = true; }
<add> });
<add>
<add> appendView();
<add>
<add> ok('function' === typeof view.click, "An event handler was added to the parent view");
<add>
<add> view.$('a').trigger('click');
<add>
<add> ok(eventHandlerWasCalled, "The event handler was called");
<add>});
<add>
<add>test("should wrap an existing event handler on the parent view", function() {
<add> var eventHandlerWasCalled = false,
<add> originalEventHandlerWasCalled = false;
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<a href="#" {{action "edit"}}>click me</a>'),
<add> click: function() { originalEventHandlerWasCalled = true; },
<add> edit: function() { eventHandlerWasCalled = true; }
<add> });
<add>
<add> appendView();
<add>
<add> view.$('a').trigger('click');
<add>
<add> ok(eventHandlerWasCalled, "The event handler was called");
<add> ok(!originalEventHandlerWasCalled, "The parent view's event handler wasn't called");
<add>
<add> eventHandlerWasCalled = originalEventHandlerWasCalled = false;
<add>
<add> view.$().trigger('click');
<add>
<add> ok(!eventHandlerWasCalled, "The event handler wasn't called");
<add> ok(originalEventHandlerWasCalled, "The parent view's event handler was called");
<add>});
<add>
<add>test("should be able to use action more than once for the same event within a view", function() {
<add> var editWasCalled = false,
<add> deleteWasCalled = false,
<add> originalEventHandlerWasCalled = false;
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile(
<add> '<a id="edit" href="#" {{action "edit"}}>edit</a><a id="delete" href="#" {{action "delete"}}>delete</a>'
<add> ),
<add> click: function() { originalEventHandlerWasCalled = true; },
<add> edit: function() { editWasCalled = true; },
<add> delete: function() { deleteWasCalled = true; }
<add> });
<add>
<add> appendView();
<add>
<add> view.$('#edit').trigger('click');
<add>
<add> ok(editWasCalled && !deleteWasCalled && !originalEventHandlerWasCalled, "Only the edit action was called");
<add>
<add> editWasCalled = deleteWasCalled = originalEventHandlerWasCalled = false;
<add>
<add> view.$('#delete').trigger('click');
<add>
<add> ok(!editWasCalled && deleteWasCalled && !originalEventHandlerWasCalled, "Only the delete action was called");
<add>
<add> editWasCalled = deleteWasCalled = originalEventHandlerWasCalled = false;
<add>
<add> view.$().trigger('click');
<add>
<add> ok(!editWasCalled && !deleteWasCalled && originalEventHandlerWasCalled, "Only the original event handler was called");
<add>});
<add>
<add>test("should work properly in an #each block", function() {
<add> var eventHandlerWasCalled = false;
<add>
<add> view = Ember.View.create({
<add> items: Ember.A([1, 2, 3, 4]),
<add> template: Ember.Handlebars.compile('{{#each items}}<a href="#" {{action "edit"}}>click me</a>{{/each}}'),
<add> edit: function() { eventHandlerWasCalled = true; }
<add> });
<add>
<add> appendView();
<add>
<add> ok('function' === typeof view.click, "The event handler was added to the parent view");
<add>
<add> view.$('a').trigger('click');
<add>
<add> ok(eventHandlerWasCalled, "The event handler was called");
<add>});
<add>
<add>test("should work properly in a #with block", function() {
<add> var eventHandlerWasCalled = false;
<add>
<add> view = Ember.View.create({
<add> something: {ohai: 'there'},
<add> template: Ember.Handlebars.compile('{{#with something}}<a href="#" {{action "edit"}}>click me</a>{{/with}}'),
<add> edit: function() { eventHandlerWasCalled = true; }
<add> });
<add>
<add> appendView();
<add>
<add> ok('function' === typeof view.click, "The event handler was added to the parent view");
<add>
<add> view.$('a').trigger('click');
<add>
<add> ok(eventHandlerWasCalled, "The event handler was called");
<add>});
<add>
<add>test("should unwrap parent view event handlers on rerender", function() {
<add> var eventHandlerWasCalled = false;
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<a href="#" {{action "edit"}}>click me</a>'),
<add> edit: function() { eventHandlerWasCalled = true; }
<add> });
<add>
<add> appendView();
<add>
<add> ok('function' === typeof view.click, "The event handler was added to the parent view");
<add>
<add> view.rerender();
<add>
<add> ok(view.click === null, "On rerender, the event handler was removed");
<add>
<add> Ember.run.end();
<add>
<add> ok('function' === typeof view.click, "After rerender completes, a new event handler was added");
<add>});
<add>
<add>test("should properly capture events on child elements of a container with an action", function() {
<add> var eventHandlerWasCalled = false;
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile('<div {{action "edit"}}><button>click me</button></div>'),
<add> edit: function() { eventHandlerWasCalled = true; }
<add> });
<add>
<add> appendView();
<add>
<add> view.$('button').trigger('click');
<add>
<add> ok(eventHandlerWasCalled, "Event on a child element triggered the action of it's parent")
<add>}); | 3 |
Go | Go | add exec to the commands list | fccb02622183ee93036d4f5068817830f3297ab5 | <ide><path>docker/flags.go
<ide> func init() {
<ide> {"cp", "Copy files/folders from a container's filesystem to the host path"},
<ide> {"diff", "Inspect changes on a container's filesystem"},
<ide> {"events", "Get real time events from the server"},
<add> {"exec", "Run a command in an existing container"},
<ide> {"export", "Stream the contents of a container as a tar archive"},
<ide> {"history", "Show the history of an image"},
<ide> {"images", "List images"}, | 1 |
Javascript | Javascript | refine invariant error message at scrolltoindex | 78d2b3c8138f54c2433958b0ad6b9f52ca59115a | <ide><path>Libraries/Lists/VirtualizedList.js
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> } = this.props;
<ide> const {animated, index, viewOffset, viewPosition} = params;
<ide> invariant(
<del> index >= 0 && index < getItemCount(data),
<del> `scrollToIndex out of range: requested index ${index} but maximum is ${getItemCount(
<add> index >= 0,
<add> `scrollToIndex out of range: requested index ${index} but minimum is 0`,
<add> );
<add> invariant(
<add> getItemCount(data) >= 1,
<add> `scrollToIndex out of range: item length ${getItemCount(
<add> data,
<add> )} but minimum is 1`,
<add> );
<add> invariant(
<add> index < getItemCount(data),
<add> `scrollToIndex out of range: requested index ${index} is out of 0 to ${getItemCount(
<ide> data,
<ide> ) - 1}`,
<ide> );
<ide><path>Libraries/Lists/__tests__/VirtualizedList-test.js
<ide> describe('VirtualizedList', () => {
<ide> console.error.mockRestore();
<ide> }
<ide> });
<add>
<add> it('throws if using scrollToIndex with index less than 0', () => {
<add> const component = ReactTestRenderer.create(
<add> <VirtualizedList
<add> data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
<add> renderItem={({item}) => <item value={item.key} />}
<add> getItem={(data, index) => data[index]}
<add> getItemCount={data => data.length}
<add> />,
<add> );
<add> const instance = component.getInstance();
<add>
<add> expect(() => instance.scrollToIndex({index: -1})).toThrow(
<add> 'scrollToIndex out of range: requested index -1 but minimum is 0',
<add> );
<add> });
<add>
<add> it('throws if using scrollToIndex when item length is less than 1', () => {
<add> const component = ReactTestRenderer.create(
<add> <VirtualizedList
<add> data={[]}
<add> renderItem={({item}) => <item value={item.key} />}
<add> getItem={(data, index) => data[index]}
<add> getItemCount={data => data.length}
<add> />,
<add> );
<add> const instance = component.getInstance();
<add>
<add> expect(() => instance.scrollToIndex({index: 1})).toThrow(
<add> 'scrollToIndex out of range: item length 0 but minimum is 1',
<add> );
<add> });
<add>
<add> it('throws if using scrollToIndex when requested index is bigger than or equal to item length', () => {
<add> const component = ReactTestRenderer.create(
<add> <VirtualizedList
<add> data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
<add> renderItem={({item}) => <item value={item.key} />}
<add> getItem={(data, index) => data[index]}
<add> getItemCount={data => data.length}
<add> />,
<add> );
<add> const instance = component.getInstance();
<add>
<add> expect(() => instance.scrollToIndex({index: 3})).toThrow(
<add> 'scrollToIndex out of range: requested index 3 is out of 0 to 2',
<add> );
<add> });
<ide> }); | 2 |
Text | Text | add mention of centralized vcs to svn article | 11ed97e860edafb27755387b7c2359ecb03dd56d | <ide><path>guide/english/svn/index.md
<ide> title: Apache Subversion
<ide> ## Apache Subversion
<ide> Apache Subversion is a software versioning and revision control system distributed as open source under the [Apache License](https://en.wikipedia.org/wiki/Apache_License). It is used to maintain current and historical versions of files such as source code, web pages and documentation.
<ide>
<add>
<add>Subversion (often abbreviated 'svn') is arguably the most well-known example of a centralized [version control system](https://en.wikipedia.org/wiki/Version_control). In a centralized system, there is generally considered one master repository that all developers pull and commit to. As such, frequent pulling and commiting as well as communication between developers is extremely important when working with svn.
<add>
<ide> ### Alternatives to Subversion
<ide> * [Git](https://en.wikipedia.org/wiki/Git)
<ide> * [GNU Bazaar](https://en.wikipedia.org/wiki/GNU_Bazaar)
<ide> * [CVS](https://en.wikipedia.org/wiki/Concurrent_Versions_System)
<ide>
<add>
<ide> For downloads and documentation, visit [Apache Subversion official site](https://subversion.apache.org) | 1 |
Java | Java | harmonize visibility of runtimehints builders | 444e06fa2299b07ce9e6e763a611f129a213ce7d | <ide><path>spring-core/src/main/java/org/springframework/aot/hint/ResourceBundleHint.java
<ide> public final class ResourceBundleHint implements ConditionalHint {
<ide> private final String baseName;
<ide>
<ide> @Nullable
<del> private TypeReference reachableType;
<add> private final TypeReference reachableType;
<ide>
<ide>
<ide> ResourceBundleHint(Builder builder) {
<ide> public static class Builder {
<ide> @Nullable
<ide> private TypeReference reachableType;
<ide>
<add> Builder(String baseName) {
<add> this.baseName = baseName;
<add> }
<add>
<ide> /**
<ide> * Make this hint conditional on the fact that the specified type
<ide> * can be resolved.
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/ResourceHints.java
<ide> public ResourceHints registerType(Class<?> type) {
<ide> * @return {@code this}, to facilitate method chaining
<ide> */
<ide> public ResourceHints registerResourceBundle(String baseName, @Nullable Consumer<ResourceBundleHint.Builder> resourceHint) {
<del> ResourceBundleHint.Builder builder = new ResourceBundleHint.Builder().baseName(baseName);
<add> ResourceBundleHint.Builder builder = new ResourceBundleHint.Builder(baseName);
<ide> if (resourceHint != null) {
<ide> resourceHint.accept(builder);
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/ResourcePatternHints.java
<ide> public static class Builder {
<ide>
<ide> private final Set<ResourcePatternHint> excludes = new LinkedHashSet<>();
<ide>
<add> Builder() {
<add> }
<add>
<ide> /**
<ide> * Includes the resources matching the specified pattern.
<ide> * @param reachableType the type that should be reachable for this hint to apply | 3 |
Text | Text | fix small typo | a79a96ddaa05f0cdf647fd4dce779d74459614eb | <ide><path>examples/language-modeling/README.md
<ide> context length for permutation language modeling.
<ide> The `--max_span_length` flag may also be used to limit the length of a span of masked tokens used
<ide> for permutation language modeling.
<ide>
<del>Here is how to fine-tun XLNet on wikitext-2:
<add>Here is how to fine-tune XLNet on wikitext-2:
<ide>
<ide> ```bash
<ide> python run_plm.py \ | 1 |
Ruby | Ruby | raise an error when no formula | 816fdd0f5aeaa5b862204476afdb947ac1cf863d | <ide><path>Library/Homebrew/dev-cmd/bump-revision.rb
<ide> def bump_revision
<ide> # user path, too.
<ide> ENV["PATH"] = ENV["HOMEBREW_PATH"]
<ide>
<add> raise FormulaUnspecifiedError if ARGV.formulae.empty?
<ide> raise "Multiple formulae given, only one is allowed." if ARGV.formulae.length > 1
<ide>
<ide> formula = ARGV.formulae.first | 1 |
Javascript | Javascript | add test for more than two nested async helpers | 5f037f29a485a35395021749d6c0ae0c197df74e | <ide><path>packages/ember-testing/tests/acceptance_test.js
<ide> test("Nested async helpers", function() {
<ide> });
<ide> });
<ide>
<add>test("Multiple nested async helpers", function() {
<add> expect(2);
<add>
<add> visit('/posts');
<add>
<add> andThen(function() {
<add> click('a:first', '#comments-link');
<add>
<add> fillIn('.ember-text-field', "hello");
<add> fillIn('.ember-text-field', "goodbye");
<add> });
<add>
<add> andThen(function() {
<add> equal(find('.ember-text-field').val(), 'goodbye', "Fillin successfully works");
<add> equal(currentRoute, 'comments', "Successfully visited comments route");
<add> });
<add>});
<add>
<ide> test("Helpers nested in thens", function() {
<ide> expect(3);
<ide> | 1 |
PHP | PHP | handle data attachments without warnings | 6c0d8dfa1f294f5da88c306f2ae464b9ac66d559 | <ide><path>src/Mailer/Email.php
<ide> public function setAttachments($attachments)
<ide> $name = basename($fileInfo['file']);
<ide> }
<ide> }
<del> if (!isset($fileInfo['mimetype']) && function_exists('mime_content_type')) {
<add> if (!isset($fileInfo['mimetype']) && isset($fileInfo['file']) && function_exists('mime_content_type')) {
<ide> $fileInfo['mimetype'] = mime_content_type($fileInfo['file']);
<ide> }
<ide> if (!isset($fileInfo['mimetype'])) {
<ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public function testViewVars()
<ide> *
<ide> * @return void
<ide> */
<del> public function testAttachments()
<add> public function testSetAttachments()
<ide> {
<ide> $this->Email->setAttachments(CAKE . 'basics.php');
<ide> $expected = [
<ide> public function testAttachments()
<ide> $this->Email->setAttachments([['nofile' => CAKE . 'basics.php', 'mimetype' => 'text/plain']]);
<ide> }
<ide>
<add> /**
<add> * Test send() with no template and data string attachment and no mimetype
<add> *
<add> * @return void
<add> */
<add> public function testSetAttachmentDataNoMimetype()
<add> {
<add> $this->Email->setAttachments(['cake.icon.gif' => [
<add> 'data' => 'test',
<add> ]]);
<add> $result = $this->Email->getAttachments();
<add> $expected = [
<add> 'cake.icon.gif' => [
<add> 'data' => base64_encode('test') . "\r\n",
<add> 'mimetype' => 'application/octet-stream'
<add> ],
<add> ];
<add> $this->assertSame($expected, $this->Email->getAttachments());
<add> }
<add>
<ide> /**
<ide> * testTransport method
<ide> *
<ide> public function testSendNoTemplateWithAttachments()
<ide> *
<ide> * @return void
<ide> */
<del>
<ide> public function testSendNoTemplateWithDataStringAttachment()
<ide> {
<ide> $this->Email->setTransport('debug'); | 2 |
Javascript | Javascript | replace vars in per_thread.js | 9240e54404c5de325db60f8c1ad5e92483cd190b | <ide><path>lib/internal/process/per_thread.js
<ide> function wrapProcessMethods(binding) {
<ide> }
<ide>
<ide> function kill(pid, sig) {
<del> var err;
<add> let err;
<ide>
<ide> // eslint-disable-next-line eqeqeq
<ide> if (pid != (pid | 0)) { | 1 |
Ruby | Ruby | set hash value instead of using merge! | d9f20c575a29e8ec8eb549aae63b7c304dc27489 | <ide><path>activemodel/lib/active_model/validations/validates.rb
<ide> def validates(*attributes)
<ide> raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
<ide> raise ArgumentError, "You need to supply at least one validation" if validations.empty?
<ide>
<del> defaults.merge!(:attributes => attributes)
<add> defaults[:attributes] = attributes
<ide>
<ide> validations.each do |key, options|
<ide> next unless options | 1 |
Python | Python | fix append to an empty chain. fixes . | f148709062f728104dcca32d475d11af4a496be3 | <ide><path>celery/canvas.py
<ide> def __or__(self, other):
<ide> return sig
<ide> elif isinstance(other, Signature):
<ide> if isinstance(self, _chain):
<del> if isinstance(self.tasks[-1], group):
<add> if self.tasks and isinstance(self.tasks[-1], group):
<ide> # CHAIN [last item is group] | TASK -> chord
<ide> sig = self.clone()
<ide> sig.tasks[-1] = chord(
<ide> sig.tasks[-1], other, app=self._app)
<ide> return sig
<del> elif isinstance(self.tasks[-1], chord):
<add> elif self.tasks and isinstance(self.tasks[-1], chord):
<ide> # CHAIN [last item is chord] -> chain with chord body.
<ide> sig = self.clone()
<ide> sig.tasks[-1].body = sig.tasks[-1].body | other
<ide><path>t/unit/tasks/test_canvas.py
<ide> def test_chord_sets_result_parent(self):
<ide> seen.add(node.id)
<ide> node = node.parent
<ide>
<add> def test_append_to_empty_chain(self):
<add> x = chain()
<add> x |= self.add.s(1, 1)
<add> x |= self.add.s(1)
<add> x.freeze()
<add> tasks, _ = x._frozen
<add> assert len(tasks) == 2
<add>
<add> assert x.apply().get() == 3
<add>
<ide>
<ide> class test_group(CanvasCase):
<ide> | 2 |
Javascript | Javascript | add missing crypto checks | 2ba1740ba17193face8fe82458ed9912fa35ff6f | <ide><path>test/internet/test-tls-connnect-cnnic.js
<ide> // 0x44, 0xB5, 0x00, 0x76, 0x48, 0x11, 0x41, 0xED },
<ide> // },
<ide> // in src/CNNICHashWhitelist.inc
<add>
<add>var common = require('../common');
<add>if (!common.hasCrypto) {
<add> console.log('1..0 # Skipped: missing crypto');
<add> process.exit();
<add>}
<add>
<ide> var tls = require('tls');
<ide> var socket = tls.connect(443, 'www1.cnnic.cn', function() {
<ide> socket.resume();
<ide><path>test/internet/test-tls-connnect-melissadata.js
<ide> 'use strict';
<ide> // Test for authorized access to the server which has a cross root
<ide> // certification between Starfield Class 2 and ValiCert Class 2
<add>
<add>var common = require('../common');
<add>if (!common.hasCrypto) {
<add> console.log('1..0 # Skipped: missing crypto');
<add> process.exit();
<add>}
<add>
<ide> var tls = require('tls');
<ide> var socket = tls.connect(443, 'address.melissadata.net', function() {
<ide> socket.resume(); | 2 |
Python | Python | add pytest compatible run_module_suite | 787b4a094c0a4f2aac338fe2a22e6e923ea14baa | <ide><path>numpy/testing/pytest_tools/nosetester.py
<ide> def get_package_name(filepath):
<ide> return '.'.join(pkg_name)
<ide>
<ide>
<del>if False:
<del> # disable run_module_suite and NoseTester
<del> # until later
<del> def run_module_suite(file_to_run=None, argv=None):
<del> """
<del> Run a test module.
<add>def run_module_suite(file_to_run=None, argv=None):
<add> """
<add> Run a test module.
<ide>
<del> Equivalent to calling ``$ nosetests <argv> <file_to_run>`` from
<del> the command line
<add> Equivalent to calling ``$ nosetests <argv> <file_to_run>`` from
<add> the command line. This version is for pytest rather than nose.
<ide>
<del> Parameters
<del> ----------
<del> file_to_run : str, optional
<del> Path to test module, or None.
<del> By default, run the module from which this function is called.
<del> argv : list of strings
<del> Arguments to be passed to the nose test runner. ``argv[0]`` is
<del> ignored. All command line arguments accepted by ``nosetests``
<del> will work. If it is the default value None, sys.argv is used.
<add> Parameters
<add> ----------
<add> file_to_run : str, optional
<add> Path to test module, or None.
<add> By default, run the module from which this function is called.
<add> argv : list of strings
<add> Arguments to be passed to the pytest runner. ``argv[0]`` is
<add> ignored. All command line arguments accepted by ``pytest``
<add> will work. If it is the default value None, sys.argv is used.
<ide>
<del> .. versionadded:: 1.9.0
<add> .. versionadded:: 1.14.0
<ide>
<del> Examples
<del> --------
<del> Adding the following::
<add> Examples
<add> --------
<add> Adding the following::
<ide>
<del> if __name__ == "__main__" :
<del> run_module_suite(argv=sys.argv)
<add> if __name__ == "__main__" :
<add> run_module_suite(argv=sys.argv)
<ide>
<del> at the end of a test module will run the tests when that module is
<del> called in the python interpreter.
<add> at the end of a test module will run the tests when that module is
<add> called in the python interpreter.
<ide>
<del> Alternatively, calling::
<add> Alternatively, calling::
<ide>
<del> >>> run_module_suite(file_to_run="numpy/tests/test_matlib.py")
<add> >>> run_module_suite(file_to_run="numpy/tests/test_matlib.py")
<ide>
<del> from an interpreter will run all the test routine in 'test_matlib.py'.
<del> """
<add> from an interpreter will run all the test routine in 'test_matlib.py'.
<add> """
<add> import pytest
<add> if file_to_run is None:
<add> f = sys._getframe(1)
<add> file_to_run = f.f_locals.get('__file__', None)
<ide> if file_to_run is None:
<del> f = sys._getframe(1)
<del> file_to_run = f.f_locals.get('__file__', None)
<del> if file_to_run is None:
<del> raise AssertionError
<del>
<del> if argv is None:
<del> argv = sys.argv + [file_to_run]
<del> else:
<del> argv = argv + [file_to_run]
<add> raise AssertionError
<ide>
<del> nose = import_nose()
<del> from .noseclasses import KnownFailurePlugin
<del> nose.run(argv=argv, addplugins=[KnownFailurePlugin()])
<add> if argv is None:
<add> argv = sys.argv + [file_to_run]
<add> else:
<add> argv = argv + [file_to_run]
<ide>
<add> pytest.main(argv)
<ide>
<add>if False:
<add> # disable run_module_suite and NoseTester
<add> # until later
<ide> class NoseTester(object):
<ide> """
<ide> Nose test runner.
<ide> def bench(self, label='fast', verbose=1, extra_argv=None):
<ide> return nose.run(argv=argv, addplugins=add_plugins)
<ide> else:
<ide>
<del> def run_module_suite(file_to_run=None, argv=None):
<del> pass
<del>
<del>
<ide> class NoseTester(object):
<ide> def __init__(self, package=None, raise_warnings="release", depth=0):
<ide> pass
<ide> def test(self, label='fast', verbose=1, extra_argv=None,
<ide>
<ide> def bench(self, label='fast', verbose=1, extra_argv=None):
<ide> pass
<del>
<add>
<ide>
<ide> def _numpy_tester():
<ide> if hasattr(np, "__version__") and ".dev0" in np.__version__: | 1 |
Ruby | Ruby | rearrange the config merger some more | de9f2f63b8548e2a8950c1727f0a1a6893713505 | <ide><path>activerecord/lib/active_record/connection_handling.rb
<ide> def establish_connection(spec = nil)
<ide> class MergeAndResolveDefaultUrlConfig # :nodoc:
<ide> def initialize(raw_configurations)
<ide> @raw_config = raw_configurations.dup
<add> @env = DEFAULT_ENV.call.to_s
<ide> end
<ide>
<ide> # Returns fully resolved connection hashes.
<ide> def resolve
<ide>
<ide> private
<ide> def config
<del> env = DEFAULT_ENV.call.to_s
<del>
<del> cfg = Hash.new do |hash, key|
<del> entry = @raw_config[key]
<del> env_url = nil
<del>
<del> if key.to_s == env
<del> env_url = ENV["DATABASE_URL"]
<add> @raw_config.dup.tap do |cfg|
<add> urls_in_environment.each do |key, url|
<add> cfg[key] ||= {}
<add> cfg[key]["url"] ||= url
<ide> end
<add> end
<add> end
<ide>
<del> env_url ||= ENV["DATABASE_URL_#{key.upcase}"]
<del>
<del> if env_url
<del> entry ||= {}
<del> entry.merge!("url" => env_url) { |h, v1, v2| v1 || v2 }
<add> def urls_in_environment
<add> {}.tap do |mapping|
<add> ENV.each do |k, v|
<add> if k =~ /\ADATABASE_URL_(.*)/
<add> mapping[$1.downcase] = v
<add> end
<ide> end
<ide>
<del> hash[key] = entry if entry
<add> # Check for this last, because it is prioritised over the
<add> # longer "DATABASE_URL_#{@env}" spelling
<add> mapping[@env] = ENV['DATABASE_URL'] if ENV['DATABASE_URL']
<ide> end
<del>
<del> @raw_config.keys.each {|k| cfg[k] }
<del> cfg[env]
<del>
<del> cfg
<ide> end
<ide> end
<ide> | 1 |
Mixed | PHP | apply geteventmanager() in src | 4eb9fd139c1a8234f36bcca37e9fe94a995c37e9 | <ide><path>src/Controller/Component/AuthComponent.php
<ide> class AuthComponent extends Component
<ide> public function initialize(array $config)
<ide> {
<ide> $controller = $this->_registry->getController();
<del> $this->eventManager($controller->eventManager());
<add> $this->eventManager($controller->getEventManager());
<ide> $this->response =& $controller->response;
<ide> $this->session = $controller->request->getSession();
<ide> }
<ide> public function constructAuthenticate()
<ide> }
<ide> $config = array_merge($global, (array)$config);
<ide> $this->_authenticateObjects[$alias] = new $className($this->_registry, $config);
<del> $this->eventManager()->on($this->_authenticateObjects[$alias]);
<add> $this->getEventManager()->on($this->_authenticateObjects[$alias]);
<ide> }
<ide>
<ide> return $this->_authenticateObjects;
<ide><path>src/Controller/ComponentRegistry.php
<ide> public function getController()
<ide> public function setController(Controller $controller)
<ide> {
<ide> $this->_Controller = $controller;
<del> $this->eventManager($controller->eventManager());
<add> $this->eventManager($controller->getEventManager());
<ide> }
<ide>
<ide> /**
<ide> protected function _create($class, $alias, $config)
<ide> $instance = new $class($this, $config);
<ide> $enable = isset($config['enabled']) ? $config['enabled'] : true;
<ide> if ($enable) {
<del> $this->eventManager()->on($instance);
<add> $this->getEventManager()->on($instance);
<ide> }
<ide>
<ide> return $instance;
<ide><path>src/Controller/Controller.php
<ide> public function __construct(ServerRequest $request = null, Response $response =
<ide>
<ide> $this->_mergeControllerVars();
<ide> $this->_loadComponents();
<del> $this->eventManager()->on($this);
<add> $this->getEventManager()->on($this);
<ide> }
<ide>
<ide> /**
<ide><path>src/Core/ObjectRegistry.php
<ide> public function set($objectName, $object)
<ide> $this->unload($objectName);
<ide> }
<ide> if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
<del> $this->eventManager()->on($object);
<add> $this->getEventManager()->on($object);
<ide> }
<ide> $this->_loaded[$name] = $object;
<ide> }
<ide> public function unload($objectName)
<ide>
<ide> $object = $this->_loaded[$objectName];
<ide> if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
<del> $this->eventManager()->off($object);
<add> $this->getEventManager()->off($object);
<ide> }
<ide> unset($this->_loaded[$objectName]);
<ide> }
<ide><path>src/Error/ExceptionRenderer.php
<ide> protected function _shutdown()
<ide> {
<ide> $this->controller->dispatchEvent('Controller.shutdown');
<ide> $dispatcher = DispatcherFactory::create();
<del> $eventManager = $dispatcher->eventManager();
<add> $eventManager = $dispatcher->getEventManager();
<ide> foreach ($dispatcher->filters() as $filter) {
<ide> $eventManager->on($filter);
<ide> }
<ide><path>src/Event/EventDispatcherTrait.php
<ide> public function dispatchEvent($name, $data = null, $subject = null)
<ide> }
<ide>
<ide> $event = new $this->_eventClass($name, $subject, $data);
<del> $this->eventManager()->dispatch($event);
<add> $this->getEventManager()->dispatch($event);
<ide>
<ide> return $event;
<ide> }
<ide><path>src/Event/README.md
<ide> class Orders
<ide> $event = new Event('Orders.afterPlace', $this, [
<ide> 'order' => $order
<ide> ]);
<del> $this->eventManager()->dispatch($event);
<add> $this->getEventManager()->dispatch($event);
<ide> }
<ide> }
<ide>
<ide> $orders = new Orders();
<del>$orders->eventManager()->on(function ($event) {
<add>$orders->getEventManager()->on(function ($event) {
<ide> // Do something after the order was placed
<ide> ...
<ide> }, 'Orders.afterPlace');
<ide><path>src/Http/ActionDispatcher.php
<ide> protected function _invoke(Controller $controller)
<ide> public function addFilter(EventListenerInterface $filter)
<ide> {
<ide> $this->filters[] = $filter;
<del> $this->eventManager()->on($filter);
<add> $this->getEventManager()->on($filter);
<ide> }
<ide>
<ide> /**
<ide><path>src/ORM/BehaviorRegistry.php
<ide> public function __construct($table = null)
<ide> public function setTable(Table $table)
<ide> {
<ide> $this->_table = $table;
<del> $this->eventManager($table->eventManager());
<add> $this->eventManager($table->getEventManager());
<ide> }
<ide>
<ide> /**
<ide> protected function _create($class, $alias, $config)
<ide> $instance = new $class($this->_table, $config);
<ide> $enable = isset($config['enabled']) ? $config['enabled'] : true;
<ide> if ($enable) {
<del> $this->eventManager()->on($instance);
<add> $this->getEventManager()->on($instance);
<ide> }
<ide> $methods = $this->_getMethods($instance, $class, $alias);
<ide> $this->_methodMap += $methods['methods'];
<ide><path>src/Routing/Dispatcher.php
<ide> class Dispatcher
<ide> */
<ide> public function dispatch(ServerRequest $request, Response $response)
<ide> {
<del> $actionDispatcher = new ActionDispatcher(null, $this->eventManager(), $this->_filters);
<add> $actionDispatcher = new ActionDispatcher(null, $this->getEventManager(), $this->_filters);
<ide> $response = $actionDispatcher->dispatch($request, $response);
<ide> if (isset($request->params['return'])) {
<ide> return $response->body();
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> public function controllerSpy($event, $controller = null)
<ide> $controller = $event->getSubject();
<ide> }
<ide> $this->_controller = $controller;
<del> $events = $controller->eventManager();
<add> $events = $controller->getEventManager();
<ide> $events->on('View.beforeRender', function ($event, $viewFile) {
<ide> if (!$this->_viewName) {
<ide> $this->_viewName = $viewFile;
<ide><path>src/TestSuite/LegacyRequestDispatcher.php
<ide> public function execute($request)
<ide> $request = new ServerRequest($request);
<ide> $response = new Response();
<ide> $dispatcher = DispatcherFactory::create();
<del> $dispatcher->eventManager()->on(
<add> $dispatcher->getEventManager()->on(
<ide> 'Dispatcher.invokeController',
<ide> ['priority' => 999],
<ide> [$this->_test, 'controllerSpy']
<ide><path>src/View/CellTrait.php
<ide> protected function cell($cell, array $data = [], array $options = [])
<ide> protected function _createCell($className, $action, $plugin, $options)
<ide> {
<ide> /* @var \Cake\View\Cell $instance */
<del> $instance = new $className($this->request, $this->response, $this->eventManager(), $options);
<add> $instance = new $className($this->request, $this->response, $this->getEventManager(), $options);
<ide> $instance->template = Inflector::underscore($action);
<ide>
<ide> $builder = $instance->viewBuilder();
<ide><path>src/View/HelperRegistry.php
<ide> class HelperRegistry extends ObjectRegistry implements EventDispatcherInterface
<ide> public function __construct(View $view)
<ide> {
<ide> $this->_View = $view;
<del> $this->eventManager($view->eventManager());
<add> $this->eventManager($view->getEventManager());
<ide> }
<ide>
<ide> /**
<ide> protected function _create($class, $alias, $settings)
<ide> }
<ide> $enable = isset($settings['enabled']) ? $settings['enabled'] : true;
<ide> if ($enable) {
<del> $this->eventManager()->on($instance);
<add> $this->getEventManager()->on($instance);
<ide> }
<ide>
<ide> return $instance;
<ide><path>src/View/ViewVarsTrait.php
<ide> public function createView($viewClass = null)
<ide> $this->viewVars,
<ide> isset($this->request) ? $this->request : null,
<ide> isset($this->response) ? $this->response : null,
<del> $this instanceof EventDispatcherInterface ? $this->eventManager() : null
<add> $this instanceof EventDispatcherInterface ? $this->getEventManager() : null
<ide> );
<ide> }
<ide>
<ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php
<ide> public function testUnloadUnknown()
<ide> public function testSetTable()
<ide> {
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')->getMock();
<del> $table->expects($this->once())->method('eventManager');
<add> $table->expects($this->once())->method('getEventManager');
<ide>
<ide> $this->Behaviors->setTable($table);
<ide> } | 16 |
Python | Python | update examples/ner/run_ner.py to use automodel | 2b60a26b463ba59c60c8b2645ec1068a0481e8e2 | <ide><path>examples/ner/run_ner.py
<ide> from tqdm import tqdm, trange
<ide>
<ide> from transformers import (
<add> ALL_PRETRAINED_MODEL_ARCHIVE_MAP,
<ide> WEIGHTS_NAME,
<ide> AdamW,
<del> AlbertConfig,
<del> AlbertForTokenClassification,
<del> AlbertTokenizer,
<del> BertConfig,
<del> BertForTokenClassification,
<del> BertTokenizer,
<del> CamembertConfig,
<del> CamembertForTokenClassification,
<del> CamembertTokenizer,
<del> DistilBertConfig,
<del> DistilBertForTokenClassification,
<del> DistilBertTokenizer,
<del> RobertaConfig,
<del> RobertaForTokenClassification,
<del> RobertaTokenizer,
<del> XLMRobertaConfig,
<del> XLMRobertaForTokenClassification,
<del> XLMRobertaTokenizer,
<add> AutoConfig,
<add> AutoModelForTokenClassification,
<add> AutoTokenizer,
<ide> get_linear_schedule_with_warmup,
<ide> )
<add>from transformers.modeling_auto import MODEL_MAPPING
<ide> from utils_ner import convert_examples_to_features, get_labels, read_examples_from_file
<ide>
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide>
<del>ALL_MODELS = sum(
<del> (
<del> tuple(conf.pretrained_config_archive_map.keys())
<del> for conf in (BertConfig, RobertaConfig, DistilBertConfig, CamembertConfig, XLMRobertaConfig)
<del> ),
<del> (),
<del>)
<del>
<del>MODEL_CLASSES = {
<del> "albert": (AlbertConfig, AlbertForTokenClassification, AlbertTokenizer),
<del> "bert": (BertConfig, BertForTokenClassification, BertTokenizer),
<del> "roberta": (RobertaConfig, RobertaForTokenClassification, RobertaTokenizer),
<del> "distilbert": (DistilBertConfig, DistilBertForTokenClassification, DistilBertTokenizer),
<del> "camembert": (CamembertConfig, CamembertForTokenClassification, CamembertTokenizer),
<del> "xlmroberta": (XLMRobertaConfig, XLMRobertaForTokenClassification, XLMRobertaTokenizer),
<del>}
<add>ALL_MODELS = tuple(ALL_PRETRAINED_MODEL_ARCHIVE_MAP)
<add>MODEL_CLASSES = tuple(m.model_type for m in MODEL_MAPPING)
<ide>
<ide> TOKENIZER_ARGS = ["do_lower_case", "strip_accents", "keep_accents", "use_fast"]
<ide>
<ide> def main():
<ide> default=None,
<ide> type=str,
<ide> required=True,
<del> help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()),
<add> help="Model type selected in the list: " + ", ".join(MODEL_CLASSES),
<ide> )
<ide> parser.add_argument(
<ide> "--model_name_or_path",
<ide> def main():
<ide> torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab
<ide>
<ide> args.model_type = args.model_type.lower()
<del> config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
<del> config = config_class.from_pretrained(
<add> config = AutoConfig.from_pretrained(
<ide> args.config_name if args.config_name else args.model_name_or_path,
<ide> num_labels=num_labels,
<ide> id2label={str(i): label for i, label in enumerate(labels)},
<ide> def main():
<ide> )
<ide> tokenizer_args = {k: v for k, v in vars(args).items() if v is not None and k in TOKENIZER_ARGS}
<ide> logger.info("Tokenizer arguments: %s", tokenizer_args)
<del> tokenizer = tokenizer_class.from_pretrained(
<add> tokenizer = AutoTokenizer.from_pretrained(
<ide> args.tokenizer_name if args.tokenizer_name else args.model_name_or_path,
<ide> cache_dir=args.cache_dir if args.cache_dir else None,
<ide> **tokenizer_args,
<ide> )
<del> model = model_class.from_pretrained(
<add> model = AutoModelForTokenClassification.from_pretrained(
<ide> args.model_name_or_path,
<ide> from_tf=bool(".ckpt" in args.model_name_or_path),
<ide> config=config,
<ide> def main():
<ide> # Evaluation
<ide> results = {}
<ide> if args.do_eval and args.local_rank in [-1, 0]:
<del> tokenizer = tokenizer_class.from_pretrained(args.output_dir, **tokenizer_args)
<add> tokenizer = AutoTokenizer.from_pretrained(args.output_dir, **tokenizer_args)
<ide> checkpoints = [args.output_dir]
<ide> if args.eval_all_checkpoints:
<ide> checkpoints = list(
<ide> def main():
<ide> logger.info("Evaluate the following checkpoints: %s", checkpoints)
<ide> for checkpoint in checkpoints:
<ide> global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
<del> model = model_class.from_pretrained(checkpoint)
<add> model = AutoModelForTokenClassification.from_pretrained(checkpoint)
<ide> model.to(args.device)
<ide> result, _ = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="dev", prefix=global_step)
<ide> if global_step:
<ide> def main():
<ide> writer.write("{} = {}\n".format(key, str(results[key])))
<ide>
<ide> if args.do_predict and args.local_rank in [-1, 0]:
<del> tokenizer = tokenizer_class.from_pretrained(args.output_dir, **tokenizer_args)
<del> model = model_class.from_pretrained(args.output_dir)
<add> tokenizer = AutoTokenizer.from_pretrained(args.output_dir, **tokenizer_args)
<add> model = AutoModelForTokenClassification.from_pretrained(args.output_dir)
<ide> model.to(args.device)
<ide> result, predictions = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="test")
<ide> # Save results | 1 |
Ruby | Ruby | expand requirements recursively when modifying env | 53cf970312fb98d53fa5859bc039e453b60274cc | <ide><path>Library/Homebrew/build.rb
<ide> end
<ide>
<ide> def install f
<del> f.requirements.each { |dep| dep.modify_build_environment }
<add> f.recursive_requirements.each { |req| req.modify_build_environment }
<ide>
<ide> f.recursive_deps.uniq.each do |dep|
<ide> dep = Formula.factory dep
<ide><path>Library/Homebrew/formula.rb
<ide> def self.expand_deps f
<ide> end
<ide> end
<ide>
<add> def recursive_requirements
<add> reqs = recursive_deps.map { |dep| dep.requirements }.to_set
<add> reqs << requirements
<add> reqs.flatten
<add> end
<add>
<ide> protected
<ide>
<ide> # Pretty titles the command and buffers stdout/stderr | 2 |
Go | Go | remove ip_forward warning | ef6c0d53410c0be6f33d049e7998b54804497350 | <ide><path>pkg/sysinfo/sysinfo.go
<ide> func New(quiet bool) *SysInfo {
<ide> }
<ide> }
<ide>
<del> content, err3 := ioutil.ReadFile("/proc/sys/net/ipv4/ip_forward")
<del> sysInfo.IPv4ForwardingDisabled = err3 != nil || len(content) == 0 || content[0] != '1'
<del> if sysInfo.IPv4ForwardingDisabled && !quiet {
<del> log.Printf("WARNING: IPv4 forwarding is disabled.")
<del> }
<del>
<ide> // Check if AppArmor seems to be enabled on this system.
<ide> if _, err := os.Stat("/sys/kernel/security/apparmor"); os.IsNotExist(err) {
<ide> sysInfo.AppArmor = false | 1 |
Javascript | Javascript | check `meta` for being `undefined` only | c74f76ca663db7a47fac8abae0271bd48656cd7a | <ide><path>packages/ember-metal/lib/chains.js
<ide> function addChainWatcher(obj, keyName, node) {
<ide> }
<ide>
<ide> function removeChainWatcher(obj, keyName, node, _meta) {
<del> if (!isObject(obj)) {
<del> return;
<del> }
<add> if (!isObject(obj)) { return; }
<ide>
<del> let meta = _meta || peekMeta(obj);
<add> let meta = _meta === undefined ? peekMeta(obj) : _meta;
<ide>
<del> if (!meta || !meta.readableChainWatchers()) {
<add> if (meta === undefined || meta.readableChainWatchers() === undefined) {
<ide> return;
<ide> }
<ide>
<ide><path>packages/ember-metal/lib/computed.js
<ide> ComputedPropertyPrototype.didChange = function(obj, keyName) {
<ide>
<ide> // don't create objects just to invalidate
<ide> let meta = peekMeta(obj);
<del> if (!meta || meta.source !== obj) {
<add> if (meta === undefined || meta.source !== obj) {
<ide> return;
<ide> }
<ide>
<ide><path>packages/ember-metal/lib/events.js
<ide> export function sendEvent(obj, eventName, params, actions, _meta) {
<ide> */
<ide> export function hasListeners(obj, eventName) {
<ide> let meta = peekMeta(obj);
<del> if (!meta) { return false; }
<add> if (meta === undefined) { return false; }
<ide> let matched = meta.matchingListeners(eventName);
<ide> return matched !== undefined && matched.length > 0;
<ide> }
<ide><path>packages/ember-metal/lib/is_proxy.js
<ide> import { peekMeta } from './meta';
<ide> export function isProxy(value) {
<ide> if (typeof value === 'object' && value !== null) {
<ide> let meta = peekMeta(value);
<del> return meta && meta.isProxy();
<add> return meta === undefined ? false : meta.isProxy();
<ide> }
<ide>
<ide> return false;
<ide><path>packages/ember-metal/lib/mixin.js
<ide> export default class Mixin {
<ide> static mixins(obj) {
<ide> let meta = peekMeta(obj);
<ide> let ret = [];
<del> if (!meta) { return ret; }
<add> if (meta === undefined) { return ret; }
<ide>
<ide> meta.forEachMixins((key, currentMixin) => {
<ide> // skip primitive mixins since these are always anonymous
<ide> MixinPrototype.detect = function(obj) {
<ide> if (typeof obj !== 'object' || obj === null) { return false; }
<ide> if (obj instanceof Mixin) { return _detect(obj, this, {}); }
<ide> let meta = peekMeta(obj);
<del> if (!meta) { return false; }
<add> if (meta === undefined) { return false; }
<ide> return !!meta.peekMixins(guidFor(this));
<ide> };
<ide>
<ide><path>packages/ember-metal/lib/properties.js
<ide> export function MANDATORY_SETTER_FUNCTION(name) {
<ide> export function DEFAULT_GETTER_FUNCTION(name) {
<ide> return function GETTER_FUNCTION() {
<ide> let meta = peekMeta(this);
<del> if (meta !== null && meta !== undefined) {
<add> if (meta !== undefined) {
<ide> return meta.peekValues(name);
<ide> }
<ide> };
<ide> export function INHERITING_GETTER_FUNCTION(name) {
<ide> function IGETTER_FUNCTION() {
<ide> let meta = peekMeta(this);
<ide> let val;
<del> if (meta !== null && meta !== undefined) {
<add> if (meta !== undefined) {
<ide> val = meta.readInheritedValue('values', name);
<ide> }
<ide>
<ide> export function INHERITING_GETTER_FUNCTION(name) {
<ide> become the explicit value of this property.
<ide> */
<ide> export function defineProperty(obj, keyName, desc, data, meta) {
<del> if (meta === null || meta === undefined) {
<del> meta = metaFor(obj);
<del> }
<add> if (meta === undefined) { meta = metaFor(obj); }
<ide>
<ide> let watchEntry = meta.peekWatching(keyName);
<ide> let watching = watchEntry !== undefined && watchEntry > 0;
<ide><path>packages/ember-metal/lib/watch_key.js
<ide> export function unwatchKey(obj, keyName, _meta) {
<ide> let meta = _meta || peekMeta(obj);
<ide>
<ide> // do nothing of this object has already been destroyed
<del> if (!meta || meta.isSourceDestroyed()) { return; }
<add> if (meta === undefined || meta.isSourceDestroyed()) { return; }
<ide>
<ide> let count = meta.peekWatching(keyName);
<ide> if (count === 1) {
<ide><path>packages/ember-runtime/lib/mixins/array.js
<ide> export function arrayContentDidChange(array, startIdx, removeAmt, addAmt) {
<ide> sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]);
<ide>
<ide> let meta = peekMeta(array);
<del> let cache = meta && meta.readableCache();
<add> let cache = meta !== undefined ? meta.readableCache() : undefined;
<ide> if (cache !== undefined) {
<ide> let length = get(array, 'length');
<ide> let addedAmount = (addAmt === -1 ? 0 : addAmt); | 8 |
Javascript | Javascript | fix a todo | 0b77e421529e9e63e57b12690917c72c0149112a | <ide><path>test/unit/src/math/Box2.tests.js
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "clone", ( assert ) => {
<add> QUnit.test( "clone", ( assert ) => {
<ide>
<ide>
<ide> var a = new Box2( zero2, zero2 );
<ide> export default QUnit.module( 'Maths', () => {
<ide> assert.ok( b.min.equals( zero2 ), "Passed!" );
<ide> assert.ok( b.max.equals( zero2 ), "Passed!" );
<ide>
<del> a = new Box2( zero2, zero2 );
<add> a = new Box2();
<ide> var b = a.clone();
<ide> assert.ok( b.min.equals( posInf2 ), "Passed!" );
<ide> assert.ok( b.max.equals( negInf2 ), "Passed!" ); | 1 |
PHP | PHP | change property name in pivot class | 29a181fd64a1d07e071351e61e8403bf00ea4b3c | <ide><path>src/Illuminate/Database/Eloquent/Relations/Pivot.php
<ide> class Pivot extends Model
<ide> *
<ide> * @var \Illuminate\Database\Eloquent\Model
<ide> */
<del> protected $parent;
<add> protected $pivotParent;
<ide>
<ide> /**
<ide> * The name of the foreign key column.
<ide> public function __construct(Model $parent, $attributes, $table, $exists = false)
<ide> // We store off the parent instance so we will access the timestamp column names
<ide> // for the model, since the pivot model timestamps aren't easily configurable
<ide> // from the developer's point of view. We can use the parents to get these.
<del> $this->parent = $parent;
<add> $this->pivotParent = $parent;
<ide>
<ide> $this->exists = $exists;
<ide>
<ide> public function hasTimestampAttributes()
<ide> */
<ide> public function getCreatedAtColumn()
<ide> {
<del> return $this->parent->getCreatedAtColumn();
<add> return $this->pivotParent->getCreatedAtColumn();
<ide> }
<ide>
<ide> /**
<ide> public function getCreatedAtColumn()
<ide> */
<ide> public function getUpdatedAtColumn()
<ide> {
<del> return $this->parent->getUpdatedAtColumn();
<add> return $this->pivotParent->getUpdatedAtColumn();
<ide> }
<ide> } | 1 |
Python | Python | remove ner words from stop words in norwegian | 251119455de70957088970ca0aa56624789ea65c | <ide><path>spacy/lang/nb/stop_words.py
<ide>
<ide> bak bare bedre beste blant ble bli blir blitt bris by både
<ide>
<del>da dag de del dem den denne der dermed det dette disse drept du
<add>da dag de del dem den denne der dermed det dette disse du
<ide>
<ide> eller en enn er et ett etter
<ide>
<del>fem fikk fire fjor flere folk for fortsatt fotball fra fram frankrike fredag
<add>fem fikk fire fjor flere folk for fortsatt fra fram
<ide> funnet få får fått før først første
<ide>
<ide> gang gi gikk gjennom gjorde gjort gjør gjøre god godt grunn gå går
<ide>
<del>ha hadde ham han hans har hele helt henne hennes her hun hva hvor hvordan
<del>hvorfor
<add>ha hadde ham han hans har hele helt henne hennes her hun
<ide>
<ide> i ifølge igjen ikke ingen inn
<ide>
<ide> ja jeg
<ide>
<ide> kamp kampen kan kl klart kom komme kommer kontakt kort kroner kunne kveld
<del>kvinner
<ide>
<del>la laget land landet langt leder ligger like litt løpet lørdag
<add>la laget land landet langt leder ligger like litt løpet
<ide>
<del>man mandag mange mannen mars med meg mellom men mener menn mennesker mens mer
<del>millioner minutter mot msci mye må mål måtte
<add>man mange med meg mellom men mener mennesker mens mer mot mye må mål måtte
<ide>
<del>ned neste noe noen nok norge norsk norske ntb ny nye nå når
<add>ned neste noe noen nok ny nye nå når
<ide>
<del>og også om onsdag opp opplyser oslo oss over
<add>og også om opp opplyser oss over
<ide>
<del>personer plass poeng politidistrikt politiet president prosent på
<add>personer plass poeng på
<ide>
<del>regjeringen runde rundt russland
<add>runde rundt
<ide>
<del>sa saken samme sammen samtidig satt se seg seks selv senere september ser sett
<add>sa saken samme sammen samtidig satt se seg seks selv senere ser sett
<ide> siden sier sin sine siste sitt skal skriver skulle slik som sted stedet stor
<del>store står sverige svært så søndag
<add>store står svært så
<ide>
<del>ta tatt tid tidligere til tilbake tillegg tirsdag to tok torsdag tre tror
<del>tyskland
<add>ta tatt tid tidligere til tilbake tillegg tok tror
<ide>
<del>under usa ut uten utenfor
<add>under ut uten utenfor
<ide>
<ide> vant var ved veldig vi videre viktig vil ville viser vår være vært
<ide> | 1 |
Javascript | Javascript | improve readability of some crypto tests | d67e71e4f7dd856ce2ad6837fe99b023c8bb72b0 | <ide><path>test/parallel/test-crypto-authenticated.js
<ide> common.expectWarning('Warning', (common.hasFipsCrypto ? [] : [
<ide> 'deprecated. Valid GCM tag lengths are 4, 8, 12, 13, 14, 15, 16.')
<ide> ));
<ide>
<del>for (const i in TEST_CASES) {
<del> const test = TEST_CASES[i];
<del>
<add>for (const test of TEST_CASES) {
<ide> if (!ciphers.includes(test.algo)) {
<ide> common.printSkipMessage(`unsupported ${test.algo} test`);
<ide> continue;
<ide><path>test/parallel/test-crypto-binary-default.js
<ide> const rfc4231 = [
<ide> }
<ide> ];
<ide>
<del>for (let i = 0, l = rfc4231.length; i < l; i++) {
<del> for (const hash in rfc4231[i]['hmac']) {
<del> let result = crypto.createHmac(hash, rfc4231[i]['key'])
<del> .update(rfc4231[i]['data'])
<add>for (const testCase of rfc4231) {
<add> for (const hash in testCase.hmac) {
<add> let result = crypto.createHmac(hash, testCase.key)
<add> .update(testCase.data)
<ide> .digest('hex');
<del> if (rfc4231[i]['truncate']) {
<add> if (testCase.truncate) {
<ide> result = result.substr(0, 32); // first 128 bits == 32 hex chars
<ide> }
<ide> assert.strictEqual(
<del> rfc4231[i]['hmac'][hash],
<del> result,
<del> `Test HMAC-${hash}: Test case ${i + 1} rfc 4231`
<add> testCase.hmac[hash],
<add> result
<ide> );
<ide> }
<ide> }
<ide> const rfc2202_sha1 = [
<ide> }
<ide> ];
<ide>
<del>for (let i = 0, l = rfc2202_md5.length; i < l; i++) {
<del> if (!common.hasFipsCrypto) {
<add>if (!common.hasFipsCrypto) {
<add> for (const testCase of rfc2202_md5) {
<ide> assert.strictEqual(
<del> rfc2202_md5[i]['hmac'],
<del> crypto.createHmac('md5', rfc2202_md5[i]['key'])
<del> .update(rfc2202_md5[i]['data'])
<del> .digest('hex'),
<del> `Test HMAC-MD5 : Test case ${i + 1} rfc 2202`
<add> testCase.hmac,
<add> crypto.createHmac('md5', testCase.key)
<add> .update(testCase.data)
<add> .digest('hex')
<ide> );
<ide> }
<ide> }
<del>for (let i = 0, l = rfc2202_sha1.length; i < l; i++) {
<add>for (const testCase of rfc2202_sha1) {
<ide> assert.strictEqual(
<del> rfc2202_sha1[i]['hmac'],
<del> crypto.createHmac('sha1', rfc2202_sha1[i]['key'])
<del> .update(rfc2202_sha1[i]['data'])
<del> .digest('hex'),
<del> `Test HMAC-SHA1 : Test case ${i + 1} rfc 2202`
<add> testCase.hmac,
<add> crypto.createHmac('sha1', testCase.key)
<add> .update(testCase.data)
<add> .digest('hex')
<ide> );
<ide> }
<ide> | 2 |
Javascript | Javascript | shorten path for bogus socket | bfa925f15f20949e02325a58b8cf3ffd1f188077 | <ide><path>test/parallel/test-net-pipe-connect-errors.js
<ide> if (common.isWindows) {
<ide> // file instead
<ide> emptyTxt = path.join(common.fixturesDir, 'empty.txt');
<ide> } else {
<del> // use common.PIPE to ensure we stay within POSIX socket path length
<del> // restrictions, even on CI
<ide> common.refreshTmpDir();
<del> emptyTxt = common.PIPE + '.txt';
<add> // Keep the file name very short so tht we don't exceed the 108 char limit
<add> // on CI for a POSIX socket. Even though this isn't actually a socket file,
<add> // the error will be different from the one we are expecting if we exceed the
<add> // limit.
<add> emptyTxt = common.tmpDir + '0.txt';
<ide>
<ide> function cleanup() {
<ide> try { | 1 |
Ruby | Ruby | add formulae_paths helper | 5366da76fd19bb945599bea47a0cf924c4c9e2dc | <ide><path>Library/Homebrew/cli/args.rb
<ide> def resolved_formulae
<ide> end.uniq(&:name)
<ide> end
<ide>
<add> def formulae_paths
<add> @formulae_paths ||= (downcased_unique_named - casks).map do |name|
<add> Formulary.path(name)
<add> end.uniq(&:name)
<add> end
<add>
<ide> def casks
<ide> @casks ||= downcased_unique_named.grep HOMEBREW_CASK_TAP_CASK_REGEX
<ide> end | 1 |
Javascript | Javascript | use standard path names for chunks | 02955791bc99d44f3392479aa4e4e5db4bfb89f3 | <ide><path>client/webpack-workers.js
<ide> module.exports = (env = {}) => {
<ide> );
<ide> return filename + '.js';
<ide> },
<del> chunkFilename: '[name].[contenthash].js',
<add> chunkFilename: '[name]-[contenthash].js',
<ide> path: staticPath
<ide> },
<ide> stats: { | 1 |
Mixed | Ruby | remove obfuscation support from mail_to helper | cf9d9450ec2a183c0007eedd62113f0ed362019c | <ide><path>actionpack/CHANGELOG.md
<ide>
<ide> *Vasiliy Ermolovich*
<ide>
<add>* Extract support for email address obfuscation via `:encode`, `:replace_at`, and `replace_dot` options
<add> from the `mail_to` helper into the `actionview-encoded_mail_to` gem.
<add>
<add> *Nick Reed + DHH*
<add>
<ide> * Clear url helper methods when routes are reloaded. *Andrew White*
<ide>
<ide> * Fix a bug in `ActionDispatch::Request#raw_post` that caused `env['rack.input']`
<ide><path>actionpack/lib/action_view/helpers/url_helper.rb
<ide> def link_to_if(condition, name, options = {}, html_options = {}, &block)
<ide> # also used as the name of the link unless +name+ is specified. Additional
<ide> # HTML attributes for the link can be passed in +html_options+.
<ide> #
<del> # +mail_to+ has several methods for hindering email harvesters and customizing
<del> # the email itself by passing special keys to +html_options+.
<add> # +mail_to+ has several methods for customizing the email itself by
<add> # passing special keys to +html_options+.
<ide> #
<ide> # ==== Options
<del> # * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex".
<del> # Passing "javascript" will dynamically create and encode the mailto link then
<del> # eval it into the DOM of the page. This method will not show the link on
<del> # the page if the user has JavaScript disabled. Passing "hex" will hex
<del> # encode the +email_address+ before outputting the mailto link.
<del> # * <tt>:replace_at</tt> - When the link +name+ isn't provided, the
<del> # +email_address+ is used for the link label. You can use this option to
<del> # obfuscate the +email_address+ by substituting the @ sign with the string
<del> # given as the value.
<del> # * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the
<del> # +email_address+ is used for the link label. You can use this option to
<del> # obfuscate the +email_address+ by substituting the . in the email with the
<del> # string given as the value.
<ide> # * <tt>:subject</tt> - Preset the subject line of the email.
<ide> # * <tt>:body</tt> - Preset the body of the email.
<ide> # * <tt>:cc</tt> - Carbon Copy additional recipients on the email.
<ide> # * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
<ide> #
<add> # ==== Obfuscation
<add> # Prior to Rails 4.0, +mail_to+ provided options for encoding the address
<add> # in order to hinder email harvesters. To take advantage of these options,
<add> # install the +actionview-encoded_mail_to+ gem.
<add> #
<ide> # ==== Examples
<ide> # mail_to "me@domain.com"
<ide> # # => <a href="mailto:me@domain.com">me@domain.com</a>
<ide> #
<del> # mail_to "me@domain.com", "My email", encode: "javascript"
<del> # # => <script>eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script>
<del> #
<del> # mail_to "me@domain.com", "My email", encode: "hex"
<del> # # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>
<del> #
<del> # mail_to "me@domain.com", nil, replace_at: "_at_", replace_dot: "_dot_", class: "email"
<del> # # => <a href="mailto:me@domain.com" class="email">me_at_domain_dot_com</a>
<add> # mail_to "me@domain.com", "My email"
<add> # # => <a href="mailto:me@domain.com">My email</a>
<ide> #
<ide> # mail_to "me@domain.com", "My email", cc: "ccaddress@domain.com",
<ide> # subject: "This is an example email"
<ide> # # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
<ide> def mail_to(email_address, name = nil, html_options = {})
<ide> email_address = ERB::Util.html_escape(email_address)
<ide>
<del> html_options = html_options.stringify_keys
<del> encode = html_options.delete("encode").to_s
<add> html_options.stringify_keys!
<ide>
<ide> extras = %w{ cc bcc body subject }.map { |item|
<ide> option = html_options.delete(item) || next
<ide> "#{item}=#{Rack::Utils.escape_path(option)}"
<ide> }.compact
<ide> extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&'))
<del>
<del> email_address_obfuscated = email_address.to_str
<del> email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.key?("replace_at")
<del> email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.key?("replace_dot")
<del> case encode
<del> when "javascript"
<del> string = ''
<del> html = content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))
<del> html = escape_javascript(html.to_str)
<del> "document.write('#{html}');".each_byte do |c|
<del> string << sprintf("%%%x", c)
<del> end
<del> "<script>eval(decodeURIComponent('#{string}'))</script>".html_safe
<del> when "hex"
<del> email_address_encoded = email_address_obfuscated.unpack('C*').map {|c|
<del> sprintf("&#%d;", c)
<del> }.join
<del>
<del> string = 'mailto:'.unpack('C*').map { |c|
<del> sprintf("&#%d;", c)
<del> }.join + email_address.unpack('C*').map { |c|
<del> char = c.chr
<del> char =~ /\w/ ? sprintf("%%%x", c) : char
<del> }.join
<del>
<del> content_tag "a", name || email_address_encoded.html_safe, html_options.merge("href" => "#{string}#{extras}".html_safe)
<del> else
<del> content_tag "a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)
<del> end
<add>
<add> content_tag "a", name || email_address.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)
<ide> end
<ide>
<ide> # True if the current request URI was generated by the given +options+.
<ide><path>actionpack/test/template/url_helper_test.rb
<ide> def test_mail_to
<ide> mail_to("david@loudthinking.com", "David Heinemeier Hansson", class: "admin")
<ide> end
<ide>
<del> def test_mail_to_with_javascript
<del> snippet = mail_to("me@domain.com", "My email", encode: "javascript")
<del> assert_dom_equal "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>", snippet
<del> end
<del>
<del> def test_mail_to_with_javascript_unicode
<del> snippet = mail_to("unicode@example.com", "únicode", encode: "javascript")
<del> assert_dom_equal "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%5c%22%3e%c3%ba%6e%69%63%6f%64%65%3c%5c%2f%61%3e%27%29%3b'))</script>", snippet
<del> end
<del>
<ide> def test_mail_with_options
<ide> assert_dom_equal(
<ide> %{<a href="mailto:me@example.com?cc=ccaddress%40example.com&bcc=bccaddress%40example.com&body=This%20is%20the%20body%20of%20the%20message.&subject=This%20is%20an%20example%20email">My email</a>},
<ide> def test_mail_to_with_img
<ide> mail_to('feedback@example.com', '<img src="/feedback.png" />'.html_safe)
<ide> end
<ide>
<del> def test_mail_to_with_hex
<del> assert_dom_equal(
<del> %{<a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>},
<del> mail_to("me@domain.com", "My email", encode: "hex")
<del> )
<del>
<del> assert_dom_equal(
<del> %{<a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">me@domain.com</a>},
<del> mail_to("me@domain.com", nil, encode: "hex")
<del> )
<del> end
<del>
<del> def test_mail_to_with_replace_options
<del> assert_dom_equal(
<del> %{<a href="mailto:wolfgang@stufenlos.net">wolfgang(at)stufenlos(dot)net</a>},
<del> mail_to("wolfgang@stufenlos.net", nil, replace_at: "(at)", replace_dot: "(dot)")
<del> )
<del>
<del> assert_dom_equal(
<del> %{<a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">me(at)domain.com</a>},
<del> mail_to("me@domain.com", nil, encode: "hex", replace_at: "(at)")
<del> )
<del>
<del> assert_dom_equal(
<del> %{<a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>},
<del> mail_to("me@domain.com", "My email", encode: "hex", replace_at: "(at)")
<del> )
<del>
<del> assert_dom_equal(
<del> %{<a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">me(at)domain(dot)com</a>},
<del> mail_to("me@domain.com", nil, encode: "hex", replace_at: "(at)", replace_dot: "(dot)")
<del> )
<del>
<del> assert_dom_equal(
<del> %{<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>},
<del> mail_to("me@domain.com", "My email", encode: "javascript", replace_at: "(at)", replace_dot: "(dot)")
<del> )
<del>
<del> assert_dom_equal(
<del> %{<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%5c%2f%61%3e%27%29%3b'))</script>},
<del> mail_to("me@domain.com", nil, encode: "javascript", replace_at: "(at)", replace_dot: "(dot)")
<del> )
<del> end
<del>
<ide> def test_mail_to_returns_html_safe_string
<ide> assert mail_to("david@loudthinking.com").html_safe?
<del> assert mail_to("me@domain.com", "My email", encode: "javascript").html_safe?
<del> assert mail_to("me@domain.com", "My email", encode: "hex").html_safe?
<ide> end
<ide>
<ide> def protect_against_forgery? | 3 |
Go | Go | share logic to create-or-replace a container | 6a2f385aea283aee4cce84c01308f5e7906a1564 | <ide><path>daemon/start.go
<ide> import (
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/errdefs"
<add> "github.com/docker/docker/libcontainerd"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide> func (daemon *Daemon) containerStart(container *container.Container, checkpoint
<ide>
<ide> ctx := context.TODO()
<ide>
<del> ctr, err := daemon.containerd.NewContainer(ctx, container.ID, spec, shim, createOptions)
<add> ctr, err := libcontainerd.ReplaceContainer(ctx, daemon.containerd, container.ID, spec, shim, createOptions)
<ide> if err != nil {
<del> if errdefs.IsConflict(err) {
<del> logrus.WithError(err).WithField("container", container.ID).Error("Container not cleaned up from containerd from previous run")
<del> daemon.cleanupStaleContainer(ctx, container.ID)
<del> ctr, err = daemon.containerd.NewContainer(ctx, container.ID, spec, shim, createOptions)
<del> }
<del> if err != nil {
<del> return translateContainerdStartErr(container.Path, container.SetExitCode, err)
<del> }
<add> return translateContainerdStartErr(container.Path, container.SetExitCode, err)
<ide> }
<ide>
<ide> // TODO(mlaventure): we need to specify checkpoint options here
<ide> func (daemon *Daemon) containerStart(container *container.Container, checkpoint
<ide> return nil
<ide> }
<ide>
<del>func (daemon *Daemon) cleanupStaleContainer(ctx context.Context, id string) {
<del> // best effort to clean up old container object
<del> log := logrus.WithContext(ctx).WithField("container", id)
<del> ctr, err := daemon.containerd.LoadContainer(ctx, id)
<del> if err != nil {
<del> // Log an error no matter the kind. A container existed with the
<del> // ID, so a NotFound error would be an exceptional situation
<del> // worth logging.
<del> log.WithError(err).Error("Error loading stale containerd container object")
<del> return
<del> }
<del> if tsk, err := ctr.Task(ctx); err != nil {
<del> if !errdefs.IsNotFound(err) {
<del> log.WithError(err).Error("Error loading stale containerd task object")
<del> }
<del> } else {
<del> if err := tsk.ForceDelete(ctx); err != nil {
<del> log.WithError(err).Error("Error cleaning up stale containerd task object")
<del> }
<del> }
<del> if err := ctr.Delete(ctx); err != nil && !errdefs.IsNotFound(err) {
<del> log.WithError(err).Error("Error cleaning up stale containerd container object")
<del> }
<del>}
<del>
<ide> // Cleanup releases any network resources allocated to the container along with any rules
<ide> // around how containers are linked together. It also unmounts the container's root filesystem.
<ide> func (daemon *Daemon) Cleanup(container *container.Container) {
<ide><path>libcontainerd/replace.go
<add>package libcontainerd // import "github.com/docker/docker/libcontainerd"
<add>
<add>import (
<add> "context"
<add>
<add> "github.com/containerd/containerd"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<add> "github.com/pkg/errors"
<add> "github.com/sirupsen/logrus"
<add>
<add> "github.com/docker/docker/errdefs"
<add> "github.com/docker/docker/libcontainerd/types"
<add>)
<add>
<add>// ReplaceContainer creates a new container, replacing any existing container
<add>// with the same id if necessary.
<add>func ReplaceContainer(ctx context.Context, client types.Client, id string, spec *specs.Spec, shim string, runtimeOptions interface{}, opts ...containerd.NewContainerOpts) (types.Container, error) {
<add> newContainer := func() (types.Container, error) {
<add> return client.NewContainer(ctx, id, spec, shim, runtimeOptions, opts...)
<add> }
<add> ctr, err := newContainer()
<add> if err == nil || !errdefs.IsConflict(err) {
<add> return ctr, err
<add> }
<add>
<add> log := logrus.WithContext(ctx).WithField("container", id)
<add> log.Debug("A container already exists with the same ID. Attempting to clean up the old container.")
<add> ctr, err = client.LoadContainer(ctx, id)
<add> if err != nil {
<add> if errdefs.IsNotFound(err) {
<add> // Task failed successfully: the container no longer exists,
<add> // despite us not doing anything. May as well try to create
<add> // the container again. It might succeed.
<add> return newContainer()
<add> }
<add> return nil, errors.Wrap(err, "could not load stale containerd container object")
<add> }
<add> tsk, err := ctr.Task(ctx)
<add> if err != nil {
<add> if errdefs.IsNotFound(err) {
<add> goto deleteContainer
<add> }
<add> // There is no point in trying to delete the container if we
<add> // cannot determine whether or not it has a task. The containerd
<add> // client would just try to load the task itself, get the same
<add> // error, and give up.
<add> return nil, errors.Wrap(err, "could not load stale containerd task object")
<add> }
<add> if err := tsk.ForceDelete(ctx); err != nil {
<add> if !errdefs.IsNotFound(err) {
<add> return nil, errors.Wrap(err, "could not delete stale containerd task object")
<add> }
<add> // The task might have exited on its own. Proceed with
<add> // attempting to delete the container.
<add> }
<add>deleteContainer:
<add> if err := ctr.Delete(ctx); err != nil && !errdefs.IsNotFound(err) {
<add> return nil, errors.Wrap(err, "could not delete stale containerd container object")
<add> }
<add>
<add> return newContainer()
<add>}
<ide><path>plugin/executor/containerd/containerd.go
<ide> func (p c8dPlugin) deleteTaskAndContainer(ctx context.Context) {
<ide> func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error {
<ide> ctx := context.Background()
<ide> log := logrus.WithField("plugin", id)
<del> ctr, err := e.client.NewContainer(ctx, id, &spec, e.runtime.Shim.Binary, e.runtime.Shim.Opts)
<add> ctr, err := libcontainerd.ReplaceContainer(ctx, e.client, id, &spec, e.runtime.Shim.Binary, e.runtime.Shim.Opts)
<ide> if err != nil {
<del> ctr2, err2 := e.client.LoadContainer(ctx, id)
<del> if err2 != nil {
<del> if !errdefs.IsNotFound(err2) {
<del> log.WithError(err2).Warn("Received an error while attempting to load containerd container for plugin")
<del> }
<del> } else {
<del> status := containerd.Unknown
<del> t, err2 := ctr2.Task(ctx)
<del> if err2 != nil {
<del> if !errdefs.IsNotFound(err2) {
<del> log.WithError(err2).Warn("Received an error while attempting to load containerd task for plugin")
<del> }
<del> } else {
<del> s, err2 := t.Status(ctx)
<del> if err2 != nil {
<del> log.WithError(err2).Warn("Received an error while attempting to read plugin status")
<del> } else {
<del> status = s.Status
<del> }
<del> }
<del> if status != containerd.Running && status != containerd.Unknown {
<del> if err2 := ctr2.Delete(ctx); err2 != nil && !errdefs.IsNotFound(err2) {
<del> log.WithError(err2).Error("Error cleaning up containerd container")
<del> }
<del> ctr, err = e.client.NewContainer(ctx, id, &spec, e.runtime.Shim.Binary, e.runtime.Shim.Opts)
<del> }
<del> }
<del>
<del> if err != nil {
<del> return errors.Wrap(err, "error creating containerd container")
<del> }
<add> return errors.Wrap(err, "error creating containerd container for plugin")
<ide> }
<ide>
<ide> p := c8dPlugin{log: log, ctr: ctr} | 3 |
Python | Python | add keyword for allow_zero | 1587fb9c43558b86fc34bbe441831be195488f72 | <ide><path>keras/layers/convolutional_recurrent.py
<ide> def input_conv(self, x, w, b=None, padding='valid'):
<ide> return conv_out
<ide>
<ide> def recurrent_conv(self, x, w):
<del> strides = conv_utils.normalize_tuple(1, self.rank, 'strides', True)
<add> strides = conv_utils.normalize_tuple(1, self.rank, 'strides', allow_zero=True)
<ide> conv_out = self._conv_func(
<ide> x, w, strides=strides, padding='same', data_format=self.data_format)
<ide> return conv_out
<ide><path>keras/layers/local.py
<ide> def __init__(self,
<ide> super(LocallyConnected1D, self).__init__(**kwargs)
<ide> self.filters = filters
<ide> self.kernel_size = conv_utils.normalize_tuple(kernel_size, 1, 'kernel_size')
<del> self.strides = conv_utils.normalize_tuple(strides, 1, 'strides', True)
<add> self.strides = conv_utils.normalize_tuple(strides, 1, 'strides', allow_zero=True)
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> if self.padding != 'valid' and implementation == 1:
<ide> raise ValueError('Invalid border mode for LocallyConnected1D ' | 2 |
Python | Python | add thai language tokenizers | d53c3fcbc16b090bdc4665b159ae38851cd8f357 | <ide><path>setup.py
<ide> def setup_package():
<ide> # Language tokenizers with external dependencies
<ide> "ja": ["mecab-python3==0.7"],
<ide> "ko": ["natto-py==0.9.0"],
<add> "th": ["pythainlp>=2.0"],
<ide> },
<ide> python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",
<ide> classifiers=[ | 1 |
Python | Python | fix polymorphic identity of hive_to_mysql | c747ae473edbea149a0379df8b14f9d3c8341d3d | <ide><path>airflow/operators/hive_to_mysql.py
<ide> class HiveToMySqlTransfer(BaseOperator):
<ide> """
<ide>
<ide> __mapper_args__ = {
<del> 'polymorphic_identity': 'MySqlToHiveOperator'
<add> 'polymorphic_identity': 'HiveToMySqlTransfer'
<ide> }
<ide> template_fields = ('sql', 'mysql_table')
<ide> template_ext = ('.sql',) | 1 |
Python | Python | name this test method correctly. refs [16334] | 7a600166a7bac4b657bc9d8dac948ddde043a629 | <ide><path>tests/modeltests/many_to_one_null/tests.py
<ide> def test_assign_clear_related_set(self):
<ide> self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True),
<ide> ['<Article: First>', '<Article: Fourth>'])
<ide>
<del> def test_remove_efficiency(self):
<add> def test_clear_efficiency(self):
<ide> r = Reporter.objects.create()
<ide> for _ in xrange(3):
<ide> r.article_set.create() | 1 |
PHP | PHP | move import to top of file | d1d3bcff041428242b519407d513ee39ccdbb01f | <ide><path>lib/Cake/Console/Shell.php
<ide> App::uses('ConsoleInput', 'Console');
<ide> App::uses('ConsoleInputSubcommand', 'Console');
<ide> App::uses('ConsoleOptionParser', 'Console');
<add>App::uses('ClassRegistry', 'Utility');
<ide> App::uses('File', 'Utility');
<ide>
<ide> /**
<ide> protected function _loadModels() {
<ide> if (empty($this->uses)) {
<ide> return false;
<ide> }
<del> App::uses('ClassRegistry', 'Utility');
<ide>
<ide> $uses = is_array($this->uses) ? $this->uses : array($this->uses);
<ide> | 1 |
PHP | PHP | fix timezone conversion in manytophp() | 2692c1172d4f15cae98c73f5f1a37d2ebbc8ea61 | <ide><path>src/Database/Type/DateTimeType.php
<ide> public function manyToPHP(array $values, array $fields, Driver $driver)
<ide> $instance = clone $this->_datetimeInstance;
<ide> $instance = $instance->modify($values[$field]);
<ide> if ($instance->getTimezone()->getName() !== date_default_timezone_get()) {
<del> $instance->setTimezone(new DateTimeZone(date_default_timezone_get()));
<add> $instance = $instance->setTimezone(new DateTimeZone(date_default_timezone_get()));
<ide> }
<ide>
<ide> if ($this->setToDateStart) {
<ide><path>tests/TestCase/Database/Type/DateTimeTypeTest.php
<ide> public function testManyToPHP()
<ide> $expected,
<ide> $this->type->manyToPHP($values, array_keys($values), $this->driver)
<ide> );
<add>
<add> $this->type->setTimezone('Asia/Kolkata'); // UTC+5:30
<add> $values = [
<add> 'a' => null,
<add> 'b' => '2001-01-04 12:13:14',
<add> ];
<add> $expected = [
<add> 'a' => null,
<add> 'b' => new Time('2001-01-04 06:43:14'),
<add> ];
<add> $this->assertEquals(
<add> $expected,
<add> $this->type->manyToPHP($values, array_keys($values), $this->driver)
<add> );
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | add pseduo locale (x-pseudo) | 82ddf620466399fb551a0329cde3eafd498edd98 | <ide><path>src/locale/x-pseudo.js
<add>//! moment.js locale configuration
<add>//! locale : pseudo (x-pseudo)
<add>//! author : Andrew Hood : https://github.com/andrewhood125
<add>
<add>import moment from '../moment';
<add>
<add>export default moment.defineLocale('x-pseudo', {
<add> months : 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split('_'),
<add> monthsShort : 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'),
<add> weekdays : 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'),
<add> weekdaysShort : 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'),
<add> weekdaysMin : 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'),
<add> longDateFormat : {
<add> LT : 'HH:mm',
<add> L : 'DD/MM/YYYY',
<add> LL : 'D MMMM YYYY',
<add> LLL : 'D MMMM YYYY LT',
<add> LLLL : 'dddd, D MMMM YYYY LT'
<add> },
<add> calendar : {
<add> sameDay : '[T~ódá~ý át] LT',
<add> nextDay : '[T~ómó~rró~w át] LT',
<add> nextWeek : 'dddd [át] LT',
<add> lastDay : '[Ý~ést~érdá~ý át] LT',
<add> lastWeek : '[L~ást] dddd [át] LT',
<add> sameElse : 'L'
<add> },
<add> relativeTime : {
<add> future : 'í~ñ %s',
<add> past : '%s á~gó',
<add> s : 'á ~féw ~sécó~ñds',
<add> m : 'á ~míñ~úté',
<add> mm : '%d m~íñú~tés',
<add> h : 'á~ñ hó~úr',
<add> hh : '%d h~óúrs',
<add> d : 'á ~dáý',
<add> dd : '%d d~áýs',
<add> M : 'á ~móñ~th',
<add> MM : '%d m~óñt~hs',
<add> y : 'á ~ýéár',
<add> yy : '%d ý~éárs'
<add> },
<add> ordinal : function (number) {
<add> var b = number % 10,
<add> output = (~~(number % 100 / 10) === 1) ? 'th' :
<add> (b === 1) ? 'st' :
<add> (b === 2) ? 'nd' :
<add> (b === 3) ? 'rd' : 'th';
<add> return number + output;
<add> },
<add> week : {
<add> dow : 1, // Monday is the first day of the week.
<add> doy : 4 // The week that contains Jan 4th is the first week of the year.
<add> }
<add>});
<ide><path>src/test/locale/x-pseudo.js
<add>import {localeModule, test} from '../qunit';
<add>import moment from '../../moment';
<add>localeModule('x-pseudo');
<add>
<add>test('parse', function (assert) {
<add> var tests = 'J~áñúá~rý J~áñ_F~ébrú~árý ~Féb_~Márc~h ~Már_Áp~ríl ~Ápr_~Máý ~Máý_~Júñé~ ~Júñ_Júl~ý ~Júl_Áú~gúst~ ~Áúg_Sép~témb~ér ~Sép_Ó~ctób~ér ~Óct_Ñ~óvém~bér ~Ñóv_~Décé~mbér ~Déc'.split('_'), i;
<add> function equalTest(input, mmm, i) {
<add> assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
<add> }
<add> for (i = 0; i < 12; i++) {
<add> tests[i] = tests[i].split(' ');
<add> equalTest(tests[i][0], 'MMM', i);
<add> equalTest(tests[i][1], 'MMM', i);
<add> equalTest(tests[i][0], 'MMMM', i);
<add> equalTest(tests[i][1], 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
<add> }
<add>});
<add>
<add>test('format', function (assert) {
<add> var a = [
<add> ['dddd, MMMM Do YYYY, h:mm:ss a', 'S~úñdá~ý, F~ébrú~árý 14th 2010, 3:25:50 pm'],
<add> ['ddd, hA', 'S~úñ, 3PM'],
<add> ['M Mo MM MMMM MMM', '2 2nd 02 F~ébrú~árý ~Féb'],
<add> ['YYYY YY', '2010 10'],
<add> ['D Do DD', '14 14th 14'],
<add> ['d do dddd ddd dd', '0 0th S~úñdá~ý S~úñ S~ú'],
<add> ['DDD DDDo DDDD', '45 45th 045'],
<add> ['w wo ww', '6 6th 06'],
<add> ['h hh', '3 03'],
<add> ['H HH', '15 15'],
<add> ['m mm', '25 25'],
<add> ['s ss', '50 50'],
<add> ['a A', 'pm PM'],
<add> ['[the] DDDo [day of the year]', 'the 45th day of the year'],
<add> ['LTS', '15:25:50'],
<add> ['L', '14/02/2010'],
<add> ['LL', '14 F~ébrú~árý 2010'],
<add> ['LLL', '14 F~ébrú~árý 2010 15:25'],
<add> ['LLLL', 'S~úñdá~ý, 14 F~ébrú~árý 2010 15:25'],
<add> ['l', '14/2/2010'],
<add> ['ll', '14 ~Féb 2010'],
<add> ['lll', '14 ~Féb 2010 15:25'],
<add> ['llll', 'S~úñ, 14 ~Féb 2010 15:25']
<add> ],
<add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
<add> i;
<add> for (i = 0; i < a.length; i++) {
<add> assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
<add> }
<add>});
<add>
<add>test('format ordinal', function (assert) {
<add> assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st');
<add> assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd');
<add> assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd');
<add> assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th');
<add> assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th');
<add> assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th');
<add> assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th');
<add> assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th');
<add> assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th');
<add> assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th');
<add>
<add> assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th');
<add> assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th');
<add> assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th');
<add> assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th');
<add> assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th');
<add> assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th');
<add> assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th');
<add> assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th');
<add> assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th');
<add> assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th');
<add>
<add> assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st');
<add> assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd');
<add> assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd');
<add> assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th');
<add> assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th');
<add> assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th');
<add> assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th');
<add> assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th');
<add> assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th');
<add> assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th');
<add>
<add> assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st');
<add>});
<add>
<add>test('format month', function (assert) {
<add> var expected = 'J~áñúá~rý J~áñ_F~ébrú~árý ~Féb_~Márc~h ~Már_Áp~ríl ~Ápr_~Máý ~Máý_~Júñé~ ~Júñ_Júl~ý ~Júl_Áú~gúst~ ~Áúg_Sép~témb~ér ~Sép_Ó~ctób~ér ~Óct_Ñ~óvém~bér ~Ñóv_~Décé~mbér ~Déc'.split('_'), i;
<add> for (i = 0; i < expected.length; i++) {
<add> assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
<add> }
<add>});
<add>
<add>test('format week', function (assert) {
<add> var expected = 'S~úñdá~ý S~úñ S~ú_Mó~ñdáý~ ~Móñ Mó~_Túé~sdáý~ ~Túé Tú_Wéd~ñésd~áý ~Wéd ~Wé_T~húrs~dáý ~Thú T~h_~Fríd~áý ~Frí Fr~_S~átúr~dáý ~Sát Sá'.split('_'), i;
<add> for (i = 0; i < expected.length; i++) {
<add> assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
<add> }
<add>});
<add>
<add>test('from', function (assert) {
<add> var start = moment([2007, 1, 28]);
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'á ~féw ~sécó~ñds', '44 seconds = a few seconds');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'á ~míñ~úté', '45 seconds = a minute');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'á ~míñ~úté', '89 seconds = a minute');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 m~íñú~tés', '90 seconds = 2 minutes');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 m~íñú~tés', '44 minutes = 44 minutes');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'á~ñ hó~úr', '45 minutes = an hour');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'á~ñ hó~úr', '89 minutes = an hour');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 h~óúrs', '90 minutes = 2 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 h~óúrs', '5 hours = 5 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 h~óúrs', '21 hours = 21 hours');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'á ~dáý', '22 hours = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'á ~dáý', '35 hours = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 d~áýs', '36 hours = 2 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'á ~dáý', '1 day = a day');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 d~áýs', '5 days = 5 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 d~áýs', '25 days = 25 days');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'á ~móñ~th', '26 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'á ~móñ~th', '30 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'á ~móñ~th', '43 days = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 m~óñt~hs', '46 days = 2 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 m~óñt~hs', '75 days = 2 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 m~óñt~hs', '76 days = 3 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'á ~móñ~th', '1 month = a month');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 m~óñt~hs', '5 months = 5 months');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'á ~ýéár', '345 days = a year');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ý~éárs', '548 days = 2 years');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'á ~ýéár', '1 year = a year');
<add> assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ý~éárs', '5 years = 5 years');
<add>});
<add>
<add>test('suffix', function (assert) {
<add> assert.equal(moment(30000).from(0), 'í~ñ á ~féw ~sécó~ñds', 'prefix');
<add> assert.equal(moment(0).from(30000), 'á ~féw ~sécó~ñds á~gó', 'suffix');
<add>});
<add>
<add>test('now from now', function (assert) {
<add> assert.equal(moment().fromNow(), 'á ~féw ~sécó~ñds á~gó', 'now from now should display as in the past');
<add>});
<add>
<add>test('fromNow', function (assert) {
<add> assert.equal(moment().add({s: 30}).fromNow(), 'í~ñ á ~féw ~sécó~ñds', 'in a few seconds');
<add> assert.equal(moment().add({d: 5}).fromNow(), 'í~ñ 5 d~áýs', 'in 5 days');
<add>});
<add>
<add>test('calendar day', function (assert) {
<add> var a = moment().hours(2).minutes(0).seconds(0);
<add>
<add> assert.equal(moment(a).calendar(), 'T~ódá~ý át 02:00', 'today at the same time');
<add> assert.equal(moment(a).add({m: 25}).calendar(), 'T~ódá~ý át 02:25', 'Now plus 25 min');
<add> assert.equal(moment(a).add({h: 1}).calendar(), 'T~ódá~ý át 03:00', 'Now plus 1 hour');
<add> assert.equal(moment(a).add({d: 1}).calendar(), 'T~ómó~rró~w át 02:00', 'tomorrow at the same time');
<add> assert.equal(moment(a).subtract({h: 1}).calendar(), 'T~ódá~ý át 01:00', 'Now minus 1 hour');
<add> assert.equal(moment(a).subtract({d: 1}).calendar(), 'Ý~ést~érdá~ý át 02:00', 'yesterday at the same time');
<add>});
<add>
<add>test('calendar next week', function (assert) {
<add> var i, m;
<add> for (i = 2; i < 7; i++) {
<add> m = moment().add({d: i});
<add> assert.equal(m.calendar(), m.format('dddd [át] LT'), 'Today + ' + i + ' days current time');
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> assert.equal(m.calendar(), m.format('dddd [át] LT'), 'Today + ' + i + ' days beginning of day');
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> assert.equal(m.calendar(), m.format('dddd [át] LT'), 'Today + ' + i + ' days end of day');
<add> }
<add>});
<add>
<add>test('calendar last week', function (assert) {
<add> var i, m;
<add>
<add> for (i = 2; i < 7; i++) {
<add> m = moment().subtract({d: i});
<add> assert.equal(m.calendar(), m.format('[L~ást] dddd [át] LT'), 'Today - ' + i + ' days current time');
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> assert.equal(m.calendar(), m.format('[L~ást] dddd [át] LT'), 'Today - ' + i + ' days beginning of day');
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> assert.equal(m.calendar(), m.format('[L~ást] dddd [át] LT'), 'Today - ' + i + ' days end of day');
<add> }
<add>});
<add>
<add>test('calendar all else', function (assert) {
<add> var weeksAgo = moment().subtract({w: 1}),
<add> weeksFromNow = moment().add({w: 1});
<add>
<add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
<add> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
<add>
<add> weeksAgo = moment().subtract({w: 2});
<add> weeksFromNow = moment().add({w: 2});
<add>
<add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
<add> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
<add>});
<add>
<add>test('weeks year starting sunday formatted', function (assert) {
<add> assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52nd', 'Jan 1 2012 should be week 52');
<add> assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1st', 'Jan 2 2012 should be week 1');
<add> assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1st', 'Jan 8 2012 should be week 1');
<add> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2nd', 'Jan 9 2012 should be week 2');
<add> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2');
<add>}); | 2 |
Text | Text | add v3.1.0 to changelog | b33720734607970789f936e7a4cd1426c440214a | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### v3.1.0-beta.5 (March 12, 2018)
<del>- [#15601](https://github.com/emberjs/ember.js/pull/15601) [BUGFIX] Ensure Mixin.prototype.toString does not return constructor code
<add>### v3.1.0 (April 10, 2018)
<add>- [#16293](https://github.com/emberjs/ember.js/pull/16293) [BUGFIX] Ignore --pod for -addon blueprints: helper, initializer, and instance-initializer
<add>- [#16312](https://github.com/emberjs/ember.js/pull/16312) [DEPRECATION] Deprecate `Route.prototype.router` in favor of `Route.prototype._router`
<ide> - [#16326](https://github.com/emberjs/ember.js/pull/16326) [BUGFIX] Expanded syntax error for if handlebars helper to include source of error
<del>- [#16347](https://github.com/emberjs/ember.js/pull/16347) [BUGFIX] Adds toJSON to list of descriptorTrap assertion exception
<del>- [#16350](https://github.com/emberjs/ember.js/pull/16350) [BUGFIX] Fix initialiters tests blueprints
<del>- [#16351](https://github.com/emberjs/ember.js/pull/16351) [BUGFIX] Bring RSVP.cast back from the dead
<del>- [#16365](https://github.com/emberjs/ember.js/pull/16365) [BUGFIX] Fold all trap methods together
<del>
<del>### v3.1.0-beta.4 (March 5, 2018)
<add>- [#16350](https://github.com/emberjs/ember.js/pull/16350) [BUGFIX] Fix initializers tests blueprints
<ide> - [#16294](https://github.com/emberjs/ember.js/pull/16294) [BUGFIX] Fix input macro params handling
<del>- [#16297](https://github.com/emberjs/ember.js/pull/16297) [BUGFIX] Revert "Update to backburner.js@2.2.0."
<del>- [#16299](https://github.com/emberjs/ember.js/pull/16299) [BUGFIX] Revert "[CLEANUP] Remove ':change' suffix on change events"
<ide> - [#16307](https://github.com/emberjs/ember.js/pull/16307) [BUGFIX] Ensure proper .toString() of default components.
<del>
<del>### v3.1.0-beta.3 (February 26, 2018)
<del>- [#16271](https://github.com/emberjs/ember.js/pull/16271) [BUGFIX] Fix ChainNode unchaining
<del>- [#16274](https://github.com/emberjs/ember.js/pull/16274) [BUGFIX] Ensure accessing a "proxy" itself does not error.
<del>- [#16282](https://github.com/emberjs/ember.js/pull/16282) [BUGFIX] Fix nested ObserverSet flushes
<del>- [#16285](https://github.com/emberjs/ember.js/pull/16285) [BUGFIX] Fix version with many special chars.
<del>- [#16286](https://github.com/emberjs/ember.js/pull/16286) [BUGFIX] Update to glimmer-vm@0.32.1.
<ide> - [#16287](https://github.com/emberjs/ember.js/pull/16287) [BUGFIX] Update to router_js@2.0.0-beta.2.
<del>- [#16288](https://github.com/emberjs/ember.js/pull/16288) [BUGFIX] Ensure all "internal symbols" avoid the proxy assertion
<del>
<del>### v3.1.0-beta.2 (February 19, 2018)
<del>
<del>- [#13355](https://github.com/emberjs/ember.js/pull/13355) [BUGFIX] Fix issue with `Ember.trySet` on destroyed objects.
<ide> - [#16245](https://github.com/emberjs/ember.js/pull/16245) [BUGFIX] Ensure errors in deferred component hooks can be recovered.
<ide> - [#16246](https://github.com/emberjs/ember.js/pull/16246) [BUGFIX] computed.sort should not sort if sortProperties is empty
<del>
<del>### v3.1.0-beta.1 (February 14, 2018)
<del>
<ide> - [emberjs/rfcs#276](https://github.com/emberjs/rfcs/blob/master/text/0276-named-args.md) [FEATURE named-args] enabled by default.
<ide> - [emberjs/rfcs#278](https://github.com/emberjs/rfcs/blob/master/text/0278-template-only-components.md) [FEATURE template-only-glimmer-components] Enable-able via `@ember/optional-features` addon.
<ide> - [emberjs/rfcs#280](https://github.com/emberjs/rfcs/blob/master/text/0280-remove-application-wrapper.md) [FEATURE application-template-wrapper] Enable-able via `@ember/optional-features` addon.
<ide> - [emberjs/rfcs#281](https://github.com/emberjs/rfcs/blob/master/text/0281-es5-getters.md) [FEATURE native-es5-getters] Enabled by default.
<ide> - [#15828](https://github.com/emberjs/ember.js/pull/15828) Upgrade glimmer-vm to latest version.
<del>- [#16212](https://github.com/emberjs/ember.js/pull/16212) Update to backburner.js@2.2.0.
<ide>
<ide> ### v3.0.0 (February 13, 2018)
<ide> | 1 |
Python | Python | use same version specifications as in werkzeug | 2713ea98cb0fc22952ba6ddf88209da1a2efa270 | <ide><path>setup.py
<ide> def run(self):
<ide> 'License :: OSI Approved :: BSD License',
<ide> 'Operating System :: OS Independent',
<ide> 'Programming Language :: Python',
<del> 'Programming Language :: Python :: 2.6',
<del> 'Programming Language :: Python :: 2.7',
<add> 'Programming Language :: Python :: 3',
<ide> 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
<ide> 'Topic :: Software Development :: Libraries :: Python Modules'
<ide> ], | 1 |
PHP | PHP | use adventage of newer phpunit sytax | c936250731cc5b4f8160a50150971e586442fd4d | <ide><path>tests/TestCase/Auth/BasicAuthenticateTest.php
<ide> public function testAuthenticateSuccess()
<ide> /**
<ide> * test scope failure.
<ide> *
<del> * @expectedException \Cake\Network\Exception\UnauthorizedException
<del> * @expectedExceptionCode 401
<ide> * @return void
<ide> */
<ide> public function testAuthenticateFailReChallenge()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\UnauthorizedException::class);
<add> $this->expectExceptionCode(401);
<ide> $this->auth->config('scope.username', 'nate');
<ide> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide><path>tests/TestCase/Auth/ControllerAuthorizeTest.php
<ide> public function setUp()
<ide> }
<ide>
<ide> /**
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testControllerErrorOnMissingMethod()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $this->auth->controller(new Controller());
<ide> }
<ide>
<ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php
<ide> public function testAuthenticateNoData()
<ide> /**
<ide> * test the authenticate method
<ide> *
<del> * @expectedException \Cake\Network\Exception\UnauthorizedException
<del> * @expectedExceptionCode 401
<ide> * @return void
<ide> */
<ide> public function testAuthenticateWrongUsername()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\UnauthorizedException::class);
<add> $this->expectExceptionCode(401);
<ide> $request = new ServerRequest('posts/index');
<ide> $request->addParams(['pass' => []]);
<ide>
<ide> public function testAuthenticateSuccessSimulatedRequestMethod()
<ide> /**
<ide> * test scope failure.
<ide> *
<del> * @expectedException \Cake\Network\Exception\UnauthorizedException
<del> * @expectedExceptionCode 401
<ide> * @return void
<ide> */
<ide> public function testAuthenticateFailReChallenge()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\UnauthorizedException::class);
<add> $this->expectExceptionCode(401);
<ide> $this->auth->config('scope.username', 'nate');
<ide> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide><path>tests/TestCase/Auth/PasswordHasherFactoryTest.php
<ide> public function testBuild()
<ide> /**
<ide> * test build() throws exception for non existent hasher
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Password hasher class "FooBar" was not found.
<ide> * @return void
<ide> */
<ide> public function testBuildException()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Password hasher class "FooBar" was not found.');
<ide> $hasher = PasswordHasherFactory::build('FooBar');
<ide> }
<ide> }
<ide><path>tests/TestCase/Cache/CacheTest.php
<ide> public function testConfigWithLibAndPluginEngines()
<ide> /**
<ide> * Test write from a config that is undefined.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testWriteNonExistingConfig()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->assertFalse(Cache::write('key', 'value', 'totally fake'));
<ide> }
<ide>
<ide> /**
<ide> * Test write from a config that is undefined.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testIncrementNonExistingConfig()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->assertFalse(Cache::increment('key', 1, 'totally fake'));
<ide> }
<ide>
<ide> /**
<ide> * Test write from a config that is undefined.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testDecrementNonExistingConfig()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->assertFalse(Cache::decrement('key', 1, 'totally fake'));
<ide> }
<ide>
<ide> public function testConfigVariants($config)
<ide> /**
<ide> * testConfigInvalidEngine method
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> * @return void
<ide> */
<ide> public function testConfigInvalidEngine()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> $config = ['engine' => 'Imaginary'];
<ide> Cache::setConfig('test', $config);
<ide> Cache::engine('test');
<ide> public function testConfigInvalidEngine()
<ide> /**
<ide> * test that trying to configure classes that don't extend CacheEngine fail.
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> * @return void
<ide> */
<ide> public function testConfigInvalidObject()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> $this->getMockBuilder(\StdClass::class)
<ide> ->setMockClassName('RubbishEngine')
<ide> ->getMock();
<ide> public function testConfigInvalidObject()
<ide> /**
<ide> * Ensure you cannot reconfigure a cache adapter.
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> * @return void
<ide> */
<ide> public function testConfigErrorOnReconfigure()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> Cache::setConfig('tests', ['engine' => 'File', 'path' => TMP]);
<ide> Cache::setConfig('tests', ['engine' => 'Apc']);
<ide> }
<ide> public function testGroupConfigsWithCacheInstance()
<ide>
<ide> /**
<ide> * testGroupConfigsThrowsException method
<del> * @expectedException \InvalidArgumentException
<ide> */
<ide> public function testGroupConfigsThrowsException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Cache::groupConfigs('bogus');
<ide> }
<ide>
<ide> public function testWriteEmptyValues()
<ide> /**
<ide> * testWriteEmptyValues method
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage An empty value is not valid as a cache key
<ide> * @return void
<ide> */
<ide> public function testWriteEmptyKey()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('An empty value is not valid as a cache key');
<ide> $this->_configCache();
<ide> Cache::write(null, 'not null', 'tests');
<ide> }
<ide> public function testDeleteMany()
<ide> /**
<ide> * Test that failed writes cause errors to be triggered.
<ide> *
<del> * @expectedException \PHPUnit\Framework\Error\Error
<ide> * @return void
<ide> */
<ide> public function testWriteTriggerError()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\Error\Error::class);
<ide> static::setAppNamespace();
<ide> Cache::setConfig('test_trigger', [
<ide> 'engine' => 'TestAppCache',
<ide><path>tests/TestCase/Cache/Engine/MemcachedEngineTest.php
<ide> public function testOptionsSetting()
<ide> /**
<ide> * test accepts only valid serializer engine
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage invalid_serializer is not a valid serializer engine for Memcached
<ide> * @return void
<ide> */
<ide> public function testInvalidSerializerSetting()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('invalid_serializer is not a valid serializer engine for Memcached');
<ide> $Memcached = new MemcachedEngine();
<ide> $config = [
<ide> 'className' => 'Memcached',
<ide> public function testIgbinarySerializerThrowException()
<ide> * test using authentication without memcached installed with SASL support
<ide> * throw an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Memcached extension is not build with SASL support
<ide> * @return void
<ide> */
<ide> public function testSaslAuthException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Memcached extension is not build with SASL support');
<ide> $this->skipIf(
<ide> method_exists(Memcached::class, 'setSaslAuthData'),
<ide> 'Cannot test exception when sasl has been compiled in.'
<ide><path>tests/TestCase/Collection/CollectionTest.php
<ide> public function testToJson()
<ide> /**
<ide> * Tests that only arrays and Traversables are allowed in the constructor
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Only an array or \Traversable is allowed for Collection
<ide> * @return void
<ide> */
<ide> public function testInvalidConstructorArgument()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Only an array or \Traversable is allowed for Collection');
<ide> new Collection('Derp');
<ide> }
<ide>
<ide> /**
<ide> * Tests that issuing a count will throw an exception
<ide> *
<del> * @expectedException \LogicException
<ide> * @return void
<ide> */
<ide> public function testCollectionCount()
<ide> {
<add> $this->expectException(\LogicException::class);
<ide> $data = [1, 2, 3, 4];
<ide> $collection = new Collection($data);
<ide> $collection->count();
<ide> public function testCartesianProduct()
<ide> /**
<ide> * Tests that an exception is thrown if the cartesian product is called with multidimensional arrays
<ide> *
<del> * @expectedException \LogicException
<ide> * @return void
<ide> */
<ide> public function testCartesianProductMultidimensionalArray()
<ide> {
<add> $this->expectException(\LogicException::class);
<ide> $collection = new Collection([
<ide> [
<ide> 'names' => [
<ide> public function testTranspose()
<ide> /**
<ide> * Tests that provided arrays do not have even length
<ide> *
<del> * @expectedException \LogicException
<ide> * @return void
<ide> */
<ide> public function testTransposeUnEvenLengthShouldThrowException()
<ide> {
<add> $this->expectException(\LogicException::class);
<ide> $collection = new Collection([
<ide> ['Products', '2012', '2013', '2014'],
<ide> ['Product A', '200', '100', '50'],
<ide><path>tests/TestCase/Collection/Iterator/MapReduceTest.php
<ide> public function testEmitFinalInMapper()
<ide> /**
<ide> * Tests that a reducer is required when there are intermediate results
<ide> *
<del> * @expectedException \LogicException
<ide> * @return void
<ide> */
<ide> public function testReducerRequired()
<ide> {
<add> $this->expectException(\LogicException::class);
<ide> $data = ['a' => ['one', 'two'], 'b' => ['three', 'four']];
<ide> $mapper = function ($row, $key, $mr) {
<ide> foreach ($row as $number) {
<ide><path>tests/TestCase/Console/CommandCollectionTest.php
<ide> public function testConstructor()
<ide> * Constructor with invalid class names should blow up
<ide> *
<ide> * @return void
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Cannot use 'stdClass' for command 'nope' it is not a subclass of Cake\Console\Shell
<ide> */
<ide> public function testConstructorInvalidClass()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot use \'stdClass\' for command \'nope\' it is not a subclass of Cake\Console\Shell');
<ide> new CommandCollection([
<ide> 'i18n' => I18nShell::class,
<ide> 'nope' => stdClass::class
<ide> public function testAddInstance()
<ide> /**
<ide> * Instances that are not shells should fail.
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Cannot use 'stdClass' for command 'routes' it is not a subclass of Cake\Console\Shell
<ide> */
<ide> public function testAddInvalidInstance()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot use \'stdClass\' for command \'routes\' it is not a subclass of Cake\Console\Shell');
<ide> $collection = new CommandCollection();
<ide> $shell = new stdClass();
<ide> $collection->add('routes', $shell);
<ide> public function testAddInvalidInstance()
<ide> /**
<ide> * Class names that are not shells should fail
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Cannot use 'stdClass' for command 'routes' it is not a subclass of Cake\Console\Shell
<ide> */
<ide> public function testInvalidShellClassName()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot use \'stdClass\' for command \'routes\' it is not a subclass of Cake\Console\Shell');
<ide> $collection = new CommandCollection();
<ide> $collection->add('routes', stdClass::class);
<ide> }
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> public function setUp()
<ide> * Test that the console hook not returning a command collection
<ide> * raises an error.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage The application's `console` method did not return a CommandCollection.
<ide> * @return void
<ide> */
<ide> public function testRunConsoleHookFailure()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('The application\'s `console` method did not return a CommandCollection.');
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<ide> ->setMethods(['console', 'middleware', 'bootstrap'])
<ide> ->setConstructorArgs([$this->config])
<ide> public function testRunConsoleHookFailure()
<ide> /**
<ide> * Test that running with empty argv fails
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot run any commands. No arguments received.
<ide> * @return void
<ide> */
<ide> public function testRunMissingRootCommand()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot run any commands. No arguments received.');
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<ide> ->setMethods(['middleware', 'bootstrap'])
<ide> ->setConstructorArgs([$this->config])
<ide> public function testRunMissingRootCommand()
<ide> /**
<ide> * Test that running an unknown command raises an error.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Unknown command `cake nope`. Run `cake --help` to get the list of valid commands.
<ide> * @return void
<ide> */
<ide> public function testRunInvalidCommand()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Unknown command `cake nope`. Run `cake --help` to get the list of valid commands.');
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<ide> ->setMethods(['middleware', 'bootstrap'])
<ide> ->setConstructorArgs([$this->config])
<ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php
<ide> public function testAddOptionWithMultipleShort()
<ide> * Test that adding an option using a two letter short value causes an exception.
<ide> * As they will not parse correctly.
<ide> *
<del> * @expectedException \Cake\Console\Exception\ConsoleException
<ide> * @return void
<ide> */
<ide> public function testAddOptionShortOneLetter()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<ide> $parser = new ConsoleOptionParser('test', false);
<ide> $parser->addOption('test', ['short' => 'te']);
<ide> }
<ide> public function testOptionWithBooleanParam()
<ide> /**
<ide> * test parsing options that do not exist.
<ide> *
<del> * @expectedException \Cake\Console\Exception\ConsoleException
<ide> * @expectedExceptionMessageRegexp /Unknown option `fail`.\n\nDid you mean `help` \?\n\nAvailable options are :\n\n
<ide> * - help\n - no-commit/
<ide> * @return void
<ide> */
<ide> public function testOptionThatDoesNotExist()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<ide> $parser = new ConsoleOptionParser('test', false);
<ide> $parser->addOption('no-commit', ['boolean' => true]);
<ide>
<ide> public function testOptionThatDoesNotExist()
<ide> /**
<ide> * test parsing short options that do not exist.
<ide> *
<del> * @expectedException \Cake\Console\Exception\ConsoleException
<ide> * @expectedExceptionMessageRegexp /Unknown short option `f`.\n\nAvailable short options are :\n\n
<ide> * - `n` (short for `--no-commit`)\n - `c` (short for `--clear`)/
<ide> * @return void
<ide> */
<ide> public function testShortOptionThatDoesNotExist()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<ide> $parser = new ConsoleOptionParser('test', false);
<ide> $parser->addOption('no-commit', ['boolean' => true, 'short' => 'n']);
<ide> $parser->addOption('construct', ['boolean' => true]);
<ide> public function testShortOptionThatDoesNotExist()
<ide> /**
<ide> * test that options with choices enforce them.
<ide> *
<del> * @expectedException \Cake\Console\Exception\ConsoleException
<ide> * @return void
<ide> */
<ide> public function testOptionWithChoices()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<ide> $parser = new ConsoleOptionParser('test', false);
<ide> $parser->addOption('name', ['choices' => ['mark', 'jose']]);
<ide>
<ide> public function testPositionalArgOverwrite()
<ide> /**
<ide> * test parsing arguments.
<ide> *
<del> * @expectedException \Cake\Console\Exception\ConsoleException
<ide> * @return void
<ide> */
<ide> public function testParseArgumentTooMany()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<ide> $parser = new ConsoleOptionParser('test', false);
<ide> $parser->addArgument('name', ['help' => 'An argument'])
<ide> ->addArgument('other');
<ide> public function testParseArgumentZero()
<ide> /**
<ide> * test that when there are not enough arguments an exception is raised
<ide> *
<del> * @expectedException \Cake\Console\Exception\ConsoleException
<ide> * @return void
<ide> */
<ide> public function testPositionalArgNotEnough()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<ide> $parser = new ConsoleOptionParser('test', false);
<ide> $parser->addArgument('name', ['required' => true])
<ide> ->addArgument('other', ['required' => true]);
<ide> public function testPositionalArgNotEnough()
<ide> /**
<ide> * test that when there are required arguments after optional ones an exception is raised
<ide> *
<del> * @expectedException \LogicException
<ide> * @return void
<ide> */
<ide> public function testPositionalArgRequiredAfterOptional()
<ide> {
<add> $this->expectException(\LogicException::class);
<ide> $parser = new ConsoleOptionParser('test');
<ide> $parser->addArgument('name', ['required' => false])
<ide> ->addArgument('other', ['required' => true]);
<ide> public function testPositionalArgRequiredAfterOptional()
<ide> /**
<ide> * test that arguments with choices enforce them.
<ide> *
<del> * @expectedException \Cake\Console\Exception\ConsoleException
<ide> * @return void
<ide> */
<ide> public function testPositionalArgWithChoices()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<ide> $parser = new ConsoleOptionParser('test', false);
<ide> $parser->addArgument('name', ['choices' => ['mark', 'jose']])
<ide> ->addArgument('alias', ['choices' => ['cowboy', 'samurai']])
<ide><path>tests/TestCase/Console/ConsoleOutputTest.php
<ide> public function testSetOutputAsPlain()
<ide> /**
<ide> * test set wrong type.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid output type "Foo".
<ide> */
<ide> public function testSetOutputWrongType()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid output type "Foo".');
<ide> $this->output->setOutputAs('Foo');
<ide> }
<ide>
<ide><path>tests/TestCase/Console/HelpFormatterTest.php
<ide> public function testWithHelpAlias()
<ide> /**
<ide> * Tests that setting a none string help alias triggers an exception
<ide> *
<del> * @expectedException \Cake\Console\Exception\ConsoleException
<del> * @expectedExceptionMessage Alias must be of type string.
<ide> * @return void
<ide> */
<ide> public function testWithNoneStringHelpAlias()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<add> $this->expectExceptionMessage('Alias must be of type string.');
<ide> $parser = new ConsoleOptionParser('mycommand', false);
<ide> $formatter = new HelpFormatter($parser);
<ide> $formatter->setAlias(['foo']);
<ide><path>tests/TestCase/Console/HelperRegistryTest.php
<ide> public function testLoadWithConfig()
<ide> /**
<ide> * test missing helper exception
<ide> *
<del> * @expectedException \Cake\Console\Exception\MissingHelperException
<ide> * @return void
<ide> */
<ide> public function testLoadMissingHelper()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\MissingHelperException::class);
<ide> $this->helpers->load('ThisTaskShouldAlwaysBeMissing');
<ide> }
<ide>
<ide><path>tests/TestCase/Console/ShellDispatcherTest.php
<ide> public function tearDown()
<ide> /**
<ide> * Test error on missing shell
<ide> *
<del> * @expectedException \Cake\Console\Exception\MissingShellException
<ide> * @return void
<ide> */
<ide> public function testFindShellMissing()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\MissingShellException::class);
<ide> $this->dispatcher->findShell('nope');
<ide> }
<ide>
<ide> /**
<ide> * Test error on missing plugin shell
<ide> *
<del> * @expectedException \Cake\Console\Exception\MissingShellException
<ide> * @return void
<ide> */
<ide> public function testFindShellMissingPlugin()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\MissingShellException::class);
<ide> $this->dispatcher->findShell('test_plugin.nope');
<ide> }
<ide>
<ide><path>tests/TestCase/Console/TaskRegistryTest.php
<ide> public function testLoad()
<ide> /**
<ide> * test missingtask exception
<ide> *
<del> * @expectedException \Cake\Console\Exception\MissingTaskException
<ide> * @return void
<ide> */
<ide> public function testLoadMissingTask()
<ide> {
<add> $this->expectException(\Cake\Console\Exception\MissingTaskException::class);
<ide> $this->Tasks->load('ThisTaskShouldAlwaysBeMissing');
<ide> }
<ide>
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testAuthorizeFalse()
<ide> /**
<ide> * testIsAuthorizedMissingFile function
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testIsAuthorizedMissingFile()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $this->Controller->Auth->config('authorize', 'Missing');
<ide> $this->Controller->Auth->isAuthorized(['User' => ['id' => 1]]);
<ide> }
<ide> public function testLoadAuthorizeResets()
<ide> /**
<ide> * testLoadAuthenticateNoFile function
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testLoadAuthenticateNoFile()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $this->Controller->Auth->config('authenticate', 'Missing');
<ide> $this->Controller->Auth->identify($this->Controller->request, $this->Controller->response);
<ide> }
<ide> public function testRedirectToUnauthorizedRedirectSuppressedAuthError()
<ide> /**
<ide> * Throw ForbiddenException if config `unauthorizedRedirect` is set to false
<ide> *
<del> * @expectedException \Cake\Network\Exception\ForbiddenException
<ide> * @return void
<ide> * @triggers Controller.startup $Controller
<ide> */
<ide> public function testForbiddenException()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\ForbiddenException::class);
<ide> $url = '/party/on';
<ide> $this->Auth->request = $request = new ServerRequest($url);
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> public function testUser()
<ide> /**
<ide> * testStatelessAuthNoRedirect method
<ide> *
<del> * @expectedException \Cake\Network\Exception\UnauthorizedException
<del> * @expectedExceptionCode 401
<ide> * @return void
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testStatelessAuthNoRedirect()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\UnauthorizedException::class);
<add> $this->expectExceptionCode(401);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $_SESSION = [];
<ide>
<ide><path>tests/TestCase/Controller/Component/CookieComponentTest.php
<ide> public function testSettings()
<ide> /**
<ide> * Test read when an invalid cipher is configured.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Invalid encryption cipher. Must be one of aes, rijndael.
<ide> * @return void
<ide> */
<ide> public function testReadInvalidCipher()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Invalid encryption cipher. Must be one of aes, rijndael.');
<ide> $this->request->cookies = [
<ide> 'Test' => $this->_encrypt('value'),
<ide> ];
<ide> public function testWriteSimple()
<ide> /**
<ide> * Test write when an invalid cipher is configured.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Invalid encryption cipher. Must be one of aes, rijndael.
<ide> * @return void
<ide> */
<ide> public function testWriteInvalidCipher()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Invalid encryption cipher. Must be one of aes, rijndael.');
<ide> $this->Cookie->config('encryption', 'derp');
<ide> $this->Cookie->write('Test', 'nope');
<ide> }
<ide><path>tests/TestCase/Controller/Component/CsrfComponentTest.php
<ide> public function testValidTokenInHeader($method)
<ide> * Test that the X-CSRF-Token works with the various http methods.
<ide> *
<ide> * @dataProvider httpMethodProvider
<del> * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
<ide> * @return void
<ide> * @triggers Controller.startup $controller
<ide> */
<ide> public function testInvalidTokenInHeader($method)
<ide> {
<add> $this->expectException(\Cake\Network\Exception\InvalidCsrfTokenException::class);
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<ide> public function testValidTokenRequestData($method)
<ide> * Test that request data works with the various http methods.
<ide> *
<ide> * @dataProvider httpMethodProvider
<del> * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
<ide> * @return void
<ide> */
<ide> public function testInvalidTokenRequestData($method)
<ide> {
<add> $this->expectException(\Cake\Network\Exception\InvalidCsrfTokenException::class);
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<ide> public function testInvalidTokenRequestData($method)
<ide> /**
<ide> * Test that missing post field fails
<ide> *
<del> * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
<ide> * @return void
<ide> */
<ide> public function testInvalidTokenRequestDataMissing()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\InvalidCsrfTokenException::class);
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<ide> public function testInvalidTokenRequestDataMissing()
<ide> * Test that missing header and cookie fails
<ide> *
<ide> * @dataProvider httpMethodProvider
<del> * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
<ide> * @return void
<ide> */
<ide> public function testInvalidTokenMissingCookie($method)
<ide> {
<add> $this->expectException(\Cake\Network\Exception\InvalidCsrfTokenException::class);
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> public function testPaginatorSetting()
<ide> /**
<ide> * Test that an exception is thrown when paginator option is invalid.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Paginator must be an instance of Cake\Datasource\Paginator
<ide> * @return void
<ide> */
<ide> public function testInvalidPaginatorOption()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Paginator must be an instance of Cake\Datasource\Paginator');
<ide> new PaginatorComponent($this->registry, [
<ide> 'paginator' => new stdClass()
<ide> ]);
<ide> public function testOutOfRangePageNumberStillProvidesPageCount()
<ide> /**
<ide> * Test that a really REALLY large page number gets clamped to the max page size.
<ide> *
<del> * @expectedException \Cake\Network\Exception\NotFoundException
<ide> * @return void
<ide> */
<ide> public function testOutOfVeryBigPageNumberGetsClamped()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\NotFoundException::class);
<ide> $this->loadFixtures('Posts');
<ide> $this->request->query = [
<ide> 'page' => '3000000000000000000000000',
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testBeforeRedirectCallbackWithArrayUrl()
<ide> /**
<ide> * testAddInputTypeException method
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testAddInputTypeException()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED);
<ide> $this->RequestHandler->addInputType('csv', ['I am not callable']);
<ide> error_reporting($restore);
<ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php
<ide> public function validatePost($expectedException = null, $expectedExceptionMessag
<ide> * Test that requests are still blackholed when controller has incorrect
<ide> * visibility keyword in the blackhole callback.
<ide> *
<del> * @expectedException \Cake\Network\Exception\BadRequestException
<ide> * @return void
<ide> * @triggers Controller.startup $Controller, $this->Controller
<ide> */
<ide> public function testBlackholeWithBrokenCallback()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\BadRequestException::class);
<ide> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'session' => $this->Security->session
<ide> public function testValidatePostDebugFormat()
<ide> *
<ide> * Test blackhole will now throw passed exception if debug enabled.
<ide> *
<del> * @expectedException \Cake\Controller\Exception\SecurityException
<del> * @expectedExceptionMessage error description
<ide> * @return void
<ide> */
<ide> public function testBlackholeThrowsException()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\SecurityException::class);
<add> $this->expectExceptionMessage('error description');
<ide> $this->Security->config('blackHoleCallback', '');
<ide> $this->Security->blackHole($this->Controller, 'auth', new SecurityException('error description'));
<ide> }
<ide> public function testValidatePostUnexpectedDebugToken()
<ide> * Auth required throws exception token not found.
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Controller\Exception\AuthSecurityException
<del> * @expectedExceptionMessage '_Token' was not found in request data.
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundPost()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\AuthSecurityException::class);
<add> $this->expectExceptionMessage('\'_Token\' was not found in request data.');
<ide> $this->Security->config('requireAuth', ['protected']);
<ide> $this->Controller->request->params['action'] = 'protected';
<ide> $this->Controller->request->data = 'notEmpty';
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundPost()
<ide> * Auth required throws exception token not found in Session.
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Controller\Exception\AuthSecurityException
<del> * @expectedExceptionMessage '_Token' was not found in session.
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundSession()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\AuthSecurityException::class);
<add> $this->expectExceptionMessage('\'_Token\' was not found in session.');
<ide> $this->Security->config('requireAuth', ['protected']);
<ide> $this->Controller->request->params['action'] = 'protected';
<ide> $this->Controller->request->data = ['_Token' => 'not empty'];
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundSession()
<ide> * Auth required throws exception controller not allowed.
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Controller\Exception\AuthSecurityException
<del> * @expectedExceptionMessage Controller 'NotAllowed' was not found in allowed controllers: 'Allowed, AnotherAllowed'.
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testAuthRequiredThrowsExceptionControllerNotAllowed()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\AuthSecurityException::class);
<add> $this->expectExceptionMessage('Controller \'NotAllowed\' was not found in allowed controllers: \'Allowed, AnotherAllowed\'.');
<ide> $this->Security->config('requireAuth', ['protected']);
<ide> $this->Controller->request->params['controller'] = 'NotAllowed';
<ide> $this->Controller->request->params['action'] = 'protected';
<ide> public function testAuthRequiredThrowsExceptionControllerNotAllowed()
<ide> * Auth required throws exception controller not allowed.
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Controller\Exception\AuthSecurityException
<del> * @expectedExceptionMessage Action 'NotAllowed::protected' was not found in allowed actions: 'index, view'.
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testAuthRequiredThrowsExceptionActionNotAllowed()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\AuthSecurityException::class);
<add> $this->expectExceptionMessage('Action \'NotAllowed::protected\' was not found in allowed actions: \'index, view\'.');
<ide> $this->Security->config('requireAuth', ['protected']);
<ide> $this->Controller->request->params['controller'] = 'NotAllowed';
<ide> $this->Controller->request->params['action'] = 'protected';
<ide><path>tests/TestCase/Controller/ComponentRegistryTest.php
<ide> public function testLoadWithEnableFalse()
<ide> /**
<ide> * test MissingComponent exception
<ide> *
<del> * @expectedException \Cake\Controller\Exception\MissingComponentException
<ide> * @return void
<ide> */
<ide> public function testLoadMissingComponent()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\MissingComponentException::class);
<ide> $this->Components->load('ThisComponentShouldAlwaysBeMissing');
<ide> }
<ide>
<ide> public function testUnset()
<ide> /**
<ide> * Test that unloading a none existing component triggers an error.
<ide> *
<del> * @expectedException \Cake\Controller\Exception\MissingComponentException
<del> * @expectedExceptionMessage Component class FooComponent could not be found.
<ide> * @return void
<ide> */
<ide> public function testUnloadUnknown()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\MissingComponentException::class);
<add> $this->expectExceptionMessage('Component class FooComponent could not be found.');
<ide> $this->Components->unload('Foo');
<ide> }
<ide>
<ide><path>tests/TestCase/Controller/ComponentTest.php
<ide> public function testMultipleComponentInitialize()
<ide> /**
<ide> * Test a duplicate component being loaded more than once with same and differing configurations.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage The "Banana" alias has already been loaded with the following config:
<ide> * @return void
<ide> */
<ide> public function testDuplicateComponentInitialize()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('The "Banana" alias has already been loaded with the following config:');
<ide> $Collection = new ComponentRegistry();
<ide> $Collection->load('Banana', ['property' => ['closure' => function () {
<ide> }]]);
<ide> public function testLazyLoading()
<ide> /**
<ide> * Lazy load a component that does not exist.
<ide> *
<del> * @expectedException \Cake\Controller\Exception\MissingComponentException
<del> * @expectedExceptionMessage Component class YouHaveNoBananasComponent could not be found.
<ide> * @return void
<ide> */
<ide> public function testLazyLoadingDoesNotExists()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\MissingComponentException::class);
<add> $this->expectExceptionMessage('Component class YouHaveNoBananasComponent could not be found.');
<ide> $Component = new ConfiguredComponent(new ComponentRegistry(), [], ['YouHaveNoBananas']);
<ide> $bananas = $Component->YouHaveNoBananas;
<ide> }
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testPaginateUsesModelClass()
<ide> /**
<ide> * testMissingAction method
<ide> *
<del> * @expectedException \Cake\Controller\Exception\MissingActionException
<del> * @expectedExceptionMessage Action TestController::missing() could not be found, or is not accessible.
<ide> * @return void
<ide> */
<ide> public function testInvokeActionMissingAction()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
<add> $this->expectExceptionMessage('Action TestController::missing() could not be found, or is not accessible.');
<ide> $url = new ServerRequest('test/missing');
<ide> $url->addParams(['controller' => 'Test', 'action' => 'missing']);
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> public function testInvokeActionMissingAction()
<ide> /**
<ide> * test invoking private methods.
<ide> *
<del> * @expectedException \Cake\Controller\Exception\MissingActionException
<del> * @expectedExceptionMessage Action TestController::private_m() could not be found, or is not accessible.
<ide> * @return void
<ide> */
<ide> public function testInvokeActionPrivate()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
<add> $this->expectExceptionMessage('Action TestController::private_m() could not be found, or is not accessible.');
<ide> $url = new ServerRequest('test/private_m/');
<ide> $url->addParams(['controller' => 'Test', 'action' => 'private_m']);
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> public function testInvokeActionPrivate()
<ide> /**
<ide> * test invoking protected methods.
<ide> *
<del> * @expectedException \Cake\Controller\Exception\MissingActionException
<del> * @expectedExceptionMessage Action TestController::protected_m() could not be found, or is not accessible.
<ide> * @return void
<ide> */
<ide> public function testInvokeActionProtected()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
<add> $this->expectExceptionMessage('Action TestController::protected_m() could not be found, or is not accessible.');
<ide> $url = new ServerRequest('test/protected_m/');
<ide> $url->addParams(['controller' => 'Test', 'action' => 'protected_m']);
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> public function testInvokeActionProtected()
<ide> /**
<ide> * test invoking controller methods.
<ide> *
<del> * @expectedException \Cake\Controller\Exception\MissingActionException
<del> * @expectedExceptionMessage Action TestController::redirect() could not be found, or is not accessible.
<ide> * @return void
<ide> */
<ide> public function testInvokeActionBaseMethods()
<ide> {
<add> $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
<add> $this->expectExceptionMessage('Action TestController::redirect() could not be found, or is not accessible.');
<ide> $url = new ServerRequest('test/redirect/');
<ide> $url->addParams(['controller' => 'Test', 'action' => 'redirect']);
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide><path>tests/TestCase/Core/Configure/Engine/IniConfigTest.php
<ide> public function testBooleanReading()
<ide> /**
<ide> * Test an exception is thrown by reading files that exist without .ini extension.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithExistentFileWithoutExtension()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new IniConfig($this->path);
<ide> $engine->read('no_ini_extension');
<ide> }
<ide>
<ide> /**
<ide> * Test an exception is thrown by reading files that don't exist.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithNonExistentFile()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new IniConfig($this->path);
<ide> $engine->read('fake_values');
<ide> }
<ide> public function testReadEmptyFile()
<ide> /**
<ide> * Test reading keys with ../ doesn't work.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithDots()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new IniConfig($this->path);
<ide> $engine->read('../empty');
<ide> }
<ide><path>tests/TestCase/Core/Configure/Engine/JsonConfigTest.php
<ide> public function testRead()
<ide> /**
<ide> * Test an exception is thrown by reading files that exist without .php extension.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithExistentFileWithoutExtension()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new JsonConfig($this->path);
<ide> $engine->read('no_json_extension');
<ide> }
<ide>
<ide> /**
<ide> * Test an exception is thrown by reading files that don't exist.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithNonExistentFile()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new JsonConfig($this->path);
<ide> $engine->read('fake_values');
<ide> }
<ide>
<ide> /**
<ide> * Test reading an empty file.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage config file "empty.json"
<ide> * @return void
<ide> */
<ide> public function testReadEmptyFile()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('config file "empty.json"');
<ide> $engine = new JsonConfig($this->path);
<ide> $config = $engine->read('empty');
<ide> }
<ide>
<ide> /**
<ide> * Test an exception is thrown by reading files that contain invalid JSON.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage Error parsing JSON string fetched from config file "invalid.json"
<ide> * @return void
<ide> */
<ide> public function testReadWithInvalidJson()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('Error parsing JSON string fetched from config file "invalid.json"');
<ide> $engine = new JsonConfig($this->path);
<ide> $engine->read('invalid');
<ide> }
<ide>
<ide> /**
<ide> * Test reading keys with ../ doesn't work.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithDots()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new JsonConfig($this->path);
<ide> $engine->read('../empty');
<ide> }
<ide><path>tests/TestCase/Core/Configure/Engine/PhpConfigTest.php
<ide> public function testRead()
<ide> /**
<ide> * Test an exception is thrown by reading files that exist without .php extension.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithExistentFileWithoutExtension()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new PhpConfig($this->path);
<ide> $engine->read('no_php_extension');
<ide> }
<ide>
<ide> /**
<ide> * Test an exception is thrown by reading files that don't exist.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithNonExistentFile()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new PhpConfig($this->path);
<ide> $engine->read('fake_values');
<ide> }
<ide>
<ide> /**
<ide> * Test reading an empty file.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadEmptyFile()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new PhpConfig($this->path);
<ide> $engine->read('empty');
<ide> }
<ide>
<ide> /**
<ide> * Test reading keys with ../ doesn't work.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testReadWithDots()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $engine = new PhpConfig($this->path);
<ide> $engine->read('../empty');
<ide> }
<ide><path>tests/TestCase/Core/ConfigureTest.php
<ide> public function testReadOrFail()
<ide> /**
<ide> * testReadOrFail method
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Expected configuration key "This.Key.Does.Not.exist" not found
<ide> * @return void
<ide> */
<ide> public function testReadOrFailThrowingException()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Expected configuration key "This.Key.Does.Not.exist" not found');
<ide> Configure::readOrFail('This.Key.Does.Not.exist');
<ide> }
<ide>
<ide> public function testCheckEmpty()
<ide> /**
<ide> * testLoad method
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testLoadExceptionOnNonExistentFile()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> Configure::config('test', new PhpConfig());
<ide> Configure::load('non_existing_configuration_file', 'test');
<ide> }
<ide> public function testClear()
<ide> }
<ide>
<ide> /**
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testDumpNoAdapter()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> Configure::dump(TMP . 'test.php', 'does_not_exist');
<ide> }
<ide>
<ide><path>tests/TestCase/Core/InstanceConfigTraitTest.php
<ide> public function testConfigShallow()
<ide> /**
<ide> * testSetClobber
<ide> *
<del> * @expectedException \Exception
<del> * @expectedExceptionMessage Cannot set a.nested.value
<ide> * @return void
<ide> */
<ide> public function testSetClobber()
<ide> {
<add> $this->expectException(\Exception::class);
<add> $this->expectExceptionMessage('Cannot set a.nested.value');
<ide> $this->object->config(['a.nested.value' => 'not possible'], null, false);
<ide> $result = $this->object->config();
<ide> }
<ide> public function testSetMergeNoClobber()
<ide> /**
<ide> * testReadOnlyConfig
<ide> *
<del> * @expectedException \Exception
<del> * @expectedExceptionMessage This Instance is readonly
<ide> * @return void
<ide> */
<ide> public function testReadOnlyConfig()
<ide> {
<add> $this->expectException(\Exception::class);
<add> $this->expectExceptionMessage('This Instance is readonly');
<ide> $object = new ReadOnlyTestInstanceConfig();
<ide>
<ide> $this->assertSame(
<ide> public function testDeleteArray()
<ide> /**
<ide> * testDeleteClobber
<ide> *
<del> * @expectedException \Exception
<del> * @expectedExceptionMessage Cannot unset a.nested.value.whoops
<ide> * @return void
<ide> */
<ide> public function testDeleteClobber()
<ide> {
<add> $this->expectException(\Exception::class);
<add> $this->expectExceptionMessage('Cannot unset a.nested.value.whoops');
<ide> $this->object->config('a.nested.value.whoops', null);
<ide> }
<ide> }
<ide><path>tests/TestCase/Core/PluginTest.php
<ide> public function testLoadMultipleWithDefaultsAndOverride()
<ide> * Tests that loading a missing routes file throws a warning
<ide> *
<ide> * @return void
<del> * @expectedException \PHPUnit\Framework\Error\Warning
<ide> */
<ide> public function testLoadMultipleWithDefaultsMissingFile()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\Error\Warning::class);
<ide> Plugin::load(['TestPlugin', 'TestPluginTwo'], ['bootstrap' => true, 'routes' => true]);
<ide> Plugin::routes();
<ide> }
<ide> public function testIgnoreMissingFiles()
<ide> * Tests that Plugin::load() throws an exception on unknown plugin
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Core\Exception\MissingPluginException
<ide> */
<ide> public function testLoadNotFound()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\MissingPluginException::class);
<ide> Plugin::load('MissingPlugin');
<ide> }
<ide>
<ide> public function testPath()
<ide> * Tests that Plugin::path() throws an exception on unknown plugin
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Core\Exception\MissingPluginException
<ide> */
<ide> public function testPathNotFound()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\MissingPluginException::class);
<ide> Plugin::path('TestPlugin');
<ide> }
<ide>
<ide> public function testClassPath()
<ide> * Tests that Plugin::classPath() throws an exception on unknown plugin
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Core\Exception\MissingPluginException
<ide> */
<ide> public function testClassPathNotFound()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\MissingPluginException::class);
<ide> Plugin::classPath('TestPlugin');
<ide> }
<ide>
<ide><path>tests/TestCase/Core/StaticConfigTraitTest.php
<ide> public function testSimpleParseDsn()
<ide> /**
<ide> * Tests that failing to pass a string to parseDsn will throw an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testParseBadType()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $className = get_class($this->subject);
<ide> $className::parseDsn(['url' => 'http://:80']);
<ide> }
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testConnect()
<ide> /**
<ide> * Tests creating a connection using no driver throws an exception
<ide> *
<del> * @expectedException \Cake\Database\Exception\MissingDriverException
<del> * @expectedExceptionMessage Database driver could not be found.
<ide> * @return void
<ide> */
<ide> public function testNoDriver()
<ide> {
<add> $this->expectException(\Cake\Database\Exception\MissingDriverException::class);
<add> $this->expectExceptionMessage('Database driver could not be found.');
<ide> $connection = new Connection([]);
<ide> }
<ide>
<ide> /**
<ide> * Tests creating a connection using an invalid driver throws an exception
<ide> *
<del> * @expectedException \Cake\Database\Exception\MissingDriverException
<del> * @expectedExceptionMessage Database driver could not be found.
<ide> * @return void
<ide> */
<ide> public function testEmptyDriver()
<ide> {
<add> $this->expectException(\Cake\Database\Exception\MissingDriverException::class);
<add> $this->expectExceptionMessage('Database driver could not be found.');
<ide> $connection = new Connection(['driver' => false]);
<ide> }
<ide>
<ide> /**
<ide> * Tests creating a connection using an invalid driver throws an exception
<ide> *
<del> * @expectedException \Cake\Database\Exception\MissingDriverException
<del> * @expectedExceptionMessage Database driver \Foo\InvalidDriver could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingDriver()
<ide> {
<add> $this->expectException(\Cake\Database\Exception\MissingDriverException::class);
<add> $this->expectExceptionMessage('Database driver \Foo\InvalidDriver could not be found.');
<ide> $connection = new Connection(['driver' => '\Foo\InvalidDriver']);
<ide> }
<ide>
<ide> /**
<ide> * Tests trying to use a disabled driver throws an exception
<ide> *
<del> * @expectedException \Cake\Database\Exception\MissingExtensionException
<del> * @expectedExceptionMessage Database driver DriverMock cannot be used due to a missing PHP extension or unmet dependency
<ide> * @return void
<ide> */
<ide> public function testDisabledDriver()
<ide> {
<add> $this->expectException(\Cake\Database\Exception\MissingExtensionException::class);
<add> $this->expectExceptionMessage('Database driver DriverMock cannot be used due to a missing PHP extension or unmet dependency');
<ide> $mock = $this->getMockBuilder(Mysql::class)
<ide> ->setMethods(['enabled'])
<ide> ->setMockClassName('DriverMock')
<ide> public function testDriverOptionClassNameSupport()
<ide> /**
<ide> * Tests that connecting with invalid credentials or database name throws an exception
<ide> *
<del> * @expectedException \Cake\Database\Exception\MissingConnectionException
<ide> * @return void
<ide> */
<ide> public function testWrongCredentials()
<ide> {
<add> $this->expectException(\Cake\Database\Exception\MissingConnectionException::class);
<ide> $config = ConnectionManager::getConfig('test');
<ide> $this->skipIf(isset($config['url']), 'Datasource has dsn, skipping.');
<ide> $connection = new Connection(['database' => '/dev/nonexistent'] + ConnectionManager::getConfig('test'));
<ide> public function testExecuteWithArgumentsAndTypes()
<ide> /**
<ide> * Tests that passing a unknown value to a query throws an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testExecuteWithMissingType()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $sql = 'SELECT ?';
<ide> $statement = $this->connection->execute($sql, [new \DateTime('2012-01-01')], ['bar']);
<ide> }
<ide> public function testTransactionalFail()
<ide> * Tests that the transactional method will rollback the transaction
<ide> * and throw the same exception if the callback raises one
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> * @throws \InvalidArgumentException
<ide> */
<ide> public function testTransactionalWithException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<ide> ->setMethods(['connect', 'commit', 'begin', 'rollback'])
<ide><path>tests/TestCase/Database/Driver/SqlserverTest.php
<ide> public function testConnectionPersistentFalse()
<ide> * Test if attempting to connect with the driver throws an exception when
<ide> * using an invalid config setting.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Config setting "persistent" cannot be set to true, as the Sqlserver PDO driver does not support PDO::ATTR_PERSISTENT
<ide> * @return void
<ide> */
<ide> public function testConnectionPersistentTrueException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Config setting "persistent" cannot be set to true, as the Sqlserver PDO driver does not support PDO::ATTR_PERSISTENT');
<ide> $this->skipIf($this->missingExtension, 'pdo_sqlsrv is not installed.');
<ide> $config = [
<ide> 'persistent' => true,
<ide><path>tests/TestCase/Database/DriverTest.php
<ide> public function setUp()
<ide> * Test if building the object throws an exception if we're not passing
<ide> * required config data.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Please pass "username" instead of "login" for connecting to the database
<ide> * @return void
<ide> */
<ide> public function testConstructorException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Please pass "username" instead of "login" for connecting to the database');
<ide> $arg = ['login' => 'Bear'];
<ide> $this->getMockForAbstractClass(Driver::class, [$arg]);
<ide> }
<ide><path>tests/TestCase/Database/Log/LoggingStatementTest.php
<ide> public function testExecuteWithBinding()
<ide> /**
<ide> * Tests that queries are logged despite database errors
<ide> *
<del> * @expectedException \LogicException
<del> * @expectedExceptionMessage This is bad
<ide> * @return void
<ide> */
<ide> public function testExecuteWithError()
<ide> {
<add> $this->expectException(\LogicException::class);
<add> $this->expectExceptionMessage('This is bad');
<ide> $exception = new \LogicException('This is bad');
<ide> $inner = $this->getMockBuilder('PDOStatement')->getMock();
<ide> $inner->expects($this->once())->method('execute')
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testSelectWhereArrayType()
<ide> * Tests that passing an empty array type to any where condition will not
<ide> * result in a SQL error, but an internal exception
<ide> *
<del> * @expectedException \Cake\Database\Exception
<del> * @expectedExceptionMessage Impossible to generate condition with empty list of values for field
<ide> * @return void
<ide> */
<ide> public function testSelectWhereArrayTypeEmpty()
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<add> $this->expectExceptionMessage('Impossible to generate condition with empty list of values for field');
<ide> $this->loadFixtures('Comments');
<ide> $query = new Query($this->connection);
<ide> $result = $query
<ide> public function testSelectWhereArrayTypeEmpty()
<ide>
<ide> /**
<ide> * Tests exception message for impossible condition when using an expression
<del> * @expectedException \Cake\Database\Exception
<del> * @expectedExceptionMessage with empty list of values for field (SELECT 1)
<ide> * @return void
<ide> */
<ide> public function testSelectWhereArrayTypeEmptyWithExpression()
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<add> $this->expectExceptionMessage('with empty list of values for field (SELECT 1)');
<ide> $this->loadFixtures('Comments');
<ide> $query = new Query($this->connection);
<ide> $result = $query
<ide> public function testDeleteNoFrom()
<ide> * from the conditions.
<ide> *
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Aliases are being removed from conditions for UPDATE/DELETE queries, this can break references to joined tables.
<ide> * @return void
<ide> */
<ide> public function testDeleteRemovingAliasesCanBreakJoins()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Aliases are being removed from conditions for UPDATE/DELETE queries, this can break references to joined tables.');
<ide> $query = new Query($this->connection);
<ide>
<ide> $query
<ide> public function testUpdateSimple()
<ide> * Test update with type checking
<ide> * by passing an array as table arg
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> *
<ide> * @return void
<ide> */
<ide> public function testUpdateArgTypeChecking()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $query = new Query($this->connection);
<ide> $query->update(['Articles']);
<ide> }
<ide> public function testUpdateStripAliasesFromConditions()
<ide> * warning about possible incompatibilities with aliases being removed
<ide> * from the conditions.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Aliases are being removed from conditions for UPDATE/DELETE queries, this can break references to joined tables.
<ide> * @return void
<ide> */
<ide> public function testUpdateRemovingAliasesCanBreakJoins()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Aliases are being removed from conditions for UPDATE/DELETE queries, this can break references to joined tables.');
<ide> $query = new Query($this->connection);
<ide>
<ide> $query
<ide> public function testUpdateRemovingAliasesCanBreakJoins()
<ide> /**
<ide> * You cannot call values() before insert() it causes all sorts of pain.
<ide> *
<del> * @expectedException \Cake\Database\Exception
<ide> * @return void
<ide> */
<ide> public function testInsertValuesBeforeInsertFailure()
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $query = new Query($this->connection);
<ide> $query->select('*')->values([
<ide> 'id' => 1,
<ide> public function testInsertValuesBeforeInsertFailure()
<ide> /**
<ide> * Inserting nothing should not generate an error.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage At least 1 column is required to perform an insert.
<ide> * @return void
<ide> */
<ide> public function testInsertNothing()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('At least 1 column is required to perform an insert.');
<ide> $query = new Query($this->connection);
<ide> $query->insert([]);
<ide> }
<ide> public function testInsertFromSelect()
<ide> /**
<ide> * Test that an exception is raised when mixing query + array types.
<ide> *
<del> * @expectedException \Cake\Database\Exception
<ide> */
<ide> public function testInsertFailureMixingTypesArrayFirst()
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $this->loadFixtures('Articles');
<ide> $query = new Query($this->connection);
<ide> $query->insert(['name'])
<ide> public function testInsertFailureMixingTypesArrayFirst()
<ide> /**
<ide> * Test that an exception is raised when mixing query + array types.
<ide> *
<del> * @expectedException \Cake\Database\Exception
<ide> */
<ide> public function testInsertFailureMixingTypesQueryFirst()
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $this->loadFixtures('Articles');
<ide> $query = new Query($this->connection);
<ide> $query->insert(['name'])
<ide> public function testGetValueBinder()
<ide> /**
<ide> * Test that reading an undefined clause does not emit an error.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The 'nope' clause is not defined. Valid clauses are: delete, update
<ide> * @return void
<ide> */
<ide> public function testClauseUndefined()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The \'nope\' clause is not defined. Valid clauses are: delete, update');
<ide> $query = new Query($this->connection);
<ide> $this->assertEmpty($query->clause('where'));
<ide> $query->clause('nope');
<ide><path>tests/TestCase/Database/Schema/CollectionTest.php
<ide> public function tearDown()
<ide> * Tests for positive describe() calls are in each platformSchema
<ide> * test case.
<ide> *
<del> * @expectedException \Cake\Database\Exception
<ide> * @return void
<ide> */
<ide> public function testDescribeIncorrectTable()
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $schema = new Collection($this->connection);
<ide> $this->assertNull($schema->describe('derp'));
<ide> }
<ide><path>tests/TestCase/Database/Schema/TableTest.php
<ide> public static function addConstraintErrorProvider()
<ide> * are added for fields that do not exist.
<ide> *
<ide> * @dataProvider addConstraintErrorProvider
<del> * @expectedException \Cake\Database\Exception
<ide> * @return void
<ide> */
<ide> public function testAddConstraintError($props)
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $table = new Table('articles');
<ide> $table->addColumn('author_id', 'integer');
<ide> $table->addConstraint('author_idx', $props);
<ide> public static function addIndexErrorProvider()
<ide> * are added for fields that do not exist.
<ide> *
<ide> * @dataProvider addIndexErrorProvider
<del> * @expectedException \Cake\Database\Exception
<ide> * @return void
<ide> */
<ide> public function testAddIndexError($props)
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $table = new Table('articles');
<ide> $table->addColumn('author_id', 'integer');
<ide> $table->addIndex('author_idx', $props);
<ide> public static function badForeignKeyProvider()
<ide> * Add a foreign key constraint with bad data
<ide> *
<ide> * @dataProvider badForeignKeyProvider
<del> * @expectedException \Cake\Database\Exception
<ide> * @return void
<ide> */
<ide> public function testAddConstraintForeignKeyBadData($data)
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $table = new Table('articles');
<ide> $table->addColumn('author_id', 'integer')
<ide> ->addConstraint('author_id_idx', $data);
<ide><path>tests/TestCase/Database/Type/BinaryTypeTest.php
<ide> public function testToPHPSqlserver()
<ide> /**
<ide> * Test exceptions on invalid data.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage Unable to convert array into binary.
<ide> */
<ide> public function testToPHPFailure()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('Unable to convert array into binary.');
<ide> $this->type->toPHP([], $this->driver);
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/BoolTypeTest.php
<ide> public function testToDatabase()
<ide> /**
<ide> * Test converting an array to boolean results in an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testToDatabaseInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->type->toDatabase([1, 2], $this->driver);
<ide> }
<ide>
<ide> /**
<ide> * Tests that passing an invalid value will throw an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testToDatabaseInvalidArray()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->type->toDatabase([1, 2, 3], $this->driver);
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/DecimalTypeTest.php
<ide> public function testToDatabase()
<ide> /**
<ide> * Arrays are invalid.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testToDatabaseInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->type->toDatabase(['3', '4'], $this->driver);
<ide> }
<ide>
<ide> public function testMarshallWithLocaleParsingDanish()
<ide> /**
<ide> * Test that exceptions are raised on invalid parsers.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testUseLocaleParsingInvalid()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> DecimalType::$numberClass = 'stdClass';
<ide> $this->type->useLocaleParser();
<ide> }
<ide><path>tests/TestCase/Database/Type/FloatTypeTest.php
<ide> public function testMarshalWithLocaleParsing()
<ide> /**
<ide> * Test that exceptions are raised on invalid parsers.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testUseLocaleParsingInvalid()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> FloatType::$numberClass = 'stdClass';
<ide> $this->type->useLocaleParser();
<ide> }
<ide><path>tests/TestCase/Database/Type/IntegerTypeTest.php
<ide> public function testToDatabase()
<ide> /**
<ide> * Tests that passing an invalid value will throw an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testToDatabaseInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->type->toDatabase(['3', '4'], $this->driver);
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/JsonTypeTest.php
<ide> public function testToDatabase()
<ide> /**
<ide> * Tests that passing an invalid value will throw an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testToDatabaseInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $value = fopen(__FILE__, 'r');
<ide> $this->type->toDatabase($value, $this->driver);
<ide> }
<ide><path>tests/TestCase/Database/Type/StringTypeTest.php
<ide> public function testToDatabase()
<ide> /**
<ide> * Tests that passing an invalid value will throw an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testToDatabaseInvalidArray()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->type->toDatabase([1, 2, 3], $this->driver);
<ide> }
<ide>
<ide><path>tests/TestCase/Database/TypeTest.php
<ide> public function basicTypesProvider()
<ide> /**
<ide> * Tests trying to build an unknown type throws exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testBuildUnknownType()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Type::build('foo');
<ide> }
<ide>
<ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php
<ide> public function testConfigVariants($settings)
<ide> /**
<ide> * Test invalid classes cause exceptions
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\MissingDatasourceException
<ide> */
<ide> public function testConfigInvalidOptions()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\MissingDatasourceException::class);
<ide> ConnectionManager::config('test_variant', [
<ide> 'className' => 'Herp\Derp'
<ide> ]);
<ide> public function testConfigInvalidOptions()
<ide> /**
<ide> * Test for errors on duplicate config.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Cannot reconfigure existing key "test_variant"
<ide> * @return void
<ide> */
<ide> public function testConfigDuplicateConfig()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Cannot reconfigure existing key "test_variant"');
<ide> $settings = [
<ide> 'className' => __NAMESPACE__ . '\FakeConnection',
<ide> 'database' => ':memory:',
<ide> public function testConfigDuplicateConfig()
<ide> /**
<ide> * Test get() failing on missing config.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage The datasource configuration "test_variant" was not found.
<ide> * @return void
<ide> */
<ide> public function testGetFailOnMissingConfig()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('The datasource configuration "test_variant" was not found.');
<ide> ConnectionManager::get('test_variant');
<ide> }
<ide>
<ide> public function testGet()
<ide> /**
<ide> * Test loading connections without aliases
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage The datasource configuration "other_name" was not found.
<ide> * @return void
<ide> */
<ide> public function testGetNoAlias()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('The datasource configuration "other_name" was not found.');
<ide> $config = ConnectionManager::config('test');
<ide> $this->skipIf(empty($config), 'No test config, skipping');
<ide>
<ide> public function testAlias()
<ide> /**
<ide> * Test alias() raises an error when aliasing an undefined connection.
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\MissingDatasourceConfigException
<ide> * @return void
<ide> */
<ide> public function testAliasError()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\MissingDatasourceConfigException::class);
<ide> $this->assertNotContains('test_kaboom', ConnectionManager::configured());
<ide> ConnectionManager::alias('test_kaboom', 'other_name');
<ide> }
<ide> public function testParseDsn($dsn, $expected)
<ide> /**
<ide> * Test parseDsn invalid.
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage The DSN string 'bagof:nope' could not be parsed.
<ide> * @return void
<ide> */
<ide> public function testParseDsnInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The DSN string \'bagof:nope\' could not be parsed.');
<ide> $result = ConnectionManager::parseDsn('bagof:nope');
<ide> }
<ide>
<ide><path>tests/TestCase/Datasource/FactoryLocatorTest.php
<ide> public function testGet()
<ide> * Test get non existing factory
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Unknown repository type "Test". Make sure you register a type before trying to use it.
<ide> */
<ide> public function testGetNonExisting()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Unknown repository type "Test". Make sure you register a type before trying to use it.');
<ide> FactoryLocator::get('Test');
<ide> }
<ide>
<ide> public function testAdd()
<ide> * test drop()
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Unknown repository type "Test". Make sure you register a type before trying to use it.
<ide> */
<ide> public function testDrop()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Unknown repository type "Test". Make sure you register a type before trying to use it.');
<ide> FactoryLocator::drop('Test');
<ide>
<ide> FactoryLocator::get('Test');
<ide> public function testModelType()
<ide> * test MissingModelException being thrown
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Datasource\Exception\MissingModelException
<del> * @expectedExceptionMessage Model class "Magic" of type "Test" could not be found.
<ide> */
<ide> public function testMissingModelException()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\MissingModelException::class);
<add> $this->expectExceptionMessage('Model class "Magic" of type "Test" could not be found.');
<ide> $stub = new Stub();
<ide>
<ide> FactoryLocator::add('Test', function ($name) {
<ide><path>tests/TestCase/Datasource/ModelAwareTraitTest.php
<ide> public function testGetSetModelType()
<ide> * test MissingModelException being thrown
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\Datasource\Exception\MissingModelException
<del> * @expectedExceptionMessage Model class "Magic" of type "Test" could not be found.
<ide> */
<ide> public function testMissingModelException()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\MissingModelException::class);
<add> $this->expectExceptionMessage('Model class "Magic" of type "Test" could not be found.');
<ide> $stub = new Stub();
<ide>
<ide> FactoryLocator::add('Test', function ($name) {
<ide><path>tests/TestCase/Datasource/PaginatorTest.php
<ide> public function testOutOfRangePageNumberGetsClamped()
<ide> /**
<ide> * Test that a really REALLY large page number gets clamped to the max page size.
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\PageOutOfBoundsException
<ide> * @return void
<ide> */
<ide> public function testOutOfVeryBigPageNumberGetsClamped()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\PageOutOfBoundsException::class);
<ide> $this->loadFixtures('Posts');
<ide> $params = [
<ide> 'page' => '3000000000000000000000000',
<ide><path>tests/TestCase/Datasource/QueryCacherTest.php
<ide> public function testFetchFunctionKey()
<ide> /**
<ide> * Test fetching with a function to generate the key but the function is poop.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cache key functions must return a string. Got false.
<ide> * @return void
<ide> */
<ide> public function testFetchFunctionKeyNoString()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cache key functions must return a string. Got false.');
<ide> $this->_mockRead('my_key', 'A winner');
<ide> $query = $this->getMockBuilder('stdClass')->getMock();
<ide>
<ide><path>tests/TestCase/Error/DebuggerTest.php
<ide> public function testOutputAs()
<ide> /**
<ide> * Test that choosing a non-existent format causes an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testOutputAsException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Debugger::outputAs('Invalid junk');
<ide> }
<ide>
<ide> public function testGetSetOutputFormat()
<ide> /**
<ide> * Test that choosing a non-existent format causes an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testSetOutputAsException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Debugger::setOutputFormat('Invalid junk');
<ide> }
<ide>
<ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php
<ide> public function testNoErrorResponse()
<ide> /**
<ide> * Test an invalid rendering class.
<ide> *
<del> * @expectedException \Exception
<del> * @expectedExceptionMessage The 'TotallyInvalid' renderer class could not be found
<ide> */
<ide> public function testInvalidRenderer()
<ide> {
<add> $this->expectException(\Exception::class);
<add> $this->expectExceptionMessage('The \'TotallyInvalid\' renderer class could not be found');
<ide> $request = ServerRequestFactory::fromGlobals();
<ide> $response = new Response();
<ide>
<ide><path>tests/TestCase/Event/Decorator/ConditionDecoratorTest.php
<ide> public function testCascadingEvents()
<ide> /**
<ide> * testCallableRuntimeException
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cake\Event\Decorator\ConditionDecorator the `if` condition is not a callable!
<ide> */
<ide> public function testCallableRuntimeException()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cake\Event\Decorator\ConditionDecorator the `if` condition is not a callable!');
<ide> $callable = function (Event $event) {
<ide> return 'success';
<ide> };
<ide><path>tests/TestCase/Filesystem/FolderTest.php
<ide> public function inPathInvalidPathArgumentDataProvider()
<ide> /**
<ide> * @dataProvider inPathInvalidPathArgumentDataProvider
<ide> * @param string $path
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The $path argument is expected to be an absolute path.
<ide> */
<ide> public function testInPathInvalidPathArgument($path)
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The $path argument is expected to be an absolute path.');
<ide> $Folder = new Folder();
<ide> $Folder->inPath($path);
<ide> }
<ide><path>tests/TestCase/Http/ActionDispatcherTest.php
<ide> public function testDispatchSetsRequestContext()
<ide> /**
<ide> * test invalid response from dispatch process.
<ide> *
<del> * @expectedException \LogicException
<del> * @expectedExceptionMessage Controller actions can only return Cake\Http\Response or null
<ide> * @return void
<ide> */
<ide> public function testDispatchInvalidResponse()
<ide> {
<add> $this->expectException(\LogicException::class);
<add> $this->expectExceptionMessage('Controller actions can only return Cake\Http\Response or null');
<ide> $req = new ServerRequest([
<ide> 'url' => '/cakes',
<ide> 'params' => [
<ide> public function testDispatchAutoRenderFalse()
<ide> /**
<ide> * testMissingController method
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class SomeController could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingController()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class SomeController could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'some_controller/home',
<ide> 'params' => [
<ide> public function testMissingController()
<ide> /**
<ide> * testMissingControllerInterface method
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class Interface could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingControllerInterface()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class Interface could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> public function testMissingControllerInterface()
<ide> /**
<ide> * testMissingControllerInterface method
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class Abstract could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingControllerAbstract()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class Abstract could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'abstract/index',
<ide> 'params' => [
<ide> public function testMissingControllerAbstract()
<ide> * In case-insensitive file systems, lowercase controller names will kind of work.
<ide> * This causes annoying deployment issues for lots of folks.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class somepages could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingControllerLowercase()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class somepages could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'pages/home',
<ide> 'params' => [
<ide><path>tests/TestCase/Http/Client/Adapter/StreamTest.php
<ide> public function testKeepDeadline()
<ide> /**
<ide> * Test that an exception is raised when timed out.
<ide> *
<del> * @expectedException \Cake\Network\Exception\HttpException
<del> * @expectedExceptionMessage Connection timed out http://dummy/?sleep
<ide> * @return void
<ide> */
<ide> public function testMissDeadline()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\HttpException::class);
<add> $this->expectExceptionMessage('Connection timed out http://dummy/?sleep');
<ide> $request = new Request();
<ide> $request->url('http://dummy/?sleep');
<ide> $options = [
<ide><path>tests/TestCase/Http/Client/Auth/OauthTest.php
<ide> class OauthTest extends TestCase
<ide> -----END RSA PRIVATE KEY-----';
<ide>
<ide> /**
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> */
<ide> public function testExceptionUnknownSigningMethod()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $auth = new Oauth();
<ide> $creds = [
<ide> 'consumerSecret' => 'it is secret',
<ide><path>tests/TestCase/Http/Client/RequestTest.php
<ide> public function testMethodInteroperability()
<ide> /**
<ide> * test invalid method.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testMethodInvalid()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $request = new Request();
<ide> $request->method('set on fire');
<ide> }
<ide><path>tests/TestCase/Http/ClientTest.php
<ide> public function testGetWithContent()
<ide> /**
<ide> * Test invalid authentication types throw exceptions.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testInvalidAuthenticationType()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
<ide> ->setMethods(['send'])
<ide> ->getMock();
<ide> public function testPostWithStringDataDefaultsToFormEncoding()
<ide> /**
<ide> * Test that exceptions are raised on invalid types.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testExceptionOnUnknownType()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
<ide> ->setMethods(['send'])
<ide> ->getMock();
<ide> public function testAddCookie()
<ide> * Test addCookie() method without a domain.
<ide> *
<ide> * @return void
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Cookie must have a domain and a path set.
<ide> */
<ide> public function testAddCookieWithoutDomain()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cookie must have a domain and a path set.');
<ide> $client = new Client();
<ide> $cookie = new Cookie('foo', '', null, '/', '');
<ide>
<ide> public function testAddCookieWithoutDomain()
<ide> * Test addCookie() method without a path.
<ide> *
<ide> * @return void
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Cookie must have a domain and a path set.
<ide> */
<ide> public function testAddCookieWithoutPath()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cookie must have a domain and a path set.');
<ide> $client = new Client();
<ide> $cookie = new Cookie('foo', '', null, '', 'example.com');
<ide>
<ide><path>tests/TestCase/Http/ControllerFactoryTest.php
<ide> public function testPrefixedPluginController()
<ide> }
<ide>
<ide> /**
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class Abstract could not be found.
<ide> * @return void
<ide> */
<ide> public function testAbstractClassFailure()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class Abstract could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'abstract/index',
<ide> 'params' => [
<ide> public function testAbstractClassFailure()
<ide> }
<ide>
<ide> /**
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class Interface could not be found.
<ide> * @return void
<ide> */
<ide> public function testInterfaceFailure()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class Interface could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> public function testInterfaceFailure()
<ide> }
<ide>
<ide> /**
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class Invisible could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingClassFailure()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class Invisible could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> public function testMissingClassFailure()
<ide> }
<ide>
<ide> /**
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class Admin/Posts could not be found.
<ide> * @return void
<ide> */
<ide> public function testSlashedControllerFailure()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class Admin/Posts could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'admin/posts/index',
<ide> 'params' => [
<ide> public function testSlashedControllerFailure()
<ide> }
<ide>
<ide> /**
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class TestApp\Controller\CakesController could not be found.
<ide> * @return void
<ide> */
<ide> public function testAbsoluteReferenceFailure()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class TestApp\Controller\CakesController could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide><path>tests/TestCase/Http/Cookie/CookieCollectionTest.php
<ide> public function testGetByName()
<ide> * Test that the constructor takes only an array of objects implementing
<ide> * the CookieInterface
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Expected `Cake\Http\Cookie\CookieCollection[]` as $cookies but instead got `array` at index 1
<ide> * @return void
<ide> */
<ide> public function testConstructorWithInvalidCookieObjects()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Expected `Cake\Http\Cookie\CookieCollection[]` as $cookies but instead got `array` at index 1');
<ide> $array = [
<ide> new Cookie('one', 'one'),
<ide> []
<ide><path>tests/TestCase/Http/Cookie/CookieTest.php
<ide> public function invalidNameProvider()
<ide> * Test invalid cookie name
<ide> *
<ide> * @dataProvider invalidNameProvider
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage contains invalid characters.
<ide> */
<ide> public function testValidateNameInvalidChars($name)
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('contains invalid characters.');
<ide> new Cookie($name, 'value');
<ide> }
<ide>
<ide> /**
<ide> * Test empty cookie name
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The cookie name cannot be empty.
<ide> * @return void
<ide> */
<ide> public function testValidateNameEmptyName()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The cookie name cannot be empty.');
<ide> new Cookie('', '');
<ide> }
<ide>
<ide> public function testGetStringValue()
<ide> * Test setting domain in cookies
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The provided arg must be of type `string` but `integer` given
<ide> */
<ide> public function testWithDomainInvalidConstructor()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The provided arg must be of type `string` but `integer` given');
<ide> new Cookie('cakephp', 'rocks', null, '', 1234);
<ide> }
<ide>
<ide> /**
<ide> * Test setting domain in cookies
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The provided arg must be of type `string` but `array` given
<ide> */
<ide> public function testWithDomainInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The provided arg must be of type `string` but `array` given');
<ide> $cookie = new Cookie('cakephp', 'rocks');
<ide> $cookie->withDomain(['oops']);
<ide> }
<ide> public function testWithDomain()
<ide> * Test setting path in cookies
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The provided arg must be of type `string` but `array` given
<ide> */
<ide> public function testWithPathInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The provided arg must be of type `string` but `array` given');
<ide> $cookie = new Cookie('cakephp', 'rocks');
<ide> $cookie->withPath(['oops']);
<ide> }
<ide> public function testWithPathInvalid()
<ide> * Test setting path in cookies
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The provided arg must be of type `string` but `integer` given
<ide> */
<ide> public function testWithPathInvalidConstructor()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The provided arg must be of type `string` but `integer` given');
<ide> new Cookie('cakephp', 'rocks', null, 123);
<ide> }
<ide>
<ide> public function testWithPath()
<ide> * Test setting httponly in cookies
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The provided arg must be of type `bool` but `string` given
<ide> */
<ide> public function testWithHttpOnlyInvalidConstructor()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The provided arg must be of type `bool` but `string` given');
<ide> new Cookie('cakephp', 'cakephp-rocks', null, '', '', false, 'invalid');
<ide> }
<ide>
<ide> /**
<ide> * Test setting httponly in cookies
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The provided arg must be of type `bool` but `string` given
<ide> */
<ide> public function testWithHttpOnlyInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The provided arg must be of type `bool` but `string` given');
<ide> $cookie = new Cookie('cakephp', 'cakephp-rocks');
<ide> $cookie->withHttpOnly('no');
<ide> }
<ide> public function testWithHttpOnly()
<ide> * Test setting secure in cookies
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The provided arg must be of type `bool` but `string` given
<ide> */
<ide> public function testWithSecureInvalidConstructor()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The provided arg must be of type `bool` but `string` given');
<ide> new Cookie('cakephp', 'cakephp-rocks', null, '', '', 'invalid');
<ide> }
<ide>
<ide> /**
<ide> * Test setting secure in cookies
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The provided arg must be of type `bool` but `string` given
<ide> */
<ide> public function testWithSecureInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The provided arg must be of type `bool` but `string` given');
<ide> $cookie = new Cookie('cakephp', 'cakephp-rocks');
<ide> $cookie->withSecure('no');
<ide> }
<ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php
<ide> public function testValidTokenInHeader($method)
<ide> * Test that the X-CSRF-Token works with the various http methods.
<ide> *
<ide> * @dataProvider httpMethodProvider
<del> * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
<ide> * @return void
<ide> */
<ide> public function testInvalidTokenInHeader($method)
<ide> {
<add> $this->expectException(\Cake\Network\Exception\InvalidCsrfTokenException::class);
<ide> $request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method,
<ide> public function testValidTokenRequestData($method)
<ide> * Test that request data works with the various http methods.
<ide> *
<ide> * @dataProvider httpMethodProvider
<del> * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
<ide> * @return void
<ide> */
<ide> public function testInvalidTokenRequestData($method)
<ide> {
<add> $this->expectException(\Cake\Network\Exception\InvalidCsrfTokenException::class);
<ide> $request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method,
<ide> public function testInvalidTokenRequestData($method)
<ide> /**
<ide> * Test that missing post field fails
<ide> *
<del> * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
<ide> * @return void
<ide> */
<ide> public function testInvalidTokenRequestDataMissing()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\InvalidCsrfTokenException::class);
<ide> $request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => 'POST',
<ide> public function testInvalidTokenRequestDataMissing()
<ide> * Test that missing header and cookie fails
<ide> *
<ide> * @dataProvider httpMethodProvider
<del> * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
<ide> * @return void
<ide> */
<ide> public function testInvalidTokenMissingCookie($method)
<ide> {
<add> $this->expectException(\Cake\Network\Exception\InvalidCsrfTokenException::class);
<ide> $request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method
<ide><path>tests/TestCase/Http/Middleware/SecurityHeadersMiddlewareTest.php
<ide> public function testAddingSecurityHeaders()
<ide> /**
<ide> * Testing that the URL is required when option is `allow-from`
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The 2nd arg $url can not be empty when `allow-from` is used
<ide> * @return void
<ide> */
<ide> public function testInvalidArgumentExceptionForsetXFrameOptionsUrl()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The 2nd arg $url can not be empty when `allow-from` is used');
<ide> $middleware = new SecurityHeadersMiddleware();
<ide> $middleware->setXFrameOptions('allow-from');
<ide> }
<ide> public function testInvalidArgumentExceptionForsetXFrameOptionsUrl()
<ide> * Testing the protected checkValues() method that is used by most of the
<ide> * methods in the test to avoid passing an invalid argument.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid arg `INVALID-VALUE!`, use one of these: all, none, master-only, by-content-type, by-ftp-filename
<ide> * @return void
<ide> */
<ide> public function testCheckValues()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid arg `INVALID-VALUE!`, use one of these: all, none, master-only, by-content-type, by-ftp-filename');
<ide> $middleware = new SecurityHeadersMiddleware();
<ide> $middleware->setCrossDomainPolicy('INVALID-VALUE!');
<ide> }
<ide><path>tests/TestCase/Http/MiddlewareQueueTest.php
<ide> public function testInsertBefore()
<ide> /**
<ide> * Test insertBefore an invalid classname
<ide> *
<del> * @expectedException \LogicException
<del> * @expectedExceptionMessage No middleware matching 'InvalidClassName' could be found.
<ide> * @return void
<ide> */
<ide> public function testInsertBeforeInvalid()
<ide> {
<add> $this->expectException(\LogicException::class);
<add> $this->expectExceptionMessage('No middleware matching \'InvalidClassName\' could be found.');
<ide> $one = function () {
<ide> };
<ide> $two = new SampleMiddleware();
<ide><path>tests/TestCase/Http/ResponseTest.php
<ide> public function testStatusCode()
<ide> /**
<ide> * Test invalid status codes
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testStatusCodeInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $response = new Response();
<ide> $response->statusCode(1001);
<ide> }
<ide> public function withTypeFull()
<ide> /**
<ide> * Test that an invalid type raises an exception
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage "beans" is an invalid content type
<ide> * @return void
<ide> */
<ide> public function testWithTypeInvalidType()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('"beans" is an invalid content type');
<ide> $response = new Response();
<ide> $response->withType('beans');
<ide> }
<ide> public function testCompress()
<ide> /**
<ide> * Tests the httpCodes method
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testHttpCodes()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $response = new Response();
<ide> $result = $response->httpCodes();
<ide> $this->assertCount(65, $result);
<ide> public function corsData()
<ide> /**
<ide> * testFileNotFound
<ide> *
<del> * @expectedException \Cake\Network\Exception\NotFoundException
<ide> * @return void
<ide> */
<ide> public function testFileNotFound()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\NotFoundException::class);
<ide> $response = new Response();
<ide> $response->file('/some/missing/folder/file.jpg');
<ide> }
<ide>
<ide> /**
<ide> * test withFile() not found
<ide> *
<del> * @expectedException \Cake\Network\Exception\NotFoundException
<ide> * @return void
<ide> */
<ide> public function testWithFileNotFound()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\NotFoundException::class);
<ide> $response = new Response();
<ide> $response->withFile('/some/missing/folder/file.jpg');
<ide> }
<ide> public function testWithStringBody()
<ide> * This should produce an "Array to string conversion" error
<ide> * which gets thrown as a \PHPUnit\Framework\Error\Error Exception by PHPUnit.
<ide> *
<del> * @expectedException \PHPUnit\Framework\Error\Error
<del> * @expectedExceptionMessage Array to string conversion
<ide> * @return void
<ide> */
<ide> public function testWithStringBodyArray()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\Error\Error::class);
<add> $this->expectExceptionMessage('Array to string conversion');
<ide> $response = new Response();
<ide> $newResponse = $response->withStringBody(['foo' => 'bar']);
<ide> $body = $newResponse->getBody();
<ide><path>tests/TestCase/Http/RunnerTest.php
<ide> public function testRunSequencing()
<ide> /**
<ide> * Test that exceptions bubble up.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage A bad thing
<ide> */
<ide> public function testRunExceptionInMiddleware()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('A bad thing');
<ide> $this->stack->add($this->ok)->add($this->fail);
<ide> $req = $this->getMockBuilder('Psr\Http\Message\ServerRequestInterface')->getMock();
<ide> $res = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock();
<ide><path>tests/TestCase/Http/ServerRequestTest.php
<ide> public function testGetUploadedFile()
<ide> /**
<ide> * Test replacing files with an invalid file
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Invalid file at 'avatar'
<ide> * @return void
<ide> */
<ide> public function testWithUploadedFilesInvalidFile()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid file at \'avatar\'');
<ide> $request = new ServerRequest();
<ide> $request->withUploadedFiles(['avatar' => 'not a file']);
<ide> }
<ide>
<ide> /**
<ide> * Test replacing files with an invalid file
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Invalid file at 'user.avatar'
<ide> * @return void
<ide> */
<ide> public function testWithUploadedFilesInvalidFileNested()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid file at \'user.avatar\'');
<ide> $request = new ServerRequest();
<ide> $request->withUploadedFiles(['user' => ['avatar' => 'not a file']]);
<ide> }
<ide> public function testWithMethod()
<ide> /**
<ide> * Test withMethod() and invalid data
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Unsupported HTTP method "no good" provided
<ide> * @return void
<ide> */
<ide> public function testWithMethodInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Unsupported HTTP method "no good" provided');
<ide> $request = new ServerRequest([
<ide> 'environment' => ['REQUEST_METHOD' => 'delete']
<ide> ]);
<ide> public function testWithProtocolVersion()
<ide> /**
<ide> * Test withProtocolVersion() and invalid data
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Unsupported protocol version 'no good' provided
<ide> * @return void
<ide> */
<ide> public function testWithProtocolVersionInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Unsupported protocol version \'no good\' provided');
<ide> $request = new ServerRequest();
<ide> $request->withProtocolVersion('no good');
<ide> }
<ide> public function testisAjaxFlashAndFriends()
<ide> /**
<ide> * Test __call exceptions
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> * @return void
<ide> */
<ide> public function testMagicCallExceptionOnUnknownMethod()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> $request = new ServerRequest();
<ide> $request->IamABanana();
<ide> }
<ide> public function testWithoutAttribute()
<ide> * Test that withoutAttribute() cannot remove deprecated public properties.
<ide> *
<ide> * @dataProvider emulatedPropertyProvider
<del> * @expectedException InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testWithoutAttributesDenyEmulatedProperties($prop)
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $request = new ServerRequest([]);
<ide> $request->withoutAttribute($prop);
<ide> }
<ide><path>tests/TestCase/Http/ServerTest.php
<ide> public function testRunWithGlobals()
<ide> /**
<ide> * Test an application failing to build middleware properly
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage The application `middleware` method
<ide> */
<ide> public function testRunWithApplicationNotMakingMiddleware()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('The application `middleware` method');
<ide> $app = new InvalidMiddlewareApplication($this->config);
<ide> $server = new Server($app);
<ide> $server->run();
<ide> public function testRunMultipleMiddlewareSuccess()
<ide> /**
<ide> * Test middleware not creating a response.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Application did not create a response. Got "Not a response" instead.
<ide> */
<ide> public function testRunMiddlewareNoResponse()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Application did not create a response. Got "Not a response" instead.');
<ide> $app = new BadResponseApplication($this->config);
<ide> $server = new Server($app);
<ide> $server->run();
<ide><path>tests/TestCase/I18n/Formatter/IcuFormatterTest.php
<ide> public function testNativePluralSelection()
<ide> * Tests that passing a message in the wrong format will throw an exception
<ide> *
<ide> * @return void
<del> * @expectedException \Exception
<del> * @expectedExceptionMessage msgfmt_create: message formatter
<ide> */
<ide> public function testBadMessageFormat()
<ide> {
<add> $this->expectException(\Exception::class);
<add> $this->expectExceptionMessage('msgfmt_create: message formatter');
<ide> $this->skipIf(version_compare(PHP_VERSION, '7', '>='));
<ide>
<ide> $formatter = new IcuFormatter();
<ide> public function testBadMessageFormat()
<ide> * Tests that passing a message in the wrong format will throw an exception
<ide> *
<ide> * @return void
<del> * @expectedException \Exception
<del> * @expectedExceptionMessage Constructor failed
<ide> */
<ide> public function testBadMessageFormatPHP7()
<ide> {
<add> $this->expectException(\Exception::class);
<add> $this->expectExceptionMessage('Constructor failed');
<ide> $this->skipIf(version_compare(PHP_VERSION, '7', '<'));
<ide>
<ide> $formatter = new IcuFormatter();
<ide><path>tests/TestCase/I18n/TranslatorFactoryTest.php
<ide> class TranslatorFactoryTest extends TestCase
<ide> /**
<ide> * Test that errors are emitted when stale cache files are found.
<ide> *
<del> * @expectedException RuntimeException
<del> * @expectedExceptionMessage Translator fallback class
<ide> */
<ide> public function testNewInstanceErrorOnFallback()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Translator fallback class');
<ide> $formatter = $this->getMockBuilder('Aura\Intl\FormatterInterface')->getMock();
<ide> $package = $this->getMockBuilder(Package::class)->getMock();
<ide> $fallback = new AuraTranslator('en_CA', $package, $formatter, null);
<ide><path>tests/TestCase/Log/LogTest.php
<ide> public function testImportingLoggers()
<ide> /**
<ide> * test all the errors from failed logger imports
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testImportingLoggerFailure()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> Log::config('fail', []);
<ide> Log::engine('fail');
<ide> }
<ide> public function testValidKeyName()
<ide> /**
<ide> * test that loggers have to implement the correct interface.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testNotImplementingInterface()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> Log::config('fail', ['engine' => '\stdClass']);
<ide> Log::engine('fail');
<ide> }
<ide> public function testDrop()
<ide> /**
<ide> * test invalid level
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testInvalidLevel()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Log::config('myengine', ['engine' => 'File']);
<ide> Log::write('invalid', 'This will not be logged');
<ide> }
<ide> public function testSetConfigVariants($settings)
<ide> * Test that config() throws an exception when adding an
<ide> * adapter with the wrong type.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testConfigInjectErrorOnWrongType()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> Log::config('test', new \StdClass);
<ide> Log::info('testing');
<ide> }
<ide> public function testConfigInjectErrorOnWrongType()
<ide> * Test that setConfig() throws an exception when adding an
<ide> * adapter with the wrong type.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testSetConfigInjectErrorOnWrongType()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> Log::setConfig('test', new \StdClass);
<ide> Log::info('testing');
<ide> }
<ide> public function testConfigRead()
<ide> /**
<ide> * Ensure you cannot reconfigure a log adapter.
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> * @return void
<ide> */
<ide> public function testConfigErrorOnReconfigure()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> Log::config('tests', ['engine' => 'File', 'path' => TMP]);
<ide> Log::config('tests', ['engine' => 'Apc']);
<ide> }
<ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public static function invalidEmails()
<ide> * testBuildInvalidData
<ide> *
<ide> * @dataProvider invalidEmails
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testInvalidEmail($value)
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->Email->to($value);
<ide> }
<ide>
<ide> /**
<ide> * testBuildInvalidData
<ide> *
<ide> * @dataProvider invalidEmails
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testInvalidEmailAdd($value)
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->Email->addTo($value);
<ide> }
<ide>
<ide> public function testCustomEmailValidation()
<ide> *
<ide> * @return void
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Transport class "TestFalse" not found.
<ide> */
<ide> public function testClassNameException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Transport class "TestFalse" not found.');
<ide> $email = new Email();
<ide> $email->transport('badClassName');
<ide> }
<ide> public function testClassNameException()
<ide> *
<ide> * @return void
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid email set for "to". You passed "fail.@example.com".
<ide> */
<ide> public function testUnsetEmailPattern()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid email set for "to". You passed "fail.@example.com".');
<ide> $email = new Email();
<ide> $this->assertSame(Email::EMAIL_PATTERN, $email->emailPattern());
<ide>
<ide> public function testUnsetEmailPattern()
<ide> *
<ide> * @return void
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The email set for "to" is empty.
<ide> */
<ide> public function testEmptyTo()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The email set for "to" is empty.');
<ide> $email = new Email();
<ide> $email->setTo('');
<ide> }
<ide> public function testPriority()
<ide> * testMessageIdInvalid method
<ide> *
<ide> * @return void
<del> * @expectedException \InvalidArgumentException
<ide> */
<ide> public function testMessageIdInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->Email->messageId('my-email@localhost');
<ide> }
<ide>
<ide> public function testTransport()
<ide> /**
<ide> * Test that using unknown transports fails.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Transport config "Invalid" is missing.
<ide> */
<ide> public function testTransportInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Transport config "Invalid" is missing.');
<ide> $this->Email->transport('Invalid');
<ide> }
<ide>
<ide> /**
<ide> * Test that using classes with no send method fails.
<ide> *
<del> * @expectedException \LogicException
<ide> */
<ide> public function testTransportInstanceInvalid()
<ide> {
<add> $this->expectException(\LogicException::class);
<ide> $this->Email->transport(new \StdClass());
<ide> }
<ide>
<ide> /**
<ide> * Test that using unknown transports fails.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The value passed for the "$name" argument must be either a string, or an object, integer given.
<ide> */
<ide> public function testTransportTypeInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The value passed for the "$name" argument must be either a string, or an object, integer given.');
<ide> $this->Email->transport(123);
<ide> }
<ide>
<ide> /**
<ide> * Test that using misconfigured transports fails.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Transport config "debug" is invalid, the required `className` option is missing
<ide> */
<ide> public function testTransportMissingClassName()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Transport config "debug" is invalid, the required `className` option is missing');
<ide> Email::dropTransport('debug');
<ide> Email::configTransport('debug', []);
<ide>
<ide> public function testConfigTransportMultiple()
<ide> /**
<ide> * Test that exceptions are raised when duplicate transports are configured.
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> */
<ide> public function testConfigTransportErrorOnDuplicate()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> Email::dropTransport('debug');
<ide> $settings = [
<ide> 'className' => 'Debug',
<ide> public function testConfig()
<ide> /**
<ide> * Test that exceptions are raised on duplicate config set.
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> * @return void
<ide> */
<ide> public function testConfigErrorOnDuplicate()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> $settings = [
<ide> 'to' => 'mark@example.com',
<ide> 'from' => 'noreply@example.com',
<ide> public function testDefaultProfile()
<ide> /**
<ide> * Test that using an invalid profile fails.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Unknown email configuration "derp".
<ide> */
<ide> public function testProfileInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Unknown email configuration "derp".');
<ide> $email = new Email();
<ide> $email->profile('derp');
<ide> }
<ide> public function testSendWithContent()
<ide> /**
<ide> * testSendWithoutFrom method
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> * @return void
<ide> */
<ide> public function testSendWithoutFrom()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> $this->Email->transport('debug');
<ide> $this->Email->to('cake@cakephp.org');
<ide> $this->Email->subject('My title');
<ide> public function testSendWithoutFrom()
<ide> /**
<ide> * testSendWithoutTo method
<ide> *
<del> * @expectedException \BadMethodCallException
<ide> * @return void
<ide> */
<ide> public function testSendWithoutTo()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<ide> $this->Email->transport('debug');
<ide> $this->Email->from('cake@cakephp.org');
<ide> $this->Email->subject('My title');
<ide> public function testSendWithoutTo()
<ide> /**
<ide> * test send without a transport method
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Cannot send email, transport was not defined.
<ide> * @return void
<ide> */
<ide> public function testSendWithoutTransport()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Cannot send email, transport was not defined.');
<ide> $this->Email->to('cake@cakephp.org');
<ide> $this->Email->from('cake@cakephp.org');
<ide> $this->Email->subject('My title');
<ide><path>tests/TestCase/Mailer/MailerAwareTraitTest.php
<ide> public function testGetMailer()
<ide> /**
<ide> * Test exception thrown by getMailer.
<ide> *
<del> * @expectedException \Cake\Mailer\Exception\MissingMailerException
<del> * @expectedExceptionMessage Mailer class "Test" could not be found.
<ide> */
<ide> public function testGetMailerThrowsException()
<ide> {
<add> $this->expectException(\Cake\Mailer\Exception\MissingMailerException::class);
<add> $this->expectExceptionMessage('Mailer class "Test" could not be found.');
<ide> $stub = new Stub();
<ide> $stub->getMailer('Test');
<ide> }
<ide><path>tests/TestCase/Mailer/MailerTest.php
<ide> public function testDefaultProfileRestoration()
<ide> }
<ide>
<ide> /**
<del> * @expectedException \Cake\Mailer\Exception\MissingActionException
<del> * @expectedExceptionMessage Mail TestMailer::test() could not be found, or is not accessible.
<ide> */
<ide> public function testMissingActionThrowsException()
<ide> {
<add> $this->expectException(\Cake\Mailer\Exception\MissingActionException::class);
<add> $this->expectExceptionMessage('Mail TestMailer::test() could not be found, or is not accessible.');
<ide> (new TestMailer())->send('test');
<ide> }
<ide> }
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php
<ide> public function testConnectEhloTls()
<ide> /**
<ide> * testConnectEhloTlsOnNonTlsServer method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.
<ide> * @return void
<ide> */
<ide> public function testConnectEhloTlsOnNonTlsServer()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<add> $this->expectExceptionMessage('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.');
<ide> $this->SmtpTransport->config(['tls' => true]);
<ide> $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true));
<ide> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n"));
<ide> public function testConnectEhloTlsOnNonTlsServer()
<ide> /**
<ide> * testConnectEhloNoTlsOnRequiredTlsServer method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP authentication method not allowed, check if SMTP server requires TLS.
<ide> * @return void
<ide> */
<ide> public function testConnectEhloNoTlsOnRequiredTlsServer()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<add> $this->expectExceptionMessage('SMTP authentication method not allowed, check if SMTP server requires TLS.');
<ide> $this->SmtpTransport->config(['tls' => false, 'username' => 'user', 'password' => 'pass']);
<ide> $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true));
<ide> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n"));
<ide> public function testConnectHelo()
<ide> /**
<ide> * testConnectFail method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP server did not accept the connection.
<ide> * @return void
<ide> */
<ide> public function testConnectFail()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<add> $this->expectExceptionMessage('SMTP server did not accept the connection.');
<ide> $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true));
<ide> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n"));
<ide> $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n");
<ide> public function testAuth()
<ide> /**
<ide> * testAuthNotRecognized method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage AUTH command not recognized or not implemented, SMTP server may not require authentication.
<ide> * @return void
<ide> */
<ide> public function testAuthNotRecognized()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<add> $this->expectExceptionMessage('AUTH command not recognized or not implemented, SMTP server may not require authentication.');
<ide> $this->socket->expects($this->at(0))->method('write')->with("AUTH LOGIN\r\n");
<ide> $this->socket->expects($this->at(1))->method('read')
<ide> ->will($this->returnValue("500 5.3.3 Unrecognized command\r\n"));
<ide> public function testAuthNotRecognized()
<ide> /**
<ide> * testAuthNotImplemented method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage AUTH command not recognized or not implemented, SMTP server may not require authentication.
<ide> * @return void
<ide> */
<ide> public function testAuthNotImplemented()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<add> $this->expectExceptionMessage('AUTH command not recognized or not implemented, SMTP server may not require authentication.');
<ide> $this->socket->expects($this->at(0))->method('write')->with("AUTH LOGIN\r\n");
<ide> $this->socket->expects($this->at(1))->method('read')
<ide> ->will($this->returnValue("502 5.3.3 Command not implemented\r\n"));
<ide> public function testAuthNotImplemented()
<ide> /**
<ide> * testAuthBadSequence method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP Error: 503 5.5.1 Already authenticated
<ide> * @return void
<ide> */
<ide> public function testAuthBadSequence()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<add> $this->expectExceptionMessage('SMTP Error: 503 5.5.1 Already authenticated');
<ide> $this->socket->expects($this->at(0))->method('write')->with("AUTH LOGIN\r\n");
<ide> $this->socket->expects($this->at(1))
<ide> ->method('read')->will($this->returnValue("503 5.5.1 Already authenticated\r\n"));
<ide> public function testAuthBadSequence()
<ide> /**
<ide> * testAuthBadUsername method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP server did not accept the username.
<ide> * @return void
<ide> */
<ide> public function testAuthBadUsername()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<add> $this->expectExceptionMessage('SMTP server did not accept the username.');
<ide> $this->socket->expects($this->at(0))->method('write')->with("AUTH LOGIN\r\n");
<ide> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("334 Login\r\n"));
<ide> $this->socket->expects($this->at(2))->method('write')->with("bWFyaw==\r\n");
<ide> public function testAuthBadUsername()
<ide> /**
<ide> * testAuthBadPassword method
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<del> * @expectedExceptionMessage SMTP server did not accept the password.
<ide> * @return void
<ide> */
<ide> public function testAuthBadPassword()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<add> $this->expectExceptionMessage('SMTP server did not accept the password.');
<ide> $this->socket->expects($this->at(0))->method('write')->with("AUTH LOGIN\r\n");
<ide> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("334 Login\r\n"));
<ide> $this->socket->expects($this->at(2))->method('write')->with("bWFyaw==\r\n");
<ide><path>tests/TestCase/Network/Session/CacheSessionTest.php
<ide> public function testDestroy()
<ide> /**
<ide> * Tests that a cache config is required
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The cache configuration name to use is required
<ide> * @return void
<ide> */
<ide> public function testMissingConfig()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The cache configuration name to use is required');
<ide> new CacheSession(['foo' => 'bar']);
<ide> }
<ide> }
<ide><path>tests/TestCase/Network/SessionTest.php
<ide> public function testEngineWithPreMadeInstance()
<ide> /**
<ide> * Tests instantiating a missing engine
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The class "Derp" does not exist and cannot be used as a session engine
<ide> * @return void
<ide> */
<ide> public function testBadEngine()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The class "Derp" does not exist and cannot be used as a session engine');
<ide> $session = new Session();
<ide> $session->engine('Derp');
<ide> }
<ide><path>tests/TestCase/Network/SocketTest.php
<ide> public static function invalidConnections()
<ide> * testInvalidConnection method
<ide> *
<ide> * @dataProvider invalidConnections
<del> * @expectedException \Cake\Network\Exception\SocketException
<ide> * @return void
<ide> */
<ide> public function testInvalidConnection($data)
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<ide> $this->Socket->config($data);
<ide> $this->Socket->connect();
<ide> }
<ide> public function testReset()
<ide> /**
<ide> * testEncrypt
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<ide> * @return void
<ide> */
<ide> public function testEnableCryptoSocketExceptionNoSsl()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<ide> $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
<ide> $configNoSslOrTls = ['host' => 'localhost', 'port' => 80, 'timeout' => 0.1];
<ide>
<ide> public function testEnableCryptoSocketExceptionNoSsl()
<ide> /**
<ide> * testEnableCryptoSocketExceptionNoTls
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<ide> * @return void
<ide> */
<ide> public function testEnableCryptoSocketExceptionNoTls()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<ide> $configNoSslOrTls = ['host' => 'localhost', 'port' => 80, 'timeout' => 0.1];
<ide>
<ide> // testing exception on no ssl socket server for ssl and tls methods
<ide> protected function _connectSocketToSslTls()
<ide> /**
<ide> * testEnableCryptoBadMode
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testEnableCryptoBadMode()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> // testing wrong encryption mode
<ide> $this->_connectSocketToSslTls();
<ide> $this->Socket->enableCrypto('doesntExistMode', 'server');
<ide> public function testEnableCrypto()
<ide> /**
<ide> * testEnableCryptoExceptionEnableTwice
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<ide> * @return void
<ide> */
<ide> public function testEnableCryptoExceptionEnableTwice()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<ide> // testing on tls server
<ide> $this->_connectSocketToSslTls();
<ide> $this->Socket->enableCrypto('tls', 'client');
<ide> public function testEnableCryptoExceptionEnableTwice()
<ide> /**
<ide> * testEnableCryptoExceptionDisableTwice
<ide> *
<del> * @expectedException \Cake\Network\Exception\SocketException
<ide> * @return void
<ide> */
<ide> public function testEnableCryptoExceptionDisableTwice()
<ide> {
<add> $this->expectException(\Cake\Network\Exception\SocketException::class);
<ide> $this->_connectSocketToSslTls();
<ide> $this->Socket->enableCrypto('tls', 'client', false);
<ide> }
<ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide> public function testRequiresKeys()
<ide> /**
<ide> * Tests that BelongsToMany can't use the join strategy
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid strategy "join" was provided
<ide> * @return void
<ide> */
<ide> public function testStrategyFailure()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid strategy "join" was provided');
<ide> $assoc = new BelongsToMany('Test');
<ide> $assoc->strategy(BelongsToMany::STRATEGY_JOIN);
<ide> }
<ide> public function testSaveStrategyInOptions()
<ide> /**
<ide> * Tests that passing an invalid strategy will throw an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid save strategy "depsert"
<ide> * @return void
<ide> */
<ide> public function testSaveStrategyInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid save strategy "depsert"');
<ide> $assoc = new BelongsToMany('Test', ['saveStrategy' => 'depsert']);
<ide> }
<ide>
<ide> public function testCascadeDeleteWithCallbacks()
<ide> /**
<ide> * Test linking entities having a non persisted source entity
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Source entity needs to be persisted before links can be created or removed
<ide> * @return void
<ide> */
<ide> public function testLinkWithNotPersistedSource()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Source entity needs to be persisted before links can be created or removed');
<ide> $config = [
<ide> 'sourceTable' => $this->article,
<ide> 'targetTable' => $this->tag,
<ide> public function testLinkWithNotPersistedSource()
<ide> /**
<ide> * Test liking entities having a non persisted target entity
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Cannot link entities that have not been persisted yet
<ide> * @return void
<ide> */
<ide> public function testLinkWithNotPersistedTarget()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot link entities that have not been persisted yet');
<ide> $config = [
<ide> 'sourceTable' => $this->article,
<ide> 'targetTable' => $this->tag,
<ide> public function testLinkSuccessWithMocks()
<ide> /**
<ide> * Test liking entities having a non persisted source entity
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Source entity needs to be persisted before links can be created or removed
<ide> * @return void
<ide> */
<ide> public function testUnlinkWithNotPersistedSource()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Source entity needs to be persisted before links can be created or removed');
<ide> $config = [
<ide> 'sourceTable' => $this->article,
<ide> 'targetTable' => $this->tag,
<ide> public function testUnlinkWithNotPersistedSource()
<ide> /**
<ide> * Test liking entities having a non persisted target entity
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Cannot link entities that have not been persisted
<ide> * @return void
<ide> */
<ide> public function testUnlinkWithNotPersistedTarget()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot link entities that have not been persisted');
<ide> $config = [
<ide> 'sourceTable' => $this->article,
<ide> 'targetTable' => $this->tag,
<ide> public function testUnlinkWithoutPropertyClean()
<ide> * Tests that replaceLink requires the sourceEntity to have primaryKey values
<ide> * for the source entity
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Could not find primary key value for source entity
<ide> * @return void
<ide> */
<ide> public function testReplaceWithMissingPrimaryKey()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Could not find primary key value for source entity');
<ide> $config = [
<ide> 'sourceTable' => $this->article,
<ide> 'targetTable' => $this->tag,
<ide> public function emptyProvider()
<ide> /**
<ide> * Test that saveAssociated() fails on non-empty, non-iterable value
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Could not save tags, it cannot be traversed
<ide> * @return void
<ide> */
<ide> public function testSaveAssociatedNotEmptyNotIterable()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Could not save tags, it cannot be traversed');
<ide> $articles = TableRegistry::get('Articles');
<ide> $assoc = $articles->belongsToMany('Tags', [
<ide> 'saveStrategy' => BelongsToMany::SAVE_APPEND,
<ide> public function testGeneratedAssociations()
<ide> /**
<ide> * Tests that eager loading requires association keys
<ide> *
<del> * @expectedException RuntimeException
<del> * @expectedExceptionMessage The "tags" table does not define a primary key
<ide> * @return void
<ide> */
<ide> public function testEagerLoadingRequiresPrimaryKey()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('The "tags" table does not define a primary key');
<ide> $table = TableRegistry::get('Articles');
<ide> $tags = TableRegistry::get('Tags');
<ide> $tags->schema()->dropConstraint('primary');
<ide><path>tests/TestCase/ORM/Association/BelongsToTest.php
<ide> public function testAttachToMultiPrimaryKey()
<ide> * Tests that using belongsto with a table having a multi column primary
<ide> * key will work if the foreign key is passed
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot match provided foreignKey for "Companies", got "(company_id)" but expected foreign key for "(id, tenant_id)"
<ide> * @return void
<ide> */
<ide> public function testAttachToMultiPrimaryKeyMismatch()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot match provided foreignKey for "Companies", got "(company_id)" but expected foreign key for "(id, tenant_id)"');
<ide> $this->company->primaryKey(['id', 'tenant_id']);
<ide> $query = $this->client->query();
<ide> $config = [
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php
<ide> public function testRequiresKeys()
<ide> /**
<ide> * Tests that HasMany can't use the join strategy
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid strategy "join" was provided
<ide> * @return void
<ide> */
<ide> public function testStrategyFailure()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid strategy "join" was provided');
<ide> $assoc = new HasMany('Test');
<ide> $assoc->strategy(HasMany::STRATEGY_JOIN);
<ide> }
<ide> public function testEagerLoaderWithOverrides()
<ide> * Test that failing to add the foreignKey to the list of fields will throw an
<ide> * exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage You are required to select the "Articles.author_id"
<ide> * @return void
<ide> */
<ide> public function testEagerLoaderFieldsException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('You are required to select the "Articles.author_id"');
<ide> $config = [
<ide> 'sourceTable' => $this->author,
<ide> 'targetTable' => $this->article,
<ide> public function testLinkUsesSingleTransaction()
<ide> /**
<ide> * Test that saveAssociated() fails on non-empty, non-iterable value
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Could not save comments, it cannot be traversed
<ide> * @return void
<ide> */
<ide> public function testSaveAssociatedNotEmptyNotIterable()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Could not save comments, it cannot be traversed');
<ide> $articles = TableRegistry::get('Articles');
<ide> $association = $articles->hasMany('Comments', [
<ide> 'saveStrategy' => HasMany::SAVE_APPEND
<ide><path>tests/TestCase/ORM/Association/HasOneTest.php
<ide> public function testAttachToMultiPrimaryKey()
<ide> * Tests that using hasOne with a table having a multi column primary
<ide> * key will work if the foreign key is passed
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot match provided foreignKey for "Profiles", got "(user_id)" but expected foreign key for "(id, site_id)"
<ide> * @return void
<ide> */
<ide> public function testAttachToMultiPrimaryKeyMismatch()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot match provided foreignKey for "Profiles", got "(user_id)" but expected foreign key for "(id, site_id)"');
<ide> $query = $this->getMockBuilder('\Cake\ORM\Query')
<ide> ->setMethods(['join', 'select'])
<ide> ->setConstructorArgs([null, null])
<ide><path>tests/TestCase/ORM/AssociationCollectionTest.php
<ide> public function testSaveChildrenFiltered()
<ide> /**
<ide> * Test exceptional case.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Cannot save Profiles, it is not associated to Users
<ide> */
<ide> public function testErrorOnUnknownAlias()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot save Profiles, it is not associated to Users');
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')
<ide> ->setMethods(['save'])
<ide> ->setConstructorArgs([['alias' => 'Users']])
<ide><path>tests/TestCase/ORM/AssociationProxyTest.php
<ide> public function testAssociationAsProperty()
<ide> /**
<ide> * Tests that getting a bad property throws exception
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Table "Cake\ORM\Table" is not associated with "posts"
<ide> * @return void
<ide> */
<ide> public function testGetBadAssociation()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Table "Cake\ORM\Table" is not associated with "posts"');
<ide> $articles = TableRegistry::get('articles');
<ide> $articles->posts;
<ide> }
<ide><path>tests/TestCase/ORM/AssociationTest.php
<ide> public function testSetNameBeforeTarget()
<ide> /**
<ide> * Tests that setName() fails after the target table is resolved.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Association name does not match target table alias.
<ide> * @return void
<ide> */
<ide> public function testSetNameAfterTarger()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Association name does not match target table alias.');
<ide> $this->association->getTarget();
<ide> $this->association->setName('Bar');
<ide> }
<ide> public function testClassNameUnnormalized()
<ide> * from a registry.
<ide> *
<ide> * @return void
<del> * @expectedException \RuntimeException
<ide> */
<ide> public function testInvalidTableFetchedFromRegistry()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> TableRegistry::get('Test');
<ide>
<ide> $config = [
<ide> public function testProperty()
<ide> * Test that warning is shown if property name clashes with table field.
<ide> *
<ide> * @return void
<del> * @expectedException \PHPUnit\Framework\Error\Warning
<del> * @expectedExceptionMessageRegExp /^Association property name "foo" clashes with field of same name of table "test"/
<ide> */
<ide> public function testPropertyNameClash()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\Error\Warning::class);
<add> $this->expectExceptionMessageRegExp('/^Association property name "foo" clashes with field of same name of table "test"/');
<ide> $this->source->schema(['foo' => ['type' => 'string']]);
<ide> $this->assertEquals('foo', $this->association->property());
<ide> }
<ide> public function testStrategy()
<ide> /**
<ide> * Tests that providing an invalid strategy throws an exception
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testInvalidStrategy()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->association->strategy('anotherThing');
<ide> $this->assertEquals('subquery', $this->association->strategy());
<ide> }
<ide><path>tests/TestCase/ORM/Behavior/TimestampBehaviorTest.php
<ide> public function testModifiedPresent()
<ide> /**
<ide> * testInvalidEventConfig
<ide> *
<del> * @expectedException \UnexpectedValueException
<del> * @expectedExceptionMessage When should be one of "always", "new" or "existing". The passed value "fat fingers" is invalid
<ide> * @return void
<ide> * @triggers Model.beforeSave
<ide> */
<ide> public function testInvalidEventConfig()
<ide> {
<add> $this->expectException(\UnexpectedValueException::class);
<add> $this->expectExceptionMessage('When should be one of "always", "new" or "existing". The passed value "fat fingers" is invalid');
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')->getMock();
<ide> $settings = ['events' => ['Model.beforeSave' => ['created' => 'fat fingers']]];
<ide> $this->Behavior = new TimestampBehavior($table, $settings);
<ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php
<ide> public function testFindChildren()
<ide> /**
<ide> * Tests that find('children') will throw an exception if the node was not found
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\RecordNotFoundException
<ide> * @return void
<ide> */
<ide> public function testFindChildrenException()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\RecordNotFoundException::class);
<ide> $table = TableRegistry::get('MenuLinkTrees');
<ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]);
<ide> $query = $table->find('children', ['for' => 500]);
<ide> public function testAddRoot()
<ide> /**
<ide> * Tests making a node its own parent as an existing entity
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot set a node's parent as itself
<ide> * @return void
<ide> */
<ide> public function testReParentSelf()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot set a node\'s parent as itself');
<ide> $entity = $this->table->get(1);
<ide> $entity->parent_id = $entity->id;
<ide> $this->table->save($entity);
<ide> public function testReParentSelf()
<ide> /**
<ide> * Tests making a node its own parent as a new entity.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot set a node's parent as itself
<ide> * @return void
<ide> */
<ide> public function testReParentSelfNewEntity()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot set a node\'s parent as itself');
<ide> $entity = $this->table->newEntity(['name' => 'root']);
<ide> $entity->id = 1;
<ide> $entity->parent_id = $entity->id;
<ide> public function testRootingNoTreeColumns()
<ide> /**
<ide> * Tests that trying to create a cycle throws an exception
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot use node "5" as parent for entity "2"
<ide> * @return void
<ide> */
<ide> public function testReparentCycle()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot use node "5" as parent for entity "2"');
<ide> $table = $this->table;
<ide> $entity = $table->get(2);
<ide> $entity->parent_id = 5;
<ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php
<ide> public function testLoadPlugin()
<ide> /**
<ide> * Test load() on undefined class
<ide> *
<del> * @expectedException \Cake\ORM\Exception\MissingBehaviorException
<ide> * @return void
<ide> */
<ide> public function testLoadMissingClass()
<ide> {
<add> $this->expectException(\Cake\ORM\Exception\MissingBehaviorException::class);
<ide> $this->Behaviors->load('DoesNotExist');
<ide> }
<ide>
<ide> /**
<ide> * Test load() duplicate method error
<ide> *
<del> * @expectedException \LogicException
<del> * @expectedExceptionMessage TestApp\Model\Behavior\DuplicateBehavior contains duplicate method "slugify"
<ide> * @return void
<ide> */
<ide> public function testLoadDuplicateMethodError()
<ide> {
<add> $this->expectException(\LogicException::class);
<add> $this->expectExceptionMessage('TestApp\Model\Behavior\DuplicateBehavior contains duplicate method "slugify"');
<ide> $this->Behaviors->load('Sluggable');
<ide> $this->Behaviors->load('Duplicate');
<ide> }
<ide> public function testLoadDuplicateMethodAliasing()
<ide> /**
<ide> * Test load() duplicate finder error
<ide> *
<del> * @expectedException \LogicException
<del> * @expectedExceptionMessage TestApp\Model\Behavior\DuplicateBehavior contains duplicate finder "children"
<ide> * @return void
<ide> */
<ide> public function testLoadDuplicateFinderError()
<ide> {
<add> $this->expectException(\LogicException::class);
<add> $this->expectExceptionMessage('TestApp\Model\Behavior\DuplicateBehavior contains duplicate finder "children"');
<ide> $this->Behaviors->load('Tree');
<ide> $this->Behaviors->load('Duplicate');
<ide> }
<ide> public function testCall()
<ide> /**
<ide> * Test errors on unknown methods.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Cannot call "nope"
<ide> */
<ide> public function testCallError()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Cannot call "nope"');
<ide> $this->Behaviors->load('Sluggable');
<ide> $this->Behaviors->call('nope');
<ide> }
<ide> public function testCallFinder()
<ide> /**
<ide> * Test errors on unknown methods.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Cannot call finder "nope"
<ide> */
<ide> public function testCallFinderError()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Cannot call finder "nope"');
<ide> $this->Behaviors->load('Sluggable');
<ide> $this->Behaviors->callFinder('nope');
<ide> }
<ide>
<ide> /**
<ide> * Test errors on unloaded behavior methods.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Cannot call "slugify" it does not belong to any attached behavior.
<ide> */
<ide> public function testUnloadBehaviorThenCall()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Cannot call "slugify" it does not belong to any attached behavior.');
<ide> $this->Behaviors->load('Sluggable');
<ide> $this->Behaviors->unload('Sluggable');
<ide>
<ide> public function testUnloadBehaviorThenCall()
<ide> /**
<ide> * Test errors on unloaded behavior finders.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Cannot call finder "noslug" it does not belong to any attached behavior.
<ide> */
<ide> public function testUnloadBehaviorThenCallFinder()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Cannot call finder "noslug" it does not belong to any attached behavior.');
<ide> $this->Behaviors->load('Sluggable');
<ide> $this->Behaviors->unload('Sluggable');
<ide>
<ide> public function testUnload()
<ide> /**
<ide> * Test that unloading a none existing behavior triggers an error.
<ide> *
<del> * @expectedException \Cake\ORM\Exception\MissingBehaviorException
<del> * @expectedExceptionMessage Behavior class FooBehavior could not be found.
<ide> * @return void
<ide> */
<ide> public function testUnloadUnknown()
<ide> {
<add> $this->expectException(\Cake\ORM\Exception\MissingBehaviorException::class);
<add> $this->expectExceptionMessage('Behavior class FooBehavior could not be found.');
<ide> $this->Behaviors->unload('Foo');
<ide> }
<ide>
<ide><path>tests/TestCase/ORM/BehaviorTest.php
<ide> public function testVerifyConfigImplementedFindersOverridden()
<ide> /**
<ide> * testVerifyImplementedFindersInvalid
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage The method findNotDefined is not callable on class Cake\Test\TestCase\ORM\Test2Behavior
<ide> *
<ide> * @return void
<ide> */
<ide> public function testVerifyImplementedFindersInvalid()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('The method findNotDefined is not callable on class Cake\Test\TestCase\ORM\Test2Behavior');
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')->getMock();
<ide> $behavior = new Test2Behavior($table, [
<ide> 'implementedFinders' => [
<ide> public function testVerifyConfigImplementedMethodsOverridden()
<ide> /**
<ide> * testVerifyImplementedMethodsInvalid
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage The method iDoNotExist is not callable on class Cake\Test\TestCase\ORM\Test2Behavior
<ide> *
<ide> * @return void
<ide> */
<ide> public function testVerifyImplementedMethodsInvalid()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('The method iDoNotExist is not callable on class Cake\Test\TestCase\ORM\Test2Behavior');
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')->getMock();
<ide> $behavior = new Test2Behavior($table, [
<ide> 'implementedMethods' => [
<ide><path>tests/TestCase/ORM/CompositeKeysTest.php
<ide> public function strategiesProviderBelongsToMany()
<ide> * Test that you cannot save rows with composite keys if some columns are missing.
<ide> *
<ide> * @group save
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot insert row, some of the primary key values are missing
<ide> * @return void
<ide> */
<ide> public function testSaveNewErrorCompositeKeyNoIncrement()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot insert row, some of the primary key values are missing');
<ide> $articles = TableRegistry::get('SiteArticles');
<ide> $article = $articles->newEntity(['site_id' => 1, 'author_id' => 1, 'title' => 'testing']);
<ide> $articles->save($article);
<ide> public function testSaveNewEntity()
<ide> * if the entity has composite primary key
<ide> *
<ide> * @group save
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot insert row, some of the primary key values are missing. Got (5, ), expecting (id, site_id)
<ide> * @return void
<ide> */
<ide> public function testSaveNewEntityMissingKey()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot insert row, some of the primary key values are missing. Got (5, ), expecting (id, site_id)');
<ide> $entity = new Entity([
<ide> 'id' => 5,
<ide> 'title' => 'Fifth Article',
<ide><path>tests/TestCase/ORM/EntityTest.php
<ide> public function emptyNamesProvider()
<ide> * Tests that trying to get an empty property name throws exception
<ide> *
<ide> * @dataProvider emptyNamesProvider
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testEmptyProperties($property)
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $entity = new Entity();
<ide> $entity->get($property);
<ide> }
<ide>
<ide> /**
<ide> * Tests that setting an empty property name does nothing
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @dataProvider emptyNamesProvider
<ide> * @return void
<ide> */
<ide> public function testSetEmptyPropertyName($property)
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $entity = new Entity();
<ide> $entity->set($property, 'bar');
<ide> }
<ide><path>tests/TestCase/ORM/Locator/TableLocatorTest.php
<ide> public function testConfigPlugin()
<ide> /**
<ide> * Test calling config() on existing instances throws an error.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage You cannot configure "Users", it has already been constructed.
<ide> * @return void
<ide> */
<ide> public function testConfigOnDefinedInstance()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('You cannot configure "Users", it has already been constructed.');
<ide> $users = $this->_locator->get('Users');
<ide> $this->_locator->config('Users', ['table' => 'my_users']);
<ide> }
<ide> public function testGetWithConfigClassName()
<ide> /**
<ide> * Test get with config throws an exception if the alias exists already.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage You cannot configure "Users", it already exists in the registry.
<ide> * @return void
<ide> */
<ide> public function testGetExistingWithConfigData()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('You cannot configure "Users", it already exists in the registry.');
<ide> $users = $this->_locator->get('Users');
<ide> $this->_locator->get('Users', ['table' => 'my_users']);
<ide> }
<ide><path>tests/TestCase/ORM/MarshallerTest.php
<ide> public function testOneAccessibleFieldsOption()
<ide> /**
<ide> * Test one() with an invalid association
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Cannot marshal data for "Derp" association. It is not associated with "Articles".
<ide> * @return void
<ide> */
<ide> public function testOneInvalidAssociation()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot marshal data for "Derp" association. It is not associated with "Articles".');
<ide> $data = [
<ide> 'title' => 'My title',
<ide> 'body' => 'My content',
<ide> public function testManyAssociations()
<ide> * Test if exception is raised when called with [associated => NonExistingAssociation]
<ide> * Previously such association were simply ignored
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testManyInvalidAssociation()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $data = [
<ide> [
<ide> 'comment' => 'First post',
<ide> public function testMergeWhitelist()
<ide> /**
<ide> * Test merge() with an invalid association
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Cannot marshal data for "Derp" association. It is not associated with "Articles".
<ide> * @return void
<ide> */
<ide> public function testMergeInvalidAssociation()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot marshal data for "Derp" association. It is not associated with "Articles".');
<ide> $data = [
<ide> 'title' => 'My title',
<ide> 'body' => 'My content',
<ide> public function testValidationFail()
<ide> /**
<ide> * Test that invalid validate options raise exceptions
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testValidateInvalidType()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> $data = ['title' => 'foo'];
<ide> $marshaller = new Marshaller($this->articles);
<ide> $marshaller->one($data, [
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testEagerLoadingMismatchingAliasInHasOne()
<ide> /**
<ide> * Tests that eagerloading belongsToMany with find list fails with a helpful message.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testEagerLoadingBelongsToManyList()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
<ide> $table = TableRegistry::get('Articles');
<ide> $table->belongsToMany('Tags', [
<ide> public function testFindMatchingOverwrite2()
<ide> * Tests that trying to contain an inexistent association
<ide> * throws an exception and not a fatal error.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testQueryNotFatalError()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->loadFixtures('Comments');
<ide> $comments = TableRegistry::get('Comments');
<ide> $comments->find()->contain('Deprs')->all();
<ide><path>tests/TestCase/ORM/QueryTest.php
<ide> public function testCollectionProxy($method, $arg)
<ide> * Tests that calling an non-existent method in query throws an
<ide> * exception
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Unknown method "derpFilter"
<ide> * @return void
<ide> */
<ide> public function testCollectionProxyBadMethod()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Unknown method "derpFilter"');
<ide> TableRegistry::get('articles')->find('all')->derpFilter();
<ide> }
<ide>
<ide> /**
<ide> * cache() should fail on non select queries.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testCacheErrorOnNonSelect()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> $table = TableRegistry::get('articles', ['table' => 'articles']);
<ide> $query = new Query($this->connection, $table);
<ide> $query->insert(['test']);
<ide> public function testContainSecondSignature()
<ide> * Integration test to ensure that filtering associations with the queryBuilder
<ide> * option works.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testContainWithQueryBuilderHasManyError()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> $table = TableRegistry::get('Authors');
<ide> $table->hasMany('Articles');
<ide> $query = new Query($this->connection, $table);
<ide><path>tests/TestCase/ORM/RulesCheckerIntegrationTest.php
<ide> public function testExistsInWithBindingKey()
<ide> * Tests existsIn with invalid associations
<ide> *
<ide> * @group save
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage ExistsIn rule for 'author_id' is invalid. 'NotValid' is not associated with 'Cake\ORM\Table'.
<ide> * @return void
<ide> */
<ide> public function testExistsInInvalidAssociation()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('ExistsIn rule for \'author_id\' is invalid. \'NotValid\' is not associated with \'Cake\ORM\Table\'.');
<ide> $entity = new Entity([
<ide> 'title' => 'An Article',
<ide> 'author_id' => 500
<ide><path>tests/TestCase/ORM/TableRegressionTest.php
<ide> public function tearDown()
<ide> * in the afterSave callback
<ide> *
<ide> * @see https://github.com/cakephp/cakephp/issues/9079
<del> * @expectedException \Cake\ORM\Exception\RolledbackTransactionException
<ide> * @return void
<ide> */
<ide> public function testAfterSaveRollbackTransaction()
<ide> {
<add> $this->expectException(\Cake\ORM\Exception\RolledbackTransactionException::class);
<ide> $table = TableRegistry::get('Authors');
<ide> $table->getEventManager()->on(
<ide> 'Model.afterSave',
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testUpdateAll()
<ide> /**
<ide> * Test that exceptions from the Query bubble up.
<ide> *
<del> * @expectedException \Cake\Database\Exception
<ide> */
<ide> public function testUpdateAllFailure()
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')
<ide> ->setMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> public function testDeleteAllAliasedConditions()
<ide> /**
<ide> * Test that exceptions from the Query bubble up.
<ide> *
<del> * @expectedException \Cake\Database\Exception
<ide> */
<ide> public function testDeleteAllFailure()
<ide> {
<add> $this->expectException(\Cake\Database\Exception::class);
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')
<ide> ->setMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> class_alias($class, 'MyPlugin\Model\Entity\SuperUser');
<ide> * Tests that using a simple string for entityClass will throw an exception
<ide> * when the class does not exist in the namespace
<ide> *
<del> * @expectedException \Cake\ORM\Exception\MissingEntityException
<del> * @expectedExceptionMessage Entity class FooUser could not be found.
<ide> * @return void
<ide> */
<ide> public function testTableClassNonExisting()
<ide> {
<add> $this->expectException(\Cake\ORM\Exception\MissingEntityException::class);
<add> $this->expectExceptionMessage('Entity class FooUser could not be found.');
<ide> $table = new Table;
<ide> $this->assertFalse($table->entityClass('FooUser'));
<ide> }
<ide> public function testBehaviors()
<ide> /**
<ide> * Ensure exceptions are raised on missing behaviors.
<ide> *
<del> * @expectedException \Cake\ORM\Exception\MissingBehaviorException
<ide> */
<ide> public function testAddBehaviorMissing()
<ide> {
<add> $this->expectException(\Cake\ORM\Exception\MissingBehaviorException::class);
<ide> $table = TableRegistry::get('article');
<ide> $this->assertNull($table->addBehavior('NopeNotThere'));
<ide> }
<ide> public function testAfterSaveCommitTriggeredOnlyForPrimaryTable()
<ide> * Test that you cannot save rows without a primary key.
<ide> *
<ide> * @group save
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot insert row in "users" table, it has no primary key
<ide> * @return void
<ide> */
<ide> public function testSaveNewErrorOnNoPrimaryKey()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot insert row in "users" table, it has no primary key');
<ide> $entity = new Entity(['username' => 'superuser']);
<ide> $table = TableRegistry::get('users', [
<ide> 'schema' => [
<ide> public function testAtomicSave()
<ide> * Tests that save will rollback the transaction in the case of an exception
<ide> *
<ide> * @group save
<del> * @expectedException \PDOException
<ide> * @return void
<ide> */
<ide> public function testAtomicSaveRollback()
<ide> {
<add> $this->expectException(\PDOException::class);
<ide> $connection = $this->getMockBuilder('\Cake\Database\Connection')
<ide> ->setMethods(['begin', 'rollback'])
<ide> ->setConstructorArgs([ConnectionManager::config('test')])
<ide> public function testUpdateDirtyNoActualChanges()
<ide> * Tests that failing to pass a primary key to save will result in exception
<ide> *
<ide> * @group save
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testUpdateNoPrimaryButOtherKeys()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $table = $this->getMockBuilder('\Cake\ORM\Table')
<ide> ->setMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> public function testValidationWithDefiner()
<ide> * Tests that a RuntimeException is thrown if the custom validator does not return an Validator instance
<ide> *
<ide> * @return void
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage The Cake\ORM\Table::validationBad() validation method must return an instance of Cake\Validation\Validator.
<ide> */
<ide> public function testValidationWithBadDefiner()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('The Cake\ORM\Table::validationBad() validation method must return an instance of Cake\Validation\Validator.');
<ide> $table = $this->getMockBuilder('\Cake\ORM\Table')
<ide> ->setMethods(['validationBad'])
<ide> ->getMock();
<ide> public function testValidationWithBadDefiner()
<ide> * Tests that a RuntimeException is thrown if the custom validator method does not exist.
<ide> *
<ide> * @return void
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage The Cake\ORM\Table::validationMissing() validation method does not exists.
<ide> */
<ide> public function testValidatorWithMissingMethod()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('The Cake\ORM\Table::validationMissing() validation method does not exists.');
<ide> $table = new Table();
<ide> $table->getValidator('missing');
<ide> }
<ide> public function testMagicFindDefaultToAll()
<ide> /**
<ide> * Test magic findByXX errors on missing arguments.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Not enough arguments for magic finder. Got 0 required 1
<ide> * @return void
<ide> */
<ide> public function testMagicFindError()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Not enough arguments for magic finder. Got 0 required 1');
<ide> $table = TableRegistry::get('Users');
<ide>
<ide> $table->findByUsername();
<ide> public function testMagicFindError()
<ide> /**
<ide> * Test magic findByXX errors on missing arguments.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Not enough arguments for magic finder. Got 1 required 2
<ide> * @return void
<ide> */
<ide> public function testMagicFindErrorMissingField()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Not enough arguments for magic finder. Got 1 required 2');
<ide> $table = TableRegistry::get('Users');
<ide>
<ide> $table->findByUsernameAndId('garrett');
<ide> public function testMagicFindErrorMissingField()
<ide> /**
<ide> * Test magic findByXX errors when there is a mix of or & and.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
<ide> * @return void
<ide> */
<ide> public function testMagicFindErrorMixOfOperators()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Cannot mix "and" & "or" in a magic finder. Use find() instead.');
<ide> $table = TableRegistry::get('Users');
<ide>
<ide> $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
<ide> public function testGetWithCache($options, $cacheKey, $cacheConfig)
<ide> /**
<ide> * Tests that get() will throw an exception if the record was not found
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\RecordNotFoundException
<del> * @expectedExceptionMessage Record not found in table "articles"
<ide> * @return void
<ide> */
<ide> public function testGetNotFoundException()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\RecordNotFoundException::class);
<add> $this->expectExceptionMessage('Record not found in table "articles"');
<ide> $table = new Table([
<ide> 'name' => 'Articles',
<ide> 'connection' => $this->connection,
<ide> public function testGetNotFoundException()
<ide> /**
<ide> * Test that an exception is raised when there are not enough keys.
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\InvalidPrimaryKeyException
<del> * @expectedExceptionMessage Record not found in table "articles" with primary key [NULL]
<ide> * @return void
<ide> */
<ide> public function testGetExceptionOnNoData()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\InvalidPrimaryKeyException::class);
<add> $this->expectExceptionMessage('Record not found in table "articles" with primary key [NULL]');
<ide> $table = new Table([
<ide> 'name' => 'Articles',
<ide> 'connection' => $this->connection,
<ide> public function testGetExceptionOnNoData()
<ide> /**
<ide> * Test that an exception is raised when there are too many keys.
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\InvalidPrimaryKeyException
<del> * @expectedExceptionMessage Record not found in table "articles" with primary key [1, 'two']
<ide> * @return void
<ide> */
<ide> public function testGetExceptionOnTooMuchData()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\InvalidPrimaryKeyException::class);
<add> $this->expectExceptionMessage('Record not found in table "articles" with primary key [1, \'two\']');
<ide> $table = new Table([
<ide> 'name' => 'Articles',
<ide> 'connection' => $this->connection,
<ide> public function testLoadIntoMany()
<ide> * Tests that saveOrFail triggers an exception on not successful save
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\ORM\Exception\PersistenceFailedException
<del> * @expectedExceptionMessage Entity save failure.
<ide> */
<ide> public function testSaveOrFail()
<ide> {
<add> $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class);
<add> $this->expectExceptionMessage('Entity save failure.');
<ide> $entity = new Entity([
<ide> 'foo' => 'bar'
<ide> ]);
<ide> public function testSaveOrFailGetEntity()
<ide> * Tests that deleteOrFail triggers an exception on not successful delete
<ide> *
<ide> * @return void
<del> * @expectedException \Cake\ORM\Exception\PersistenceFailedException
<del> * @expectedExceptionMessage Entity delete failure.
<ide> */
<ide> public function testDeleteOrFail()
<ide> {
<add> $this->expectException(\Cake\ORM\Exception\PersistenceFailedException::class);
<add> $this->expectExceptionMessage('Entity delete failure.');
<ide> $entity = new Entity([
<ide> 'id' => 999
<ide> ]);
<ide><path>tests/TestCase/Routing/DispatcherFactoryTest.php
<ide> public function testAddFilterString()
<ide> /**
<ide> * Test add filter missing
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingDispatcherFilterException
<ide> * @return void
<ide> */
<ide> public function testAddFilterMissing()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingDispatcherFilterException::class);
<ide> DispatcherFactory::add('NopeSauce');
<ide> }
<ide>
<ide><path>tests/TestCase/Routing/DispatcherFilterTest.php
<ide> public function testImplementedEvents()
<ide> /**
<ide> * Test constructor error invalid when
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage "when" conditions must be a callable.
<ide> * @return void
<ide> */
<ide> public function testConstructorInvalidWhen()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('"when" conditions must be a callable.');
<ide> new DispatcherFilter(['when' => 'nope']);
<ide> }
<ide>
<ide><path>tests/TestCase/Routing/DispatcherTest.php
<ide> public function tearDown()
<ide> /**
<ide> * testMissingController method
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class SomeController could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingController()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class SomeController could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'some_controller/home',
<ide> 'params' => [
<ide> public function testMissingController()
<ide> /**
<ide> * testMissingControllerInterface method
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class Interface could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingControllerInterface()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class Interface could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> public function testMissingControllerInterface()
<ide> /**
<ide> * testMissingControllerInterface method
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class Abstract could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingControllerAbstract()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class Abstract could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'abstract/index',
<ide> 'params' => [
<ide> public function testMissingControllerAbstract()
<ide> * In case-insensitive file systems, lowercase controller names will kind of work.
<ide> * This causes annoying deployment issues for lots of folks.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class somepages could not be found.
<ide> * @return void
<ide> */
<ide> public function testMissingControllerLowercase()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class somepages could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'pages/home',
<ide> 'params' => [
<ide> public function testDispatchActionReturnsResponse()
<ide> /**
<ide> * test forbidden controller names.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class TestPlugin.Tests could not be found.
<ide> * @return void
<ide> */
<ide> public function testDispatchBadPluginName()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class TestPlugin.Tests could not be found.');
<ide> Plugin::load('TestPlugin');
<ide>
<ide> $request = new ServerRequest([
<ide> public function testDispatchBadPluginName()
<ide> /**
<ide> * test forbidden controller names.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingControllerException
<del> * @expectedExceptionMessage Controller class TestApp\Controller\PostsController could not be found.
<ide> * @return void
<ide> */
<ide> public function testDispatchBadName()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingControllerException::class);
<add> $this->expectExceptionMessage('Controller class TestApp\Controller\PostsController could not be found.');
<ide> $request = new ServerRequest([
<ide> 'url' => 'TestApp%5CController%5CPostsController/index',
<ide> 'params' => [
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php
<ide> public function testRouterNoopOnController()
<ide> /**
<ide> * Test missing routes not being caught.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<ide> */
<ide> public function testMissingRouteNotCaught()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/missing']);
<ide> $response = new Response();
<ide> $next = function ($req, $res) {
<ide><path>tests/TestCase/Routing/Route/RedirectRouteTest.php
<ide> public function testParseMiss()
<ide> /**
<ide> * test the parsing of routes.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/posts
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParseSimple()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/posts');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/home', ['controller' => 'posts']);
<ide> $route->parse('/home');
<ide> }
<ide>
<ide> /**
<ide> * test the parsing of routes.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/posts
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParseRedirectOption()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/posts');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/home', ['redirect' => ['controller' => 'posts']]);
<ide> $route->parse('/home');
<ide> }
<ide>
<ide> /**
<ide> * test the parsing of routes.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/posts
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParseArray()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/posts');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/home', ['controller' => 'posts', 'action' => 'index']);
<ide> $route->parse('/home');
<ide> }
<ide>
<ide> /**
<ide> * test redirecting to an external url
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://google.com
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParseAbsolute()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://google.com');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/google', 'http://google.com');
<ide> $route->parse('/google');
<ide> }
<ide>
<ide> /**
<ide> * test redirecting with a status code
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/posts/view
<del> * @expectedExceptionCode 302
<ide> * @return void
<ide> */
<ide> public function testParseStatusCode()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/posts/view');
<add> $this->expectExceptionCode(302);
<ide> $route = new RedirectRoute('/posts/*', ['controller' => 'posts', 'action' => 'view'], ['status' => 302]);
<ide> $route->parse('/posts/2');
<ide> }
<ide>
<ide> /**
<ide> * test redirecting with the persist option
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/posts/view/2
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParsePersist()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/posts/view/2');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/posts/*', ['controller' => 'posts', 'action' => 'view'], ['persist' => true]);
<ide> $route->parse('/posts/2');
<ide> }
<ide>
<ide> /**
<ide> * test redirecting with persist and string target URLs
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/test
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParsePersistStringUrl()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/test');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/posts/*', '/test', ['persist' => true]);
<ide> $route->parse('/posts/2');
<ide> }
<ide>
<ide> /**
<ide> * test redirecting with persist and passed args
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/tags/add/passme
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParsePersistPassedArgs()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/tags/add/passme');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/my_controllers/:action/*', ['controller' => 'tags', 'action' => 'add'], ['persist' => true]);
<ide> $route->parse('/my_controllers/do_something/passme');
<ide> }
<ide>
<ide> /**
<ide> * test redirecting without persist and passed args
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/tags/add
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParseNoPersistPassedArgs()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/tags/add');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/my_controllers/:action/*', ['controller' => 'tags', 'action' => 'add']);
<ide> $route->parse('/my_controllers/do_something/passme');
<ide> }
<ide>
<ide> /**
<ide> * test redirecting with patterns
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/tags/add?lang=nl
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParsePersistPatterns()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/tags/add?lang=nl');
<add> $this->expectExceptionCode(301);
<ide> $route = new RedirectRoute('/:lang/my_controllers', ['controller' => 'tags', 'action' => 'add'], ['lang' => '(nl|en)', 'persist' => ['lang']]);
<ide> $route->parse('/nl/my_controllers/');
<ide> }
<ide>
<ide> /**
<ide> * test redirecting with patterns and a routed target
<ide> *
<del> * @expectedException \Cake\Routing\Exception\RedirectException
<del> * @expectedExceptionMessage http://localhost/nl/preferred_controllers
<del> * @expectedExceptionCode 301
<ide> * @return void
<ide> */
<ide> public function testParsePersistMatchesAnotherRoute()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\RedirectException::class);
<add> $this->expectExceptionMessage('http://localhost/nl/preferred_controllers');
<add> $this->expectExceptionCode(301);
<ide> Router::connect('/:lang/preferred_controllers', ['controller' => 'tags', 'action' => 'add'], ['lang' => '(nl|en)', 'persist' => ['lang']]);
<ide> $route = new RedirectRoute('/:lang/my_controllers', ['controller' => 'tags', 'action' => 'add'], ['lang' => '(nl|en)', 'persist' => ['lang']]);
<ide> $route->parse('/nl/my_controllers/');
<ide><path>tests/TestCase/Routing/Route/RouteTest.php
<ide> public function testSetMethods()
<ide> /**
<ide> * Test setting the method on a route to an invalid method
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Invalid HTTP method received. NOPE is invalid
<ide> * @return void
<ide> */
<ide> public function testSetMethodsInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid HTTP method received. NOPE is invalid');
<ide> $route = new Route('/books/reviews', ['controller' => 'Reviews', 'action' => 'index']);
<ide> $route->setMethods(['nope']);
<ide> }
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testExtensionsString()
<ide> /**
<ide> * Test error on invalid route class
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Route class not found, or route class is not a subclass of
<ide> * @return void
<ide> */
<ide> public function testConnectErrorInvalidRouteClass()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Route class not found, or route class is not a subclass of');
<ide> $routes = new RouteBuilder(
<ide> $this->collection,
<ide> '/l',
<ide> public function testConnectErrorInvalidRouteClass()
<ide> /**
<ide> * Test conflicting parameters raises an exception.
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage You cannot define routes that conflict with the scope.
<ide> * @return void
<ide> */
<ide> public function testConnectConflictingParameters()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('You cannot define routes that conflict with the scope.');
<ide> $routes = new RouteBuilder($this->collection, '/admin', ['plugin' => 'TestPlugin']);
<ide> $routes->connect('/', ['plugin' => 'TestPlugin2', 'controller' => 'Dashboard', 'action' => 'view']);
<ide> }
<ide> public function testMiddlewareGroup()
<ide> /**
<ide> * Test overlap between middleware name and group name
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot add middleware group 'test'. A middleware by this name has already been registered.
<ide> * @return void
<ide> */
<ide> public function testMiddlewareGroupOverlap()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot add middleware group \'test\'. A middleware by this name has already been registered.');
<ide> $func = function () {
<ide> };
<ide> $routes = new RouteBuilder($this->collection, '/api');
<ide> public function testMiddlewareGroupOverlap()
<ide> /**
<ide> * Test applying middleware to a scope when it doesn't exist
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot apply 'bad' middleware or middleware group. Use registerMiddleware() to register middleware
<ide> * @return void
<ide> */
<ide> public function testApplyMiddlewareInvalidName()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot apply \'bad\' middleware or middleware group. Use registerMiddleware() to register middleware');
<ide> $routes = new RouteBuilder($this->collection, '/api');
<ide> $routes->applyMiddleware('bad');
<ide> }
<ide> public function testHttpMethodIntegration()
<ide> /**
<ide> * Test loading routes from a missing plugin
<ide> *
<del> * @expectedException Cake\Core\Exception\MissingPluginException
<ide> * @return void
<ide> */
<ide> public function testLoadPluginBadPlugin()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\MissingPluginException::class);
<ide> $routes = new RouteBuilder($this->collection, '/');
<ide> $routes->loadPlugin('Nope');
<ide> }
<ide>
<ide> /**
<ide> * Test loading routes from a missing file
<ide> *
<del> * @expectedException InvalidArgumentException
<del> * @expectedExceptionMessage Cannot load routes for the plugin named TestPlugin.
<ide> * @return void
<ide> */
<ide> public function testLoadPluginBadFile()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Cannot load routes for the plugin named TestPlugin.');
<ide> Plugin::load('TestPlugin');
<ide> $routes = new RouteBuilder($this->collection, '/');
<ide> $routes->loadPlugin('TestPlugin', 'nope.php');
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> public function setUp()
<ide> /**
<ide> * Test parse() throws an error on unknown routes.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<del> * @expectedExceptionMessage A route matching "/" could not be found
<ide> */
<ide> public function testParseMissingRoute()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<add> $this->expectExceptionMessage('A route matching "/" could not be found');
<ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
<ide> $routes->connect('/', ['controller' => 'Articles']);
<ide> $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']);
<ide> public function testParseMissingRoute()
<ide> /**
<ide> * Test parse() throws an error on known routes called with unknown methods.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<del> * @expectedExceptionMessage A "POST" route matching "/b" could not be found
<ide> */
<ide> public function testParseMissingRouteMethod()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<add> $this->expectExceptionMessage('A "POST" route matching "/b" could not be found');
<ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
<ide> $routes->connect('/', ['controller' => 'Articles', '_method' => ['GET']]);
<ide>
<ide> public function testParseFallback()
<ide> /**
<ide> * Test parseRequest() throws an error on unknown routes.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<del> * @expectedExceptionMessage A route matching "/" could not be found
<ide> */
<ide> public function testParseRequestMissingRoute()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<add> $this->expectExceptionMessage('A route matching "/" could not be found');
<ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
<ide> $routes->connect('/', ['controller' => 'Articles']);
<ide> $routes->connect('/:id', ['controller' => 'Articles', 'action' => 'view']);
<ide> public static function hostProvider()
<ide> * Test parseRequest() checks host conditions
<ide> *
<ide> * @dataProvider hostProvider
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<del> * @expectedExceptionMessage A route matching "/fallback" could not be found
<ide> */
<ide> public function testParseRequestCheckHostConditionFail($host)
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<add> $this->expectExceptionMessage('A route matching "/fallback" could not be found');
<ide> $routes = new RouteBuilder($this->collection, '/');
<ide> $routes->connect(
<ide> '/fallback',
<ide> public function testParseRequestUnicode()
<ide> /**
<ide> * Test match() throws an error on unknown routes.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<del> * @expectedExceptionMessage A route matching "array (
<ide> */
<ide> public function testMatchError()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<add> $this->expectExceptionMessage('A route matching "array (');
<ide> $context = [
<ide> '_base' => '/',
<ide> '_scheme' => 'http',
<ide> public function testMatchNamed()
<ide> /**
<ide> * Test match() throws an error on named routes that fail to match
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<del> * @expectedExceptionMessage A named route was found for "fail", but matching failed
<ide> */
<ide> public function testMatchNamedError()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<add> $this->expectExceptionMessage('A named route was found for "fail", but matching failed');
<ide> $context = [
<ide> '_base' => '/',
<ide> '_scheme' => 'http',
<ide> public function testMatchNamedError()
<ide> /**
<ide> * Test matching routes with names and failing
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<ide> * @return void
<ide> */
<ide> public function testMatchNamedMissingError()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> $context = [
<ide> '_base' => '/',
<ide> '_scheme' => 'http',
<ide> public function testAddingRoutes()
<ide> /**
<ide> * Test the add() with some _name.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\DuplicateNamedRouteException
<ide> *
<ide> * @return void
<ide> */
<ide> public function testAddingDuplicateNamedRoutes()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\DuplicateNamedRouteException::class);
<ide> $one = new Route('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
<ide> $two = new Route('/', ['controller' => 'Dashboards', 'action' => 'display']);
<ide> $this->collection->add($one, ['_name' => 'test']);
<ide> public function testMiddlewareGroupOverwrite()
<ide> /**
<ide> * Test adding ab unregistered middleware to a middleware group fails.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot add 'bad' middleware to group 'group'. It has not been registered.
<ide> * @return void
<ide> */
<ide> public function testMiddlewareGroupUnregisteredMiddleware()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot add \'bad\' middleware to group \'group\'. It has not been registered.');
<ide> $this->collection->middlewareGroup('group', ['bad']);
<ide> }
<ide> }
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testUrlGenerationNamedRoute()
<ide> /**
<ide> * Test that using invalid names causes exceptions.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<ide> * @return void
<ide> */
<ide> public function testNamedRouteException()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> Router::connect(
<ide> '/users/:name',
<ide> ['controller' => 'users', 'action' => 'view'],
<ide> public function testNamedRouteException()
<ide> /**
<ide> * Test that using duplicate names causes exceptions.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\DuplicateNamedRouteException
<ide> * @return void
<ide> */
<ide> public function testDuplicateNamedRouteException()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\DuplicateNamedRouteException::class);
<ide> Router::connect(
<ide> '/users/:name',
<ide> ['controller' => 'users', 'action' => 'view'],
<ide> public function testRouteSymmetry()
<ide> /**
<ide> * Test exceptions when parsing fails.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<ide> */
<ide> public function testParseError()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> Router::connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
<ide> Router::parse('/nope', 'GET');
<ide> }
<ide> public function testParsingWithTrailingPeriodAndParseExtensions()
<ide> /**
<ide> * test that patterns work for :action
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<ide> * @return void
<ide> */
<ide> public function testParsingWithPatternOnAction()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> Router::connect(
<ide> '/blog/:action/*',
<ide> ['controller' => 'blog_posts'],
<ide> public function testParsingWithPatternOnAction()
<ide> /**
<ide> * Test url() works with patterns on :action
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<ide> * @return void
<ide> */
<ide> public function testUrlPatternOnAction()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> Router::connect(
<ide> '/blog/:action/*',
<ide> ['controller' => 'blog_posts'],
<ide> public function testRegexRouteMatching()
<ide> /**
<ide> * testRegexRouteMatching error
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<ide> * @return void
<ide> */
<ide> public function testRegexRouteMatchingError()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> Router::connect('/:locale/:controller/:action/*', [], ['locale' => 'dan|eng']);
<ide> Router::parse('/badness/test/test_action', 'GET');
<ide> }
<ide>
<ide> /**
<ide> * testRegexRouteMatching method
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<ide> * @return void
<ide> */
<ide> public function testRegexRouteMatchUrl()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> Router::connect('/:locale/:controller/:action/*', [], ['locale' => 'dan|eng']);
<ide>
<ide> $request = new ServerRequest();
<ide> public function testUsingCustomRouteClassPluginDotSyntax()
<ide> /**
<ide> * test that route classes must extend \Cake\Routing\Route\Route
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testCustomRouteException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Router::connect('/:controller', [], ['routeClass' => 'Object']);
<ide> }
<ide>
<ide> public function testScope()
<ide> /**
<ide> * Test the scope() method
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testScopeError()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Router::scope('/path', 'derpy');
<ide> }
<ide>
<ide><path>tests/TestCase/Shell/Helper/ProgressHelperTest.php
<ide> public function testInit()
<ide> /**
<ide> * Test that a callback is required.
<ide> *
<del> * @expectedException \RuntimeException
<ide> */
<ide> public function testOutputFailure()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> $this->helper->output(['not a callback']);
<ide> }
<ide>
<ide><path>tests/TestCase/Shell/OrmCacheShellTest.php
<ide> public function testBuildOverwritesExistingData()
<ide> /**
<ide> * Test build() with a non-existing connection name.
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\MissingDatasourceConfigException
<ide> * @return void
<ide> */
<ide> public function testBuildInvalidConnection()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\MissingDatasourceConfigException::class);
<ide> $this->shell->params['connection'] = 'derpy-derp';
<ide> $this->shell->build('articles');
<ide> }
<ide>
<ide> /**
<ide> * Test clear() with an invalid connection name.
<ide> *
<del> * @expectedException \Cake\Datasource\Exception\MissingDatasourceConfigException
<ide> * @return void
<ide> */
<ide> public function testClearInvalidConnection()
<ide> {
<add> $this->expectException(\Cake\Datasource\Exception\MissingDatasourceConfigException::class);
<ide> $this->shell->params['connection'] = 'derpy-derp';
<ide> $this->shell->clear('articles');
<ide> }
<ide><path>tests/TestCase/TestSuite/Constraint/EventFiredWithTest.php
<ide> public function testMatches()
<ide> * tests trying to assert data key=>value when an event is fired multiple times
<ide> *
<ide> * @return void
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<ide> */
<ide> public function testMatchesInvalid()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<ide> $manager = EventManager::instance();
<ide> $manager->setEventList(new EventList());
<ide> $manager->trackEvents(true);
<ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php
<ide> public function testFixturizeClassName()
<ide> /**
<ide> * Test that unknown types are handled gracefully.
<ide> *
<del> * @expectedException \UnexpectedValueException
<del> * @expectedExceptionMessage Referenced fixture class "Test\Fixture\Derp.derpFixture" not found. Fixture "derp.derp" was referenced
<ide> */
<ide> public function testFixturizeInvalidType()
<ide> {
<add> $this->expectException(\UnexpectedValueException::class);
<add> $this->expectExceptionMessage('Referenced fixture class "Test\Fixture\Derp.derpFixture" not found. Fixture "derp.derp" was referenced');
<ide> $test = $this->getMockBuilder('Cake\TestSuite\TestCase')->getMock();
<ide> $test->fixtures = ['derp.derp'];
<ide> $this->manager->fixturize($test);
<ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php
<ide> public function testGetSpecificRouteHttpServer()
<ide> /**
<ide> * Test customizing the app class.
<ide> *
<del> * @expectedException \LogicException
<del> * @expectedExceptionMessage Cannot load "TestApp\MissingApp" for use in integration
<ide> * @return void
<ide> */
<ide> public function testConfigApplication()
<ide> {
<add> $this->expectException(\LogicException::class);
<add> $this->expectExceptionMessage('Cannot load "TestApp\MissingApp" for use in integration');
<ide> DispatcherFactory::clear();
<ide> $this->useHttpServer(true);
<ide> $this->configApplication('TestApp\MissingApp', []);
<ide> public function testFlashAssertionsWithNoRender()
<ide> /**
<ide> * Tests the failure message for assertCookieNotSet
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<del> * @expectedExceptionMessage Cookie 'remember_me' has been set
<ide> * @return void
<ide> */
<ide> public function testCookieNotSetFailure()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<add> $this->expectExceptionMessage('Cookie \'remember_me\' has been set');
<ide> $this->post('/posts/index');
<ide> $this->assertCookieNotSet('remember_me');
<ide> }
<ide> public function testCookieNotSetFailure()
<ide> * Tests the failure message for assertCookieNotSet when no
<ide> * response whas generated
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<del> * @expectedExceptionMessage No response set, cannot assert cookies.
<ide> * @return void
<ide> */
<ide> public function testCookieNotSetFailureNoResponse()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<add> $this->expectExceptionMessage('No response set, cannot assert cookies.');
<ide> $this->assertCookieNotSet('remember_me');
<ide> }
<ide>
<ide> public function testWithExpectedExceptionHttpServer()
<ide> /**
<ide> * Test that exceptions being thrown are handled correctly.
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<ide> * @return void
<ide> */
<ide> public function testWithUnexpectedException()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<ide> $this->get('/tests_apps/throw_exception');
<ide> $this->assertResponseCode(501);
<ide> }
<ide> public function testAssertResponseRegExp()
<ide> /**
<ide> * Test the content regexp assertion failing
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<del> * @expectedExceptionMessage No response set
<ide> * @return void
<ide> */
<ide> public function testAssertResponseRegExpNoResponse()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<add> $this->expectExceptionMessage('No response set');
<ide> $this->assertResponseRegExp('/cont/');
<ide> }
<ide>
<ide> public function testAssertResponseNotRegExp()
<ide> /**
<ide> * Test negated content regexp assertion failing
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<del> * @expectedExceptionMessage No response set
<ide> * @return void
<ide> */
<ide> public function testAssertResponseNotRegExpNoResponse()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<add> $this->expectExceptionMessage('No response set');
<ide> $this->assertResponseNotRegExp('/cont/');
<ide> }
<ide>
<ide> public function testSendFileHttpServer()
<ide> /**
<ide> * Test that assertFile requires a response
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<del> * @expectedExceptionMessage No response set, cannot assert file
<ide> * @return void
<ide> */
<ide> public function testAssertFileNoResponse()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<add> $this->expectExceptionMessage('No response set, cannot assert file');
<ide> $this->assertFileResponse('foo');
<ide> }
<ide>
<ide> /**
<ide> * Test that assertFile requires a file
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<del> * @expectedExceptionMessage No file was sent in this response
<ide> * @return void
<ide> */
<ide> public function testAssertFileNoFile()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<add> $this->expectExceptionMessage('No file was sent in this response');
<ide> $this->get('/posts/get');
<ide> $this->assertFileResponse('foo');
<ide> }
<ide>
<ide> /**
<ide> * Test disabling the error handler middleware.
<ide> *
<del> * @expectedException \Cake\Routing\Exception\MissingRouteException
<del> * @expectedExceptionMessage A route matching "/foo" could not be found.
<ide> * @return void
<ide> */
<ide> public function testDisableErrorHandlerMiddleware()
<ide> {
<add> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<add> $this->expectExceptionMessage('A route matching "/foo" could not be found.');
<ide> $this->disableErrorHandlerMiddleware();
<ide> $this->get('/foo');
<ide> }
<ide><path>tests/TestCase/TestSuite/TestCaseTest.php
<ide> class TestCaseTest extends TestCase
<ide> /**
<ide> * tests trying to assertEventFired without configuring an event list
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<ide> */
<ide> public function testEventFiredMisconfiguredEventList()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<ide> $manager = EventManager::instance();
<ide> $this->assertEventFired('my.event', $manager);
<ide> }
<ide>
<ide> /**
<ide> * tests trying to assertEventFired without configuring an event list
<ide> *
<del> * @expectedException \PHPUnit\Framework\AssertionFailedError
<ide> */
<ide> public function testEventFiredWithMisconfiguredEventList()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
<ide> $manager = EventManager::instance();
<ide> $this->assertEventFiredWith('my.event', 'some', 'data', $manager);
<ide> }
<ide><path>tests/TestCase/TestSuite/TestFixtureTest.php
<ide> public function testInitImportModel()
<ide> * test schema reflection without $import or $fields and without the table existing
<ide> * it will throw an exception
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage Cannot describe schema for table `letters` for fixture `Cake\Test\TestCase\TestSuite\LettersFixture` : the table does not exist.
<ide> * @return void
<ide> */
<ide> public function testInitNoImportNoFieldsException()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('Cannot describe schema for table `letters` for fixture `Cake\Test\TestCase\TestSuite\LettersFixture` : the table does not exist.');
<ide> $fixture = new LettersFixture();
<ide> $fixture->init();
<ide> }
<ide> public function testCreate()
<ide> /**
<ide> * test create method, trigger error
<ide> *
<del> * @expectedException \PHPUnit\Framework\Error\Error
<ide> * @return void
<ide> */
<ide> public function testCreateError()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\Error\Error::class);
<ide> $fixture = new ArticlesFixture();
<ide> $db = $this->getMockBuilder('Cake\Database\Connection')
<ide> ->disableOriginalConstructor()
<ide><path>tests/TestCase/Utility/Crypto/OpenSslTest.php
<ide> public function setUp()
<ide> /**
<ide> * testRijndael method
<ide> *
<del> * @expectedException \LogicException
<ide> * @return void
<ide> */
<ide> public function testRijndael()
<ide> {
<add> $this->expectException(\LogicException::class);
<ide> $txt = 'The quick brown fox jumped over the lazy dog.';
<ide> $key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
<ide>
<ide><path>tests/TestCase/Utility/HashTest.php
<ide> public function testGetEmptyKey()
<ide> /**
<ide> * Test get() for invalid $data type
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid data type, must be an array or \ArrayAccess instance.
<ide> * @return void
<ide> */
<ide> public function testGetInvalidData()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid data type, must be an array or \ArrayAccess instance.');
<ide> Hash::get('string', 'path');
<ide> }
<ide>
<ide> /**
<ide> * Test get() with an invalid path
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testGetInvalidPath()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Hash::get(['one' => 'two'], true);
<ide> }
<ide>
<ide> public function testNumeric()
<ide> /**
<ide> * Test passing invalid argument type
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid data type, must be an array or \ArrayAccess instance.
<ide> * @return void
<ide> */
<ide> public function testExtractInvalidArgument()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid data type, must be an array or \ArrayAccess instance.');
<ide> Hash::extract('foo', '');
<ide> }
<ide>
<ide> public function testCombine()
<ide> /**
<ide> * test combine() giving errors on key/value length mismatches.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testCombineErrorMissingValue()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> $data = [
<ide> ['User' => ['id' => 1, 'name' => 'mark']],
<ide> ['User' => ['name' => 'jose']],
<ide> public function testCombineErrorMissingValue()
<ide> /**
<ide> * test combine() giving errors on key/value length mismatches.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testCombineErrorMissingKey()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> $data = [
<ide> ['User' => ['id' => 1, 'name' => 'mark']],
<ide> ['User' => ['id' => 2]],
<ide> public function testMissingParent()
<ide> /**
<ide> * Tests that nest() throws an InvalidArgumentException when providing an invalid input.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testNestInvalid()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $input = [
<ide> [
<ide> 'ParentCategory' => [
<ide><path>tests/TestCase/Utility/SecurityTest.php
<ide> public function testRijndael()
<ide> /**
<ide> * testRijndaelInvalidOperation method
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testRijndaelInvalidOperation()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $txt = 'The quick brown fox jumped over the lazy dog.';
<ide> $key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
<ide> Security::rijndael($txt, $key, 'foo');
<ide> public function testRijndaelInvalidOperation()
<ide> /**
<ide> * testRijndaelInvalidKey method
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testRijndaelInvalidKey()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $txt = 'The quick brown fox jumped over the lazy dog.';
<ide> $key = 'too small';
<ide> Security::rijndael($txt, $key, 'encrypt');
<ide> public function testDecryptHmacSaltFailure()
<ide> /**
<ide> * Test that short keys cause errors
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid key for encrypt(), key must be at least 256 bits (32 bytes) long.
<ide> * @return void
<ide> */
<ide> public function testEncryptInvalidKey()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid key for encrypt(), key must be at least 256 bits (32 bytes) long.');
<ide> $txt = 'The quick brown fox jumped over the lazy dog.';
<ide> $key = 'this is too short';
<ide> Security::encrypt($txt, $key);
<ide> public function testEncryptDecryptFalseyData()
<ide> /**
<ide> * Test that short keys cause errors
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Invalid key for decrypt(), key must be at least 256 bits (32 bytes) long.
<ide> * @return void
<ide> */
<ide> public function testDecryptInvalidKey()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Invalid key for decrypt(), key must be at least 256 bits (32 bytes) long.');
<ide> $txt = 'The quick brown fox jumped over the lazy dog.';
<ide> $key = 'this is too short';
<ide> Security::decrypt($txt, $key);
<ide> public function testDecryptInvalidKey()
<ide> /**
<ide> * Test that empty data cause errors
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage The data to decrypt cannot be empty.
<ide> * @return void
<ide> */
<ide> public function testDecryptInvalidData()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The data to decrypt cannot be empty.');
<ide> $txt = '';
<ide> $key = 'This is a key that is long enough to be ok.';
<ide> Security::decrypt($txt, $key);
<ide><path>tests/TestCase/Utility/TextTest.php
<ide> public function testparseFileSize($params, $expected)
<ide> /**
<ide> * testparseFileSizeException
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testparseFileSizeException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> Text::parseFileSize('bogus', false);
<ide> }
<ide>
<ide><path>tests/TestCase/Utility/XmlTest.php
<ide> public function testBuildHuge()
<ide> /**
<ide> * Test that the readFile option disables local file parsing.
<ide> *
<del> * @expectedException \Cake\Utility\Exception\XmlException
<ide> * @return void
<ide> */
<ide> public function testBuildFromFileWhenDisabled()
<ide> {
<add> $this->expectException(\Cake\Utility\Exception\XmlException::class);
<ide> $xml = CORE_TESTS . 'Fixture/sample.xml';
<ide> $obj = Xml::build($xml, ['readFile' => false]);
<ide> }
<ide> public static function invalidDataProvider()
<ide> * testBuildInvalidData
<ide> *
<ide> * @dataProvider invalidDataProvider
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testBuildInvalidData($value)
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> Xml::build($value);
<ide> }
<ide>
<ide> /**
<ide> * Test that building SimpleXmlElement with invalid XML causes the right exception.
<ide> *
<del> * @expectedException \Cake\Utility\Exception\XmlException
<ide> * @return void
<ide> */
<ide> public function testBuildInvalidDataSimpleXml()
<ide> {
<add> $this->expectException(\Cake\Utility\Exception\XmlException::class);
<ide> $input = '<derp';
<ide> Xml::build($input, ['return' => 'simplexml']);
<ide> }
<ide> public static function invalidArrayDataProvider()
<ide> * testFromArrayFail method
<ide> *
<ide> * @dataProvider invalidArrayDataProvider
<del> * @expectedException \Exception
<ide> * @return void
<ide> */
<ide> public function testFromArrayFail($value)
<ide> {
<add> $this->expectException(\Exception::class);
<ide> Xml::fromArray($value);
<ide> }
<ide>
<ide> public static function invalidToArrayDataProvider()
<ide> * testToArrayFail method
<ide> *
<ide> * @dataProvider invalidToArrayDataProvider
<del> * @expectedException \Cake\Utility\Exception\XmlException
<ide> * @return void
<ide> */
<ide> public function testToArrayFail($value)
<ide> {
<add> $this->expectException(\Cake\Utility\Exception\XmlException::class);
<ide> Xml::toArray($value);
<ide> }
<ide>
<ide><path>tests/TestCase/Validation/ValidationRuleTest.php
<ide> public function testCustomMethodNoProvider()
<ide> /**
<ide> * Make sure errors are triggered when validation is missing.
<ide> *
<del> * @expectedException \InvalidArgumentException
<del> * @expectedExceptionMessage Unable to call method "totallyMissing" in "default" provider for field "test"
<ide> * @return void
<ide> */
<ide> public function testCustomMethodMissingError()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage('Unable to call method "totallyMissing" in "default" provider for field "test"');
<ide> $def = ['rule' => ['totallyMissing']];
<ide> $data = 'some data';
<ide> $providers = ['default' => $this];
<ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> public function testMimeTypePsr7()
<ide> /**
<ide> * testMimeTypeFalse method
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testMimeTypeFalse()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> $image = CORE_TESTS . 'invalid-file.png';
<ide> $File = new File($image, false);
<ide> $this->skipIf($File->mime(), 'mimeType can be determined, no Exception will be thrown');
<ide> public function testNumElements()
<ide> /**
<ide> * Test ImageSize InvalidArgumentException
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testImageSizeInvalidArgumentException()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $this->assertTrue(Validation::imageSize([], []));
<ide> }
<ide>
<ide><path>tests/TestCase/Validation/ValidatorTest.php
<ide> public function testRequirePresenceAsArray()
<ide> /**
<ide> * Tests the requirePresence failure case
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testRequirePresenceAsArrayFailure()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $validator = new Validator();
<ide> $validator->requirePresence(['title' => 'derp', 'created' => false]);
<ide> }
<ide> public function testAllowEmptyAsArray()
<ide> /**
<ide> * Tests the allowEmpty failure case
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testAllowEmptyAsArrayFailure()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $validator = new Validator();
<ide> $validator->allowEmpty(['title' => 'derp', 'created' => false]);
<ide> }
<ide> public function testNotEmptyAsArray()
<ide> /**
<ide> * Tests the notEmpty failure case
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testNotEmptyAsArrayFailure()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $validator = new Validator();
<ide> $validator->notEmpty(['title' => 'derp', 'created' => false]);
<ide> }
<ide> public function testLengthBetween()
<ide> /**
<ide> * Tests the lengthBetween proxy method
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testLengthBetweenFailure()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $validator = new Validator();
<ide> $validator->lengthBetween('username', [7]);
<ide> }
<ide> public function testRange()
<ide> /**
<ide> * Tests the range failure case
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testRangeFailure()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $validator = new Validator();
<ide> $validator->range('username', [1]);
<ide> }
<ide><path>tests/TestCase/View/CellTest.php
<ide> public function testCellManualRender()
<ide> /**
<ide> * Tests manual render() invocation with error
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingCellViewException
<ide> * @return void
<ide> */
<ide> public function testCellManualRenderError()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingCellViewException::class);
<ide> $cell = $this->View->cell('Articles');
<ide> $cell->render('derp');
<ide> }
<ide> public function testPluginCellAlternateTemplateRenderParam()
<ide> /**
<ide> * Tests that using an non-existent cell throws an exception.
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingCellException
<ide> * @return void
<ide> */
<ide> public function testNonExistentCell()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingCellException::class);
<ide> $cell = $this->View->cell('TestPlugin.Void::echoThis', ['arg1' => 'v1']);
<ide> $cell = $this->View->cell('Void::echoThis', ['arg1' => 'v1', 'arg2' => 'v2']);
<ide> }
<ide>
<ide> /**
<ide> * Tests missing method errors
<ide> *
<del> * @expectedException \BadMethodCallException
<del> * @expectedExceptionMessage Class TestApp\View\Cell\ArticlesCell does not have a "nope" method.
<ide> * @return void
<ide> */
<ide> public function testCellMissingMethod()
<ide> {
<add> $this->expectException(\BadMethodCallException::class);
<add> $this->expectExceptionMessage('Class TestApp\View\Cell\ArticlesCell does not have a "nope" method.');
<ide> $cell = $this->View->cell('Articles::nope');
<ide> $cell->render();
<ide> }
<ide><path>tests/TestCase/View/Form/EntityContextTest.php
<ide> public function testIsCreateCollection($collection)
<ide> /**
<ide> * Test an invalid table scope throws an error.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Unable to find table class for current entity
<ide> */
<ide> public function testInvalidTable()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Unable to find table class for current entity');
<ide> $row = new \stdClass();
<ide> $context = new EntityContext($this->request, [
<ide> 'entity' => $row,
<ide> public function testInvalidTable()
<ide> /**
<ide> * Tests that passing a plain entity will give an error as it cannot be matched
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Unable to find table class for current entity
<ide> */
<ide> public function testDefaultEntityError()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Unable to find table class for current entity');
<ide> $context = new EntityContext($this->request, [
<ide> 'entity' => new Entity,
<ide> ]);
<ide><path>tests/TestCase/View/Helper/BreadcrumbsHelperTest.php
<ide> public function testInsertAt()
<ide> /**
<ide> * Test adding crumbs to a specific index
<ide> *
<del> * @expectedException \LogicException
<ide> */
<ide> public function testInsertAtIndexOutOfBounds()
<ide> {
<add> $this->expectException(\LogicException::class);
<ide> $this->breadcrumbs
<ide> ->add('Home', '/', ['class' => 'first'])
<ide> ->insertAt(2, 'Insert At Again', ['controller' => 'Insert', 'action' => 'at_again']);
<ide><path>tests/TestCase/View/Helper/FlashHelperTest.php
<ide> public function testFlash()
<ide> /**
<ide> * testFlashThrowsException
<ide> *
<del> * @expectedException \UnexpectedValueException
<ide> */
<ide> public function testFlashThrowsException()
<ide> {
<add> $this->expectException(\UnexpectedValueException::class);
<ide> $this->View->request->session()->write('Flash.foo', 'bar');
<ide> $this->Flash->render('foo');
<ide> }
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testRenderingWidgetWithEmptyName()
<ide> /**
<ide> * Test registering an invalid widget class.
<ide> *
<del> * @expectedException \RuntimeException
<ide> * @return void
<ide> */
<ide> public function testAddWidgetInvalid()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<ide> $mock = new \StdClass();
<ide> $this->Form->addWidget('test', $mock);
<ide> $this->Form->widget('test');
<ide> public function testAddContextProviderAdd()
<ide> /**
<ide> * Test adding an invalid context class.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Context providers must return object implementing Cake\View\Form\ContextInterface. Got "stdClass" instead.
<ide> * @return void
<ide> */
<ide> public function testAddContextProviderInvalid()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Context providers must return object implementing Cake\View\Form\ContextInterface. Got "stdClass" instead.');
<ide> $context = 'My data';
<ide> $this->Form->addContextProvider('test', function ($request, $data) use ($context) {
<ide> return new \StdClass();
<ide> public function testControlMagicSelectForTypeNumber()
<ide> *
<ide> * Test invalid 'input' type option to control() function.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Invalid type 'input' used for field 'text'
<ide> * @return void
<ide> */
<ide> public function testInvalidControlTypeOption()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Invalid type \'input\' used for field \'text\'');
<ide> $this->Form->control('text', ['type' => 'input']);
<ide> }
<ide>
<ide> public function testHtml5ControlWithControl()
<ide> *
<ide> * Test errors when field name is missing.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<ide> * @return void
<ide> */
<ide> public function testHtml5ControlException()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $this->Form->email();
<ide> }
<ide>
<ide><path>tests/TestCase/View/HelperRegistryTest.php
<ide> public function testLazyLoad()
<ide> /**
<ide> * test lazy loading of helpers
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingHelperException
<ide> * @return void
<ide> */
<ide> public function testLazyLoadException()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingHelperException::class);
<ide> $this->Helpers->NotAHelper;
<ide> }
<ide>
<ide> public function testLoadWithEnabledFalse()
<ide> /**
<ide> * test missinghelper exception
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingHelperException
<ide> * @return void
<ide> */
<ide> public function testLoadMissingHelper()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingHelperException::class);
<ide> $this->Helpers->load('ThisHelperShouldAlwaysBeMissing');
<ide> }
<ide>
<ide> public function testUnload()
<ide> /**
<ide> * Test that unloading a none existing helper triggers an error.
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingHelperException
<del> * @expectedExceptionMessage Helper class FooHelper could not be found.
<ide> * @return void
<ide> */
<ide> public function testUnloadUnknown()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingHelperException::class);
<add> $this->expectExceptionMessage('Helper class FooHelper could not be found.');
<ide> $this->Helpers->unload('Foo');
<ide> }
<ide>
<ide> public function testLoadMultipleTimesDefaultConfigValuesWorks()
<ide> /**
<ide> * Loading a helper with different config, should throw an exception
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage The "Html" alias has already been loaded with the following
<ide> * @return void
<ide> */
<ide> public function testLoadMultipleTimesDifferentConfigured()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('The "Html" alias has already been loaded with the following');
<ide> $this->Helpers->load('Html');
<ide> $this->Helpers->load('Html', ['same' => 'stuff']);
<ide> }
<ide>
<ide> /**
<ide> * Loading a helper with different config, should throw an exception
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage The "Html" alias has already been loaded with the following
<ide> * @return void
<ide> */
<ide> public function testLoadMultipleTimesDifferentConfigValues()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('The "Html" alias has already been loaded with the following');
<ide> $this->Helpers->load('Html', ['key' => 'value']);
<ide> $this->Helpers->load('Html', ['key' => 'new value']);
<ide> }
<ide><path>tests/TestCase/View/StringTemplateTest.php
<ide> public function testFormatArrayData()
<ide> /**
<ide> * Test formatting a missing template.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Cannot find template named 'missing'
<ide> * @return void
<ide> */
<ide> public function testFormatMissingTemplate()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Cannot find template named \'missing\'');
<ide> $templates = [
<ide> 'text' => '{{text}}',
<ide> ];
<ide> public function testLoadPlugin()
<ide> /**
<ide> * Test that loading non-existing templates causes errors.
<ide> *
<del> * @expectedException \Cake\Core\Exception\Exception
<del> * @expectedExceptionMessage Could not load configuration file
<ide> */
<ide> public function testLoadErrorNoFile()
<ide> {
<add> $this->expectException(\Cake\Core\Exception\Exception::class);
<add> $this->expectExceptionMessage('Could not load configuration file');
<ide> $this->template->load('no_such_file');
<ide> }
<ide>
<ide><path>tests/TestCase/View/ViewBuilderTest.php
<ide> public function testBuildAppViewPresent()
<ide> /**
<ide> * test missing view class
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingViewException
<del> * @expectedExceptionMessage View class "Foo" is missing.
<ide> * @return void
<ide> */
<ide> public function testBuildMissingViewClass()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingViewException::class);
<add> $this->expectExceptionMessage('View class "Foo" is missing.');
<ide> $builder = new ViewBuilder();
<ide> $builder->setClassName('Foo');
<ide> $builder->build();
<ide><path>tests/TestCase/View/ViewTest.php
<ide> public function testPluginGetTemplate()
<ide> * Test that plugin files with absolute file paths are scoped
<ide> * to the plugin and do now allow any file path.
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingTemplateException
<ide> * @return void
<ide> */
<ide> public function testPluginGetTemplateAbsoluteFail()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingTemplateException::class);
<ide> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> public function testGetViewFileNames()
<ide> /**
<ide> * Test that getViewFileName() protects against malicious directory traversal.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testGetViewFileNameDirectoryTraversal()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $viewOptions = [
<ide> 'plugin' => null,
<ide> 'name' => 'Pages',
<ide> public function testGetLayoutFileNamePrefix()
<ide> /**
<ide> * Test that getLayoutFileName() protects against malicious directory traversal.
<ide> *
<del> * @expectedException \InvalidArgumentException
<ide> * @return void
<ide> */
<ide> public function testGetLayoutFileNameDirectoryTraversal()
<ide> {
<add> $this->expectException(\InvalidArgumentException::class);
<ide> $viewOptions = [
<ide> 'plugin' => null,
<ide> 'name' => 'Pages',
<ide> public function testGetLayoutFileNameDirectoryTraversal()
<ide> /**
<ide> * Test for missing views
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingTemplateException
<ide> * @return void
<ide> */
<ide> public function testMissingTemplate()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingTemplateException::class);
<ide> $viewOptions = ['plugin' => null,
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages'
<ide> public function testMissingTemplate()
<ide> /**
<ide> * Test for missing layouts
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingLayoutException
<ide> * @return void
<ide> */
<ide> public function testMissingLayout()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingLayoutException::class);
<ide> $viewOptions = ['plugin' => null,
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages',
<ide> public function testBlockSetObjectWithToString()
<ide> * This should produce a "Object of class TestObjectWithoutToString could not be converted to string" error
<ide> * which gets thrown as a \PHPUnit\Framework\Error\Error Exception by PHPUnit.
<ide> *
<del> * @expectedException \PHPUnit\Framework\Error\Error
<ide> * @return void
<ide> */
<ide> public function testBlockSetObjectWithoutToString()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\Error\Error::class);
<ide> $objectWithToString = new TestObjectWithoutToString();
<ide> $this->View->assign('testWithObjectWithoutToString', $objectWithToString);
<ide> }
<ide> public function testBlockAppend($value)
<ide> * This should produce a "Object of class TestObjectWithoutToString could not be converted to string" error
<ide> * which gets thrown as a \PHPUnit\Framework\Error\Error Exception by PHPUnit.
<ide> *
<del> * @expectedException \PHPUnit\Framework\Error\Error
<ide> * @return void
<ide> */
<ide> public function testBlockAppendObjectWithoutToString()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\Error\Error::class);
<ide> $object = new TestObjectWithoutToString();
<ide> $this->View->assign('testBlock', 'Block ');
<ide> $this->View->append('testBlock', $object);
<ide> public function testBlockPrepend($value)
<ide> * This should produce a "Object of class TestObjectWithoutToString could not be converted to string" error
<ide> * which gets thrown as a \PHPUnit\Framework\Error\Error Exception by PHPUnit.
<ide> *
<del> * @expectedException \PHPUnit\Framework\Error\Error
<ide> * @return void
<ide> */
<ide> public function testBlockPrependObjectWithoutToString()
<ide> {
<add> $this->expectException(\PHPUnit\Framework\Error\Error::class);
<ide> $object = new TestObjectWithoutToString();
<ide> $this->View->assign('test', 'Block ');
<ide> $this->View->prepend('test', $object);
<ide><path>tests/TestCase/View/ViewVarsTraitTest.php
<ide> public function testCreateViewParameter()
<ide> /**
<ide> * test createView() throws exception if view class cannot be found
<ide> *
<del> * @expectedException \Cake\View\Exception\MissingViewException
<del> * @expectedExceptionMessage View class "Foo" is missing.
<ide> * @return void
<ide> */
<ide> public function testCreateViewException()
<ide> {
<add> $this->expectException(\Cake\View\Exception\MissingViewException::class);
<add> $this->expectExceptionMessage('View class "Foo" is missing.');
<ide> $this->subject->createView('Foo');
<ide> }
<ide> }
<ide><path>tests/TestCase/View/Widget/WidgetRegistryTest.php
<ide> public function testAdd()
<ide> /**
<ide> * Test adding an instance of an invalid type.
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Widget objects must implement Cake\View\Widget\WidgetInterface
<ide> * @return void
<ide> */
<ide> public function testAddInvalidType()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Widget objects must implement Cake\View\Widget\WidgetInterface');
<ide> $inputs = new WidgetRegistry($this->templates, $this->view);
<ide> $inputs->add([
<ide> 'text' => new \StdClass()
<ide> public function testGetFallback()
<ide> /**
<ide> * Test getting errors
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Unknown widget "foo"
<ide> * @return void
<ide> */
<ide> public function testGetNoFallbackError()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Unknown widget "foo"');
<ide> $inputs = new WidgetRegistry($this->templates, $this->view);
<ide> $inputs->clear();
<ide> $inputs->get('foo');
<ide> public function testGetResolveDependency()
<ide> /**
<ide> * Test getting resolve dependency missing class
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Unable to locate widget class "TestApp\View\DerpWidget"
<ide> * @return void
<ide> */
<ide> public function testGetResolveDependencyMissingClass()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Unable to locate widget class "TestApp\View\DerpWidget"');
<ide> $inputs = new WidgetRegistry($this->templates, $this->view);
<ide> $inputs->add(['test' => ['TestApp\View\DerpWidget']]);
<ide> $inputs->get('test');
<ide> public function testGetResolveDependencyMissingClass()
<ide> /**
<ide> * Test getting resolve dependency missing dependency
<ide> *
<del> * @expectedException \RuntimeException
<del> * @expectedExceptionMessage Unknown widget "label"
<ide> * @return void
<ide> */
<ide> public function testGetResolveDependencyMissingDependency()
<ide> {
<add> $this->expectException(\RuntimeException::class);
<add> $this->expectExceptionMessage('Unknown widget "label"');
<ide> $inputs = new WidgetRegistry($this->templates, $this->view);
<ide> $inputs->clear();
<ide> $inputs->add(['multicheckbox' => ['Cake\View\Widget\MultiCheckboxWidget', 'label']]); | 136 |
PHP | PHP | use dispatch instead of fire | 5e98a2ce90530847f11a3d8ed7e73d9fea6acc14 | <ide><path>src/Illuminate/Auth/SessionGuard.php
<ide> public function logout()
<ide> }
<ide>
<ide> if (isset($this->events)) {
<del> $this->events->fire(new Events\Logout($user));
<add> $this->events->dispatch(new Events\Logout($user));
<ide> }
<ide>
<ide> // Once we have fired the logout event we will clear the users out of memory
<ide> public function attempting($callback)
<ide> protected function fireAttemptEvent(array $credentials, $remember = false)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->fire(new Events\Attempting(
<add> $this->events->dispatch(new Events\Attempting(
<ide> $credentials, $remember
<ide> ));
<ide> }
<ide> protected function fireAttemptEvent(array $credentials, $remember = false)
<ide> protected function fireLoginEvent($user, $remember = false)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->fire(new Events\Login($user, $remember));
<add> $this->events->dispatch(new Events\Login($user, $remember));
<ide> }
<ide> }
<ide>
<ide> protected function fireLoginEvent($user, $remember = false)
<ide> protected function fireAuthenticatedEvent($user)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->fire(new Events\Authenticated($user));
<add> $this->events->dispatch(new Events\Authenticated($user));
<ide> }
<ide> }
<ide>
<ide> protected function fireAuthenticatedEvent($user)
<ide> protected function fireFailedEvent($user, array $credentials)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->fire(new Events\Failed($user, $credentials));
<add> $this->events->dispatch(new Events\Failed($user, $credentials));
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Broadcasting/PendingBroadcast.php
<ide> public function toOthers()
<ide> */
<ide> public function __destruct()
<ide> {
<del> $this->events->fire($this->event);
<add> $this->events->dispatch($this->event);
<ide> }
<ide> }
<ide><path>src/Illuminate/Cache/Repository.php
<ide> public function getStore()
<ide> protected function event($event)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->fire($event);
<add> $this->events->dispatch($event);
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Console/Application.php
<ide> public function __construct(Container $laravel, Dispatcher $events, $version)
<ide> $this->setAutoExit(false);
<ide> $this->setCatchExceptions(false);
<ide>
<del> $events->fire(new Events\ArtisanStarting($this));
<add> $events->dispatch(new Events\ArtisanStarting($this));
<ide>
<ide> $this->bootstrap();
<ide> }
<ide><path>src/Illuminate/Database/Connection.php
<ide> protected function fireConnectionEvent($event)
<ide>
<ide> switch ($event) {
<ide> case 'beganTransaction':
<del> return $this->events->fire(new Events\TransactionBeginning($this));
<add> return $this->events->dispatch(new Events\TransactionBeginning($this));
<ide> case 'committed':
<del> return $this->events->fire(new Events\TransactionCommitted($this));
<add> return $this->events->dispatch(new Events\TransactionCommitted($this));
<ide> case 'rollingBack':
<del> return $this->events->fire(new Events\TransactionRolledBack($this));
<add> return $this->events->dispatch(new Events\TransactionRolledBack($this));
<ide> }
<ide> }
<ide>
<ide> protected function fireConnectionEvent($event)
<ide> protected function event($event)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->fire($event);
<add> $this->events->dispatch($event);
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Events/Dispatcher.php
<ide> public function hasListeners($eventName)
<ide> public function push($event, $payload = [])
<ide> {
<ide> $this->listen($event.'_pushed', function () use ($event, $payload) {
<del> $this->fire($event, $payload);
<add> $this->dispatch($event, $payload);
<ide> });
<ide> }
<ide>
<ide> protected function resolveSubscriber($subscriber)
<ide> */
<ide> public function flush($event)
<ide> {
<del> $this->fire($event.'_pushed');
<add> $this->dispatch($event.'_pushed');
<ide> }
<ide>
<ide> /**
<ide> public function flush($event)
<ide> * @return array|null
<ide> */
<ide> public function dispatch($event, $payload = [])
<del> {
<del> return $this->fire($event, $payload);
<del> }
<del>
<del> /**
<del> * Fire an event and call the listeners.
<del> *
<del> * @param string|object $event
<del> * @param mixed $payload
<del> * @return array|null
<del> */
<del> public function fire($event, $payload = [])
<ide> {
<ide> // When the given "event" is actually an object we will assume it is an event
<ide> // object and use the class as the event name and this event itself as the
<ide> public function fire($event, $payload = [])
<ide> return $responses;
<ide> }
<ide>
<add> /**
<add> * Fire an event and call the listeners.
<add> *
<add> * @param string|object $event
<add> * @param mixed $payload
<add> * @return array|null
<add> */
<add> public function fire($event, $payload = [])
<add> {
<add> return $this->dispatch($event, $payload);
<add> }
<add>
<ide> /**
<ide> * Parse the given event and payload and prepare them for dispatching.
<ide> *
<ide><path>src/Illuminate/Log/Writer.php
<ide> protected function fireLogEvent($level, $message, array $context = [])
<ide> // log listeners. These are useful for building profilers or other tools
<ide> // that aggregate all of the log messages for a given "request" cycle.
<ide> if (isset($this->dispatcher)) {
<del> $this->dispatcher->fire(new MessageLogged($level, $message, $context));
<add> $this->dispatcher->dispatch(new MessageLogged($level, $message, $context));
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Mail/Mailer.php
<ide> protected function createMessage()
<ide> protected function sendSwiftMessage($message)
<ide> {
<ide> if ($this->events) {
<del> $this->events->fire(new Events\MessageSending($message));
<add> $this->events->dispatch(new Events\MessageSending($message));
<ide> }
<ide>
<ide> try {
<ide><path>src/Illuminate/Notifications/Channels/BroadcastChannel.php
<ide> public function send($notifiable, Notification $notification)
<ide> ->onQueue($message->queue);
<ide> }
<ide>
<del> return $this->events->fire($event);
<add> return $this->events->dispatch($event);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Notifications/NotificationSender.php
<ide> protected function sendToNotifiable($notifiable, $id, $notification, $channel)
<ide>
<ide> $response = $this->manager->driver($channel)->send($notifiable, $notification);
<ide>
<del> $this->events->fire(
<add> $this->events->dispatch(
<ide> new Events\NotificationSent($notifiable, $notification, $channel, $response)
<ide> );
<ide> }
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function dispatchToRoute(Request $request)
<ide> return $route;
<ide> });
<ide>
<del> $this->events->fire(new Events\RouteMatched($route, $request));
<add> $this->events->dispatch(new Events\RouteMatched($route, $request));
<ide>
<ide> $response = $this->runRouteWithinStack($route, $request);
<ide>
<ide><path>tests/Auth/AuthGuardTest.php
<ide> public function testAttemptCallsRetrieveByCredentials()
<ide> {
<ide> $guard = $this->getGuard();
<ide> $guard->setDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type(Attempting::class));
<del> $events->shouldReceive('fire')->once()->with(m::type(Failed::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Attempting::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Failed::class));
<ide> $guard->getProvider()->shouldReceive('retrieveByCredentials')->once()->with(['foo']);
<ide> $guard->attempt(['foo']);
<ide> }
<ide> public function testAttemptReturnsUserInterface()
<ide> list($session, $provider, $request, $cookie) = $this->getMocks();
<ide> $guard = $this->getMockBuilder('Illuminate\Auth\SessionGuard')->setMethods(['login'])->setConstructorArgs(['default', $provider, $session, $request])->getMock();
<ide> $guard->setDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type(Attempting::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Attempting::class));
<ide> $user = $this->createMock('Illuminate\Contracts\Auth\Authenticatable');
<ide> $guard->getProvider()->shouldReceive('retrieveByCredentials')->once()->andReturn($user);
<ide> $guard->getProvider()->shouldReceive('validateCredentials')->with($user, ['foo'])->andReturn(true);
<ide> public function testAttemptReturnsFalseIfUserNotGiven()
<ide> {
<ide> $mock = $this->getGuard();
<ide> $mock->setDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type(Attempting::class));
<del> $events->shouldReceive('fire')->once()->with(m::type(Failed::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Attempting::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Failed::class));
<ide> $mock->getProvider()->shouldReceive('retrieveByCredentials')->once()->andReturn(null);
<ide> $this->assertFalse($mock->attempt(['foo']));
<ide> }
<ide> public function testLoginFiresLoginAndAuthenticatedEvents()
<ide> $mock = $this->getMockBuilder('Illuminate\Auth\SessionGuard')->setMethods(['getName'])->setConstructorArgs(['default', $provider, $session, $request])->getMock();
<ide> $mock->setDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<ide> $user = m::mock('Illuminate\Contracts\Auth\Authenticatable');
<del> $events->shouldReceive('fire')->once()->with(m::type('Illuminate\Auth\Events\Login'));
<del> $events->shouldReceive('fire')->once()->with(m::type('Illuminate\Auth\Events\Authenticated'));
<add> $events->shouldReceive('dispatch')->once()->with(m::type('Illuminate\Auth\Events\Login'));
<add> $events->shouldReceive('dispatch')->once()->with(m::type('Illuminate\Auth\Events\Authenticated'));
<ide> $mock->expects($this->once())->method('getName')->will($this->returnValue('foo'));
<ide> $user->shouldReceive('getAuthIdentifier')->once()->andReturn('bar');
<ide> $mock->getSession()->shouldReceive('put')->with('foo', 'bar')->once();
<ide> public function testFailedAttemptFiresFailedEvent()
<ide> {
<ide> $guard = $this->getGuard();
<ide> $guard->setDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type(Attempting::class));
<del> $events->shouldReceive('fire')->once()->with(m::type(Failed::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Attempting::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Failed::class));
<ide> $guard->getProvider()->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn(null);
<ide> $guard->attempt(['foo']);
<ide> }
<ide> public function testSetUserFiresAuthenticatedEvent()
<ide> $user = m::mock('Illuminate\Contracts\Auth\Authenticatable');
<ide> $guard = $this->getGuard();
<ide> $guard->setDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type(Authenticated::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Authenticated::class));
<ide> $guard->setUser($user);
<ide> }
<ide>
<ide> public function testLogoutFiresLogoutEvent()
<ide> $user = m::mock('Illuminate\Contracts\Auth\Authenticatable');
<ide> $user->shouldReceive('setRememberToken')->once();
<ide> $provider->shouldReceive('updateRememberToken')->once();
<del> $events->shouldReceive('fire')->once()->with(m::type(Authenticated::class));
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Authenticated::class));
<ide> $mock->setUser($user);
<del> $events->shouldReceive('fire')->once()->with(m::type('Illuminate\Auth\Events\Logout'));
<add> $events->shouldReceive('dispatch')->once()->with(m::type('Illuminate\Auth\Events\Logout'));
<ide> $mock->logout();
<ide> }
<ide>
<ide><path>tests/Cache/CacheEventsTest.php
<ide> public function testHasTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<ide> $this->assertFalse($repository->has('foo'));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux']));
<ide> $this->assertTrue($repository->has('baz'));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<ide> $this->assertFalse($repository->tags('taylor')->has('foo'));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux', 'tags' => ['taylor']]));
<ide> $this->assertTrue($repository->tags('taylor')->has('baz'));
<ide> }
<ide>
<ide> public function testGetTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<ide> $this->assertNull($repository->get('foo'));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux']));
<ide> $this->assertEquals('qux', $repository->get('baz'));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<ide> $this->assertNull($repository->tags('taylor')->get('foo'));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux', 'tags' => ['taylor']]));
<ide> $this->assertEquals('qux', $repository->tags('taylor')->get('baz'));
<ide> }
<ide>
<ide> public function testPullTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux']));
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyForgotten::class, ['key' => 'baz']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyForgotten::class, ['key' => 'baz']));
<ide> $this->assertEquals('qux', $repository->pull('baz'));
<ide> }
<ide>
<ide> public function testPullTriggersEventsUsingTags()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux', 'tags' => ['taylor']]));
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyForgotten::class, ['key' => 'baz', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheHit::class, ['key' => 'baz', 'value' => 'qux', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyForgotten::class, ['key' => 'baz', 'tags' => ['taylor']]));
<ide> $this->assertEquals('qux', $repository->tags('taylor')->pull('baz'));
<ide> }
<ide>
<ide> public function testPutTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<ide> $repository->put('foo', 'bar', 99);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<ide> $repository->tags('taylor')->put('foo', 'bar', 99);
<ide> }
<ide>
<ide> public function testAddTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<ide> $this->assertTrue($repository->add('foo', 'bar', 99));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<ide> $this->assertTrue($repository->tags('taylor')->add('foo', 'bar', 99));
<ide> }
<ide>
<ide> public function testForeverTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<ide> $repository->forever('foo', 'bar');
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<ide> $repository->tags('taylor')->forever('foo', 'bar');
<ide> }
<ide>
<ide> public function testRememberTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<ide> $this->assertEquals('bar', $repository->remember('foo', 99, function () {
<ide> return 'bar';
<ide> }));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<ide> $this->assertEquals('bar', $repository->tags('taylor')->remember('foo', 99, function () {
<ide> return 'bar';
<ide> }));
<ide> public function testRememberForeverTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar']));
<ide> $this->assertEquals('bar', $repository->rememberForever('foo', function () {
<ide> return 'bar';
<ide> }));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheMissed::class, ['key' => 'foo', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyWritten::class, ['key' => 'foo', 'value' => 'bar', 'tags' => ['taylor']]));
<ide> $this->assertEquals('bar', $repository->tags('taylor')->rememberForever('foo', function () {
<ide> return 'bar';
<ide> }));
<ide> public function testForgetTriggersEvents()
<ide> $dispatcher = $this->getDispatcher();
<ide> $repository = $this->getRepository($dispatcher);
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyForgotten::class, ['key' => 'baz']));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyForgotten::class, ['key' => 'baz']));
<ide> $this->assertTrue($repository->forget('baz'));
<ide>
<del> $dispatcher->shouldReceive('fire')->once()->with($this->assertEventMatches(KeyForgotten::class, ['key' => 'baz', 'tags' => ['taylor']]));
<add> $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(KeyForgotten::class, ['key' => 'baz', 'tags' => ['taylor']]));
<ide> $this->assertTrue($repository->tags('taylor')->forget('baz'));
<ide> }
<ide>
<ide><path>tests/Console/ConsoleApplicationTest.php
<ide> public function testResolveAddsCommandViaApplicationResolution()
<ide> protected function getMockConsole(array $methods)
<ide> {
<ide> $app = m::mock('Illuminate\Contracts\Foundation\Application', ['version' => '5.4']);
<del> $events = m::mock('Illuminate\Contracts\Events\Dispatcher', ['fire' => null]);
<add> $events = m::mock('Illuminate\Contracts\Events\Dispatcher', ['dispatch' => null]);
<ide>
<ide> $console = $this->getMockBuilder('Illuminate\Console\Application')->setMethods($methods)->setConstructorArgs([
<ide> $app, $events, 'test-version',
<ide><path>tests/Database/DatabaseConnectionTest.php
<ide> public function testBeganTransactionFiresEventsIfSet()
<ide> $connection = $this->getMockConnection(['getName'], $pdo);
<ide> $connection->expects($this->any())->method('getName')->will($this->returnValue('name'));
<ide> $connection->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type('Illuminate\Database\Events\TransactionBeginning'));
<add> $events->shouldReceive('dispatch')->once()->with(m::type('Illuminate\Database\Events\TransactionBeginning'));
<ide> $connection->beginTransaction();
<ide> }
<ide>
<ide> public function testCommitedFiresEventsIfSet()
<ide> $connection = $this->getMockConnection(['getName'], $pdo);
<ide> $connection->expects($this->any())->method('getName')->will($this->returnValue('name'));
<ide> $connection->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type('Illuminate\Database\Events\TransactionCommitted'));
<add> $events->shouldReceive('dispatch')->once()->with(m::type('Illuminate\Database\Events\TransactionCommitted'));
<ide> $connection->commit();
<ide> }
<ide>
<ide> public function testRollBackedFiresEventsIfSet()
<ide> $connection->expects($this->any())->method('getName')->will($this->returnValue('name'));
<ide> $connection->beginTransaction();
<ide> $connection->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type('Illuminate\Database\Events\TransactionRolledBack'));
<add> $events->shouldReceive('dispatch')->once()->with(m::type('Illuminate\Database\Events\TransactionRolledBack'));
<ide> $connection->rollBack();
<ide> }
<ide>
<ide> public function testRedundantRollBackFiresNoEvent()
<ide> $connection = $this->getMockConnection(['getName'], $pdo);
<ide> $connection->expects($this->any())->method('getName')->will($this->returnValue('name'));
<ide> $connection->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldNotReceive('fire');
<add> $events->shouldNotReceive('dispatch');
<ide> $connection->rollBack();
<ide> }
<ide>
<ide> public function testLogQueryFiresEventsIfSet()
<ide> $connection = $this->getMockConnection();
<ide> $connection->logQuery('foo', [], time());
<ide> $connection->setEventDispatcher($events = m::mock('Illuminate\Contracts\Events\Dispatcher'));
<del> $events->shouldReceive('fire')->once()->with(m::type('Illuminate\Database\Events\QueryExecuted'));
<add> $events->shouldReceive('dispatch')->once()->with(m::type('Illuminate\Database\Events\QueryExecuted'));
<ide> $connection->logQuery('foo', [], null);
<ide> }
<ide>
<ide><path>tests/Notifications/NotificationBroadcastChannelTest.php
<ide> public function testDatabaseChannelCreatesDatabaseRecordWithProperData()
<ide> $notifiable = Mockery::mock();
<ide>
<ide> $events = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
<del> $events->shouldReceive('fire')->once()->with(Mockery::type('Illuminate\Notifications\Events\BroadcastNotificationCreated'));
<add> $events->shouldReceive('dispatch')->once()->with(Mockery::type('Illuminate\Notifications\Events\BroadcastNotificationCreated'));
<ide> $channel = new BroadcastChannel($events);
<ide> $channel->send($notifiable, $notification);
<ide> }
<ide> public function testNotificationIsBroadcastedNow()
<ide> $notifiable = Mockery::mock();
<ide>
<ide> $events = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
<del> $events->shouldReceive('fire')->once()->with(Mockery::on(function ($event) {
<add> $events->shouldReceive('dispatch')->once()->with(Mockery::on(function ($event) {
<ide> return $event->connection == 'sync';
<ide> }));
<ide> $channel = new BroadcastChannel($events);
<ide><path>tests/Notifications/NotificationChannelManagerTest.php
<ide> public function testNotificationCanBeDispatchedToDriver()
<ide> $manager->shouldReceive('driver')->andReturn($driver = Mockery::mock());
<ide> $events->shouldReceive('until')->with(Mockery::type(Illuminate\Notifications\Events\NotificationSending::class))->andReturn(true);
<ide> $driver->shouldReceive('send')->once();
<del> $events->shouldReceive('fire')->with(Mockery::type(Illuminate\Notifications\Events\NotificationSent::class));
<add> $events->shouldReceive('dispatch')->with(Mockery::type(Illuminate\Notifications\Events\NotificationSent::class));
<ide>
<ide> $manager->send(new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestNotification);
<ide> }
<ide> public function testNotificationNotSentOnHalt()
<ide> $events->shouldReceive('until')->with(Mockery::type(Illuminate\Notifications\Events\NotificationSending::class))->andReturn(true);
<ide> $manager->shouldReceive('driver')->once()->andReturn($driver = Mockery::mock());
<ide> $driver->shouldReceive('send')->once();
<del> $events->shouldReceive('fire')->with(Mockery::type(Illuminate\Notifications\Events\NotificationSent::class));
<add> $events->shouldReceive('dispatch')->with(Mockery::type(Illuminate\Notifications\Events\NotificationSent::class));
<ide>
<ide> $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestNotificationWithTwoChannels);
<ide> } | 17 |
PHP | PHP | add more methods to collection | 9032d1aa4583c6de258f54aa7b67f05897b45bf3 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function each(callable $callback)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Create a new collection consisting of even elements.
<add> *
<add> * @return static
<add> */
<add> public function even()
<add> {
<add> return $this->every(2);
<add> }
<add>
<add> /**
<add> * Create a new collection consisting of every n-th element.
<add> *
<add> * @param int $step
<add> * @param int $offset
<add> * @return static
<add> */
<add> public function every($step, $offset = 0)
<add> {
<add> $new = [];
<add> $position = 0;
<add> foreach ($this->items as $key => $item) {
<add> if ($position % $step === $offset) {
<add> $new[] = $item;
<add> }
<add> $position++;
<add> }
<add>
<add> return new static($new);
<add> }
<add>
<ide> /**
<ide> * Fetch a nested element of the collection.
<ide> *
<ide> public function min($key = null)
<ide> });
<ide> }
<ide>
<add> /**
<add> * Create a new collection consisting of odd elements.
<add> *
<add> * @return static
<add> */
<add> public function odd()
<add> {
<add> return $this->every(2, 1);
<add> }
<add>
<ide> /**
<ide> * "Paginate" the collection by slicing it into a smaller collection.
<ide> *
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testChunk()
<ide> $this->assertEquals([10], $data[3]->toArray());
<ide> }
<ide>
<add> public function testEven()
<add> {
<add> $data = new Collection(['a', 'b', 'c', 'd', 'e', 'f']);
<add>
<add> $this->assertEquals(['a', 'c', 'e'], $data->even()->all());
<add> }
<add>
<add> public function testOdd()
<add> {
<add> $data = new Collection(['a', 'b', 'c', 'd', 'e', 'f']);
<add>
<add> $this->assertEquals(['b', 'd', 'f'], $data->odd()->all());
<add> }
<add>
<add> public function testEvery()
<add> {
<add> $data = new Collection([
<add> 6 => 'a',
<add> 4 => 'b',
<add> 7 => 'c',
<add> 1 => 'd',
<add> 5 => 'e',
<add> 3 => 'f',
<add> ]);
<add>
<add> $this->assertEquals(['a', 'e'], $data->every(4)->all());
<add> $this->assertEquals(['b', 'f'], $data->every(4, 1)->all());
<add> $this->assertEquals(['c'], $data->every(4, 2)->all());
<add> $this->assertEquals(['d'], $data->every(4, 3)->all());
<add> }
<add>
<ide> public function testPluckWithArrayAndObjectValues()
<ide> {
<ide> $data = new Collection([(object) ['name' => 'taylor', 'email' => 'foo'], ['name' => 'dayle', 'email' => 'bar']]); | 2 |
Python | Python | add option for base model in init-model cli | 49ef06d793b885c3bd634ac72f38be067246822a | <ide><path>spacy/cli/init_model.py
<ide>
<ide> from ..vectors import Vectors
<ide> from ..errors import Errors, Warnings
<del>from ..util import ensure_path, get_lang_class, OOV_RANK
<add>from ..util import ensure_path, get_lang_class, load_model, OOV_RANK
<ide>
<ide> try:
<ide> import ftfy
<ide> str,
<ide> ),
<ide> model_name=("Optional name for the model meta", "option", "mn", str),
<add> base_model=("Base model (for languages with custom tokenizers)", "option", "b", str),
<ide> )
<ide> def init_model(
<ide> lang,
<ide> def init_model(
<ide> prune_vectors=-1,
<ide> vectors_name=None,
<ide> model_name=None,
<add> base_model=None,
<ide> ):
<ide> """
<ide> Create a new model from raw data, like word frequencies, Brown clusters
<ide> def init_model(
<ide> lex_attrs = read_attrs_from_deprecated(freqs_loc, clusters_loc)
<ide>
<ide> with msg.loading("Creating model..."):
<del> nlp = create_model(lang, lex_attrs, name=model_name)
<add> nlp = create_model(lang, lex_attrs, name=model_name, base_model=base_model)
<ide> msg.good("Successfully created model")
<ide> if vectors_loc is not None:
<ide> add_vectors(nlp, vectors_loc, truncate_vectors, prune_vectors, vectors_name)
<ide> def read_attrs_from_deprecated(freqs_loc, clusters_loc):
<ide> return lex_attrs
<ide>
<ide>
<del>def create_model(lang, lex_attrs, name=None):
<del> lang_class = get_lang_class(lang)
<del> nlp = lang_class()
<add>def create_model(lang, lex_attrs, name=None, base_model=None):
<add> if base_model:
<add> nlp = load_model(base_model)
<add> # keep the tokenizer but remove any existing pipeline components due to
<add> # potentially conflicting vectors
<add> for pipe in nlp.pipe_names:
<add> nlp.remove_pipe(pipe)
<add> else:
<add> lang_class = get_lang_class(lang)
<add> nlp = lang_class()
<ide> for lexeme in nlp.vocab:
<ide> lexeme.rank = OOV_RANK
<ide> for attrs in lex_attrs: | 1 |
PHP | PHP | remove encrpyption method | 33908a5079b3ef791f0c09fc502396692f228a6a | <ide><path>src/Controller/Component/CookieComponent.php
<ide> public function delete($key) {
<ide> }
<ide> }
<ide>
<del>/**
<del> * Get / set encryption type. Use this method in ex: AppController::beforeFilter()
<del> * before you have read or written any cookies.
<del> *
<del> * @param string|null $type Encryption type to set or null to get current type.
<del> * @return string|null
<del> * @throws \Cake\Error\Exception When an unknown type is used.
<del> */
<del> public function encryption($type = null) {
<del> if ($type === null) {
<del> return $this->_config['encryption'];
<del> }
<del>
<del> $availableTypes = [
<del> 'rijndael',
<del> 'aes'
<del> ];
<del> if (!in_array($type, $availableTypes)) {
<del> throw new Error\Exception('You must use rijndael, or aes for cookie encryption type');
<del> }
<del> $this->config('encryption', $type);
<del> }
<del>
<ide> /**
<ide> * Set cookie
<ide> *
<ide><path>tests/TestCase/Controller/Component/CookieComponentTest.php
<ide> public function testWriteThanRead() {
<ide> * @return void
<ide> */
<ide> public function testWriteWithFalseyValue() {
<del> $this->Cookie->encryption('aes');
<del> $this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^';
<add> $this->Cookie->config([
<add> 'encryption' => 'aes',
<add> 'key' => 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^',
<add> ]);
<ide>
<ide> $this->Cookie->write('Testing');
<ide> $result = $this->Cookie->read('Testing'); | 2 |
Text | Text | update description to accommodate tests | dc7092ecd18a1e6d3ea20f18db943ae993ee8d85 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.english.md
<ide> forumTopicId: 301363
<ide> Usernames are used everywhere on the internet. They are what give users a unique identity on their favorite sites.
<ide> You need to check all the usernames in a database. Here are some simple rules that users have to follow when creating their username.
<ide> 1) Usernames can only use alpha-numeric characters.
<del>2) The only numbers in the username have to be at the end. There can be zero or more of them at the end.
<add>2) The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.
<ide> 3) Username letters can be lowercase and uppercase.
<ide> 4) Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
<ide> </section> | 1 |
Text | Text | update the upgrading guide | a9adf93d50610b429a1b4ddf51aef44e043b9019 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> Also, make sure `config.cache_classes` is set to `false` in `config/environments
<ide>
<ide> ### Applications need to run in `zeitwerk` mode
<ide>
<del>Applications still running in `classic` mode have to switch to `zeitwerk` mode. Please check the [upgrading guide for Rails 6.0](https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#autoloading) for details.
<add>Applications still running in `classic` mode have to switch to `zeitwerk` mode. Please check the [Classic to Zeitwerk HOWTO](https://guides.rubyonrails.org/classic_to_zeitwerk_howto.html) guide for details.
<ide>
<ide> ### The setter `config.autoloader=` has been deleted
<ide> | 1 |
Text | Text | use shields.io instead of pypip.in | 7eeb0e81c03ed8c6c9ed4523511641fce9332b64 | <ide><path>README.md
<ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide>
<ide> [build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.svg?branch=master
<ide> [travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
<del>[pypi-version]: https://pypip.in/version/djangorestframework/badge.svg
<add>[pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
<ide> [pypi]: https://pypi.python.org/pypi/djangorestframework
<ide> [twitter]: https://twitter.com/_tomchristie
<ide> [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework | 1 |
Javascript | Javascript | fix bug in iso-week creation test | d67554fe7d1a317e9761f6d89fb8359ca1eb7de8 | <ide><path>test/moment/create.js
<ide> exports.create = {
<ide>
<ide> test.equal(moment('22', 'WW').isoWeek(), 22, 'iso week sets the week by itself');
<ide> test.equal(moment('2012 22', 'YYYY WW').weekYear(), 2012, 'iso week keeps parsed year');
<del> test.equal(moment('22', 'WW').weekYear(), moment().weekYear(), 'iso week keeps this year');
<add> test.equal(moment('22', 'WW').isoWeekYear(), moment().isoWeekYear(), 'iso week keeps this year');
<ide>
<ide> // order
<ide> ver('6 2013 2', 'e gggg w', '2013 01 12', 'order doesn\'t matter'); | 1 |
PHP | PHP | fix failing tests around positional replacements | 5b475a1f15ec5dca553868316c76c2743ab7041c | <ide><path>src/Database/Log/QueryLogger.php
<ide> protected function _interpolate($query)
<ide>
<ide> $keys = [];
<ide> $limit = is_int(key($params)) ? 1 : -1;
<del> $params = array_reverse($params);
<ide> foreach ($params as $key => $param) {
<del> $keys[] = is_string($key) ? "/:$key/" : '/[?]/';
<add> $keys[] = is_string($key) ? "/:$key\b/" : '/[?]/';
<ide> }
<ide>
<ide> return preg_replace($keys, $params, $query->query, $limit);
<ide><path>tests/TestCase/Database/Log/QueryLoggerTest.php
<ide> public function testStringInterpolation3()
<ide> $this->assertEquals($expected, (string)$query);
<ide> }
<ide>
<add> /**
<add> * Tests that named placeholders
<add> *
<add> * @return void
<add> */
<add> public function testStringInterpolationNamed()
<add> {
<add> $logger = $this->getMock('\Cake\Database\Log\QueryLogger', ['_log']);
<add> $query = new LoggedQuery;
<add> $query->query = 'SELECT a FROM b where a = :p1 AND b = :p11 AND c = :p20 AND d = :p2';
<add> $query->params = ['p11' => 'test', 'p1' => 'string', 'p2' => 3, 'p20' => 5];
<add>
<add> $logger->expects($this->once())->method('_log')->with($query);
<add> $logger->log($query);
<add> $expected = "SELECT a FROM b where a = 'string' AND b = 'test' AND c = 5 AND d = 3";
<add> $this->assertEquals($expected, (string)$query);
<add> }
<add>
<ide> /**
<ide> * Tests that the logged query object is passed to the built-in logger using
<ide> * the correct scope | 2 |
Ruby | Ruby | add method to return the corresponding version | 31b61cb01342b5a2079cb447693d003bdf455a65 | <ide><path>Library/Homebrew/keg.rb
<ide> def completion_installed? shell
<ide> dir.directory? and not dir.children.length.zero?
<ide> end
<ide>
<add> def version
<add> require 'version'
<add> Version.new(basename.to_s)
<add> end
<add>
<add> def basename
<add> Pathname.new(self.to_s).basename
<add> end
<add>
<ide> def link mode=nil
<ide> raise "Cannot link #{fname}\nAnother version is already linked: #{linked_keg_record.realpath}" if linked_keg_record.directory?
<ide> | 1 |
Javascript | Javascript | remove stray logging | 7aec696bb5a1e570badc08280fb72d14d299d7c8 | <ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> expect(initialKoreanCharacterWidth).not.toBe(initialBaseCharacterWidth)
<ide> verifyCursorPosition(component, cursorNode, 1, 29)
<ide>
<del> console.log(initialFontSize);
<ide> element.style.fontSize = initialFontSize - 5 + 'px'
<ide> TextEditor.didUpdateStyles()
<ide> await component.getNextUpdatePromise() | 1 |
Mixed | Ruby | fix code typo in `mysqladapter` .closes | d0ea5c5b20687520740bad636951973a34ac2e68 | <ide><path>activerecord/CHANGELOG.md
<add>* Fix code typo in `MysqlAdapter` when `Encoding.default_internal` is set.
<add>
<add> Fixes #12647.
<add>
<add> *Yves Senn*
<add>
<ide> * ActiveRecord::Base#attribute_for_inspect now truncates long arrays (more than 10 elements)
<ide>
<ide> *Jan Bernacki*
<ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
<ide> def version
<ide> def set_field_encoding field_name
<ide> field_name.force_encoding(client_encoding)
<ide> if internal_enc = Encoding.default_internal
<del> field_name = field_name.encoding(internal_enc)
<add> field_name = field_name.encode!(internal_enc)
<ide> end
<ide> field_name
<ide> end
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_readonly_attributes
<ide> end
<ide>
<ide> def test_unicode_column_name
<add> Weird.reset_column_information
<ide> weird = Weird.create(:なまえ => 'たこ焼き仮面')
<ide> assert_equal 'たこ焼き仮面', weird.なまえ
<ide> end
<ide>
<add> def test_respect_internal_encoding
<add> if current_adapter?(:PostgreSQLAdapter)
<add> skip 'pg does not respect internal encoding and always returns utf8'
<add> end
<add> old_default_internal = Encoding.default_internal
<add> silence_warnings { Encoding.default_internal = "EUC-JP" }
<add>
<add> Weird.reset_column_information
<add>
<add> assert_equal ["EUC-JP"], Weird.columns.map {|c| c.name.encoding.name }.uniq
<add> ensure
<add> silence_warnings { Encoding.default_internal = old_default_internal }
<add> end
<add>
<ide> def test_non_valid_identifier_column_name
<ide> weird = Weird.create('a$b' => 'value')
<ide> weird.reload | 3 |
PHP | PHP | add support for middleware groups | 737ee84cc2f5a71ae359a1fc7c5ced6d741e901d | <ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> class Kernel implements KernelContract
<ide> */
<ide> protected $middleware = [];
<ide>
<add> /**
<add> * The application's route middleware groups.
<add> *
<add> * @var array
<add> */
<add> protected $middlewareGroups = [];
<add>
<ide> /**
<ide> * The application's route middleware.
<ide> *
<ide> public function __construct(Application $app, Router $router)
<ide> $this->app = $app;
<ide> $this->router = $router;
<ide>
<add> foreach ($this->middlewareGroups as $key => $middleware) {
<add> $router->middlewareGroup($key, $middleware);
<add> }
<add>
<ide> foreach ($this->routeMiddleware as $key => $middleware) {
<ide> $router->middleware($key, $middleware);
<ide> }
<ide><path>src/Illuminate/Routing/ControllerDispatcher.php
<ide>
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Pipeline\Pipeline;
<add>use Illuminate\Support\Collection;
<ide> use Illuminate\Container\Container;
<ide>
<ide> class ControllerDispatcher
<ide> protected function callWithinStack($instance, $route, $request, $method)
<ide> */
<ide> protected function getMiddleware($instance, $method)
<ide> {
<del> $results = [];
<add> $results = new Collection;
<ide>
<ide> foreach ($instance->getMiddleware() as $name => $options) {
<ide> if (! $this->methodExcludedByOptions($method, $options)) {
<ide> $results[] = $this->router->resolveMiddlewareClassName($name);
<ide> }
<ide> }
<ide>
<del> return $results;
<add> return $results->flatten()->all();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Routing/Router.php
<ide> class Router implements RegistrarContract
<ide> */
<ide> protected $middleware = [];
<ide>
<add> /**
<add> * All of the middleware groups.
<add> *
<add> * @var array
<add> */
<add> protected $middlewareGroups = [];
<add>
<ide> /**
<ide> * The registered route value binders.
<ide> *
<ide> protected function runRouteWithinStack(Route $route, Request $request)
<ide> public function gatherRouteMiddlewares(Route $route)
<ide> {
<ide> return Collection::make($route->middleware())->map(function ($name) {
<add> if (isset($this->middlewareGroups[$name])) {
<add> return $this->middlewareGroups[$name];
<add> }
<add>
<ide> return Collection::make($this->resolveMiddlewareClassName($name));
<ide> })
<ide> ->collapse()->all();
<ide> }
<ide>
<ide> /**
<del> * Resolve the middleware name to a class name preserving passed parameters.
<add> * Resolve the middleware name to a class name(s) preserving passed parameters.
<ide> *
<ide> * @param string $name
<del> * @return string
<add> * @return string|array
<ide> */
<ide> public function resolveMiddlewareClassName($name)
<ide> {
<ide> $map = $this->middleware;
<ide>
<del> list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
<add> if (isset($this->middlewareGroups[$name])) {
<add> return $this->middlewareGroups[$name];
<add> } elseif (isset($map[$name]) && $map[$name] instanceof Closure) {
<add> return $map[$name];
<add> } else {
<add> list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
<ide>
<del> return (isset($map[$name]) ? $map[$name] : $name).($parameters !== null ? ':'.$parameters : '');
<add> return (isset($map[$name]) ? $map[$name] : $name).
<add> ($parameters !== null ? ':'.$parameters : '');
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function middleware($name, $class)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Register a group of middleware.
<add> *
<add> * @param string $name
<add> * @param array $middleware
<add> * @return $this
<add> */
<add> public function middlewareGroup($name, array $middleware)
<add> {
<add> $this->middlewareGroups[$name] = $middleware;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Register a model binder for a wildcard.
<ide> *
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testBasicDispatchingOfRoutes()
<ide> $this->assertEquals('closure', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
<ide> }
<ide>
<add> public function testClosureMiddleware()
<add> {
<add> $router = $this->getRouter();
<add> $router->get('foo/bar', ['middleware' => 'foo', function () { return 'hello'; }]);
<add> $router->middleware('foo', function ($request, $next) {
<add> return 'caught';
<add> });
<add> $this->assertEquals('caught', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
<add> }
<add>
<add> public function testMiddlewareGroups()
<add> {
<add> unset($_SERVER['__middleware.group']);
<add> $router = $this->getRouter();
<add> $router->get('foo/bar', ['middleware' => 'web', function () { return 'hello'; }]);
<add>
<add> $router->middlewareGroup('web', [
<add> function ($request, $next) {
<add> $_SERVER['__middleware.group'] = true;
<add> return $next($request);
<add> },
<add> function ($request, $next) {
<add> return 'caught';
<add> },
<add> ]);
<add>
<add> $this->assertEquals('caught', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
<add> $this->assertTrue($_SERVER['__middleware.group']);
<add>
<add> unset($_SERVER['__middleware.group']);
<add> }
<add>
<ide> public function testFluentRouteNamingWithinAGroup()
<ide> {
<ide> $router = $this->getRouter();
<ide> public function testControllerRouting()
<ide> $_SERVER['route.test.controller.middleware.parameters.one'], $_SERVER['route.test.controller.middleware.parameters.two']
<ide> );
<ide>
<del> $router = new Router(new Illuminate\Events\Dispatcher, $container = new Illuminate\Container\Container);
<del>
<del> $container->singleton('illuminate.route.dispatcher', function ($container) use ($router) {
<del> return new Illuminate\Routing\ControllerDispatcher($router, $container);
<del> });
<add> $router = $this->getRouter();
<ide>
<ide> $router->get('foo/bar', 'RouteTestControllerStub@index');
<ide>
<ide> public function testControllerRouting()
<ide> $this->assertFalse(isset($_SERVER['route.test.controller.except.middleware']));
<ide> }
<ide>
<add> public function testControllerMiddlewareGroups()
<add> {
<add> unset(
<add> $_SERVER['route.test.controller.middleware'],
<add> $_SERVER['route.test.controller.middleware.class']
<add> );
<add>
<add> $router = $this->getRouter();
<add>
<add> $router->middlewareGroup('web', [
<add> 'RouteTestControllerMiddleware',
<add> 'RouteTestControllerMiddlewareTwo',
<add> ]);
<add>
<add> $router->get('foo/bar', 'RouteTestControllerMiddlewareGroupStub@index');
<add>
<add> $this->assertEquals('caught', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
<add> $this->assertTrue($_SERVER['route.test.controller.middleware']);
<add> $this->assertEquals('Illuminate\Http\Response', $_SERVER['route.test.controller.middleware.class']);
<add> }
<add>
<ide> public function testControllerInspection()
<ide> {
<ide> $router = $this->getRouter();
<ide> public function index()
<ide> }
<ide> }
<ide>
<add>class RouteTestControllerMiddlewareGroupStub extends Illuminate\Routing\Controller
<add>{
<add> public function __construct()
<add> {
<add> $this->middleware('web');
<add> }
<add>
<add> public function index()
<add> {
<add> return 'Hello World';
<add> }
<add>}
<add>
<ide> class RouteTestControllerMiddleware
<ide> {
<ide> public function handle($request, $next)
<ide> public function handle($request, $next)
<ide> }
<ide> }
<ide>
<add>class RouteTestControllerMiddlewareTwo
<add>{
<add> public function handle($request, $next)
<add> {
<add> return new \Illuminate\Http\Response('caught');
<add> }
<add>}
<add>
<ide> class RouteTestControllerParameterizedMiddlewareOne
<ide> {
<ide> public function handle($request, $next, $parameter) | 4 |
Text | Text | remove extra word and translation | 74057447acc2382af0a2bfeb9caf7dfa39b01324 | <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.chinese.md
<ide> localeTitle: 探索var和let关键字之间的差异
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">使用<code>var</code>关键字声明变量的最大问题之一是您可以在没有错误的情况下覆盖变量声明。 <blockquote> var camper ='詹姆斯'; <br> var camper ='大卫'; <br>的console.log(野营车); <br> //记录'大卫' </blockquote>正如您在上面的代码中看到的那样, <code>camper</code>变量最初被声明为<code>James</code> ,然后被重写为<code>David</code> 。在小型应用程序中,您可能不会遇到此类问题,但是当您的代码变大时,您可能会意外覆盖您不打算覆盖的变量。因为这种行为不会引发错误,所以搜索和修复错误变得更加困难。 <br>在ES6中引入了一个名为<code>let</code>的新关键字,用<code>var</code>关键字解决了这个潜在的问题。如果要在上面代码的变量声明中用<code>let</code>替换<code>var</code> ,结果将是一个错误。 <blockquote>让露营者='詹姆斯'; <br>让露营者='大卫'; //抛出错误</blockquote>您可以在浏览器的控制台中看到此错误。因此与<code>var</code>不同,使用<code>let</code> ,具有相同名称的变量只能声明一次。注意<code>"use strict"</code> 。这启用了严格模式,可以捕获常见的编码错误和“不安全”操作。例如: <blockquote> “严格使用”; <br> x = 3.14; //因为未声明x而抛出错误</blockquote></section>
<add><section id="description">使用<code>var</code>关键字声明变量的最大问题之一是您可以在没有错误的情况下覆盖变量声明。 <blockquote> var camper ='詹姆斯'; <br> var camper ='大卫'; <br>console.log(野营车); <br> //记录'大卫' </blockquote>正如您在上面的代码中看到的那样, <code>camper</code>变量最初被声明为<code>James</code> ,然后被重写为<code>David</code> 。在小型应用程序中,您可能不会遇到此类问题,但是当您的代码变大时,您可能会意外覆盖您不打算覆盖的变量。因为这种行为不会引发错误,所以搜索和修复错误变得更加困难。 <br>在ES6中引入了一个名为<code>let</code>的新关键字,用<code>var</code>关键字解决了这个潜在的问题。如果要在上面代码的变量声明中用<code>let</code>替换<code>var</code> ,结果将是一个错误。 <blockquote>let camper='詹姆斯'; <br>let camper='大卫'; //抛出错误</blockquote>您可以在浏览器的控制台中看到此错误。因此与<code>var</code>不同,使用<code>let</code> ,具有相同名称的变量只能声明一次。注意<code>"use strict"</code> 。这启用了严格模式,可以捕获常见的编码错误和“不安全”操作。例如: <blockquote> “严格使用”; <br> x = 3.14; //因为未声明x而抛出错误</blockquote></section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">更新代码,使其仅使用<code>let</code>关键字。 </section> | 1 |
Python | Python | add seperated class for resnet 50 101 152 | e649274ea724d476cdc76ed01624dd9378d27a08 | <ide><path>research/object_detection/models/faster_rcnn_resnet_v1_fpn_keras_feature_extractor.py
<ide> class FasterRCNNResnetV1FPNKerasFeatureExtractor(
<ide>
<ide> def __init__(self,
<ide> is_training,
<add> resnet_v1_base_model,
<add> resnet_v1_base_model_name,
<ide> first_stage_features_stride,
<ide> conv_hyperparams,
<ide> min_depth,
<ide> depth_multiplier,
<del> resnet_v1_base_model,
<del> resnet_v1_base_model_name,
<ide> batch_norm_trainable=False,
<ide> weight_decay=0.0,
<ide> fpn_min_level=3,
<ide> def get_proposal_feature_extractor_model(self, name=None):
<ide> # return feature_maps
<ide>
<ide> def get_box_classifier_feature_extractor_model(self, name=None):
<add>
<add>
<add>
<add>class FasterRCNNResnet50FPNKerasFeatureExtractor(
<add> FasterRCNNResnetV1FPNKerasFeatureExtractor):
<add> """Faster RCNN with Resnet50 FPN feature extractor implementation."""
<add>
<add> def __init__(self,
<add> is_training,
<add> first_stage_features_stride=16,
<add> conv_hyperparams=None,
<add> min_depth=16,
<add> depth_multiplier=1,
<add> batch_norm_trainable=False,
<add> weight_decay=0.0,
<add> fpn_min_level=3,
<add> fpn_max_level=7,
<add> additional_layer_depth=256,
<add> override_base_feature_extractor_hyperparams=False):
<add> """Constructor.
<add>
<add> Args:
<add> is_training: See base class.
<add> first_stage_features_stride: See base class.
<add> conv_hyperparams: See base class.
<add> min_depth: See base class.
<add> depth_multiplier: See base class.
<add> batch_norm_trainable: See base class.
<add> weight_decay: See base class.
<add> fpn_min_level: See base class.
<add> fpn_max_level: See base class.
<add> additional_layer_depth: See base class.
<add> override_base_feature_extractor_hyperparams: See base class.
<add> """
<add> super(FasterRCNNResnet50KerasFeatureExtractor, self).__init__(
<add> is_training=is_training,
<add> first_stage_features_stride=first_stage_features_stride,
<add> conv_hyperparams=conv_hyperparameters,
<add> min_depth=min_depth,
<add> depth_multiplier=depth_multiplier,
<add> resnet_v1_base_model=resnet_v1.resnet_v1_50,
<add> resnet_v1_base_model_name='resnet_v1_50',
<add> batch_norm_trainable=batch_norm_trainable,
<add> weight_decay=weight_decay,
<add> fpn_min_level=fpn_min_level,
<add> fpn_max_level=fpn_max_level,
<add> additional_layer_depth=additional_layer_depth,
<add> override_base_feature_extractor_hyperparams=override_base_feature_extractor_hyperparams)
<add>
<add>class FasterRCNNResnet101FPNKerasFeatureExtractor(
<add> FasterRCNNResnetV1FPNKerasFeatureExtractor):
<add> """Faster RCNN with Resnet101 FPN feature extractor implementation."""
<add> def __init__(self,
<add> is_training,
<add> first_stage_features_stride=16,
<add> conv_hyperparams=None,
<add> min_depth=16,
<add> depth_multiplier=1,
<add> batch_norm_trainable=False,
<add> weight_decay=0.0,
<add> fpn_min_level=3,
<add> fpn_max_level=7,
<add> additional_layer_depth=256,
<add> override_base_feature_extractor_hyperparams=False):
<add> """Constructor.
<add>
<add> Args:
<add> is_training: See base class.
<add> first_stage_features_stride: See base class.
<add> conv_hyperparams: See base class.
<add> min_depth: See base class.
<add> depth_multiplier: See base class.
<add> batch_norm_trainable: See base class.
<add> weight_decay: See base class.
<add> fpn_min_level: See base class.
<add> fpn_max_level: See base class.
<add> additional_layer_depth: See base class.
<add> override_base_feature_extractor_hyperparams: See base class.
<add> """
<add> super(FasterRCNNResnet50KerasFeatureExtractor, self).__init__(
<add> is_training=is_training,
<add> first_stage_features_stride=first_stage_features_stride,
<add> conv_hyperparams=conv_hyperparameters,
<add> min_depth=min_depth,
<add> depth_multiplier=depth_multiplier,
<add> resnet_v1_base_model=resnet_v1.resnet_v1_101,
<add> resnet_v1_base_model_name='resnet_v1_101',
<add> batch_norm_trainable=batch_norm_trainable,
<add> weight_decay=weight_decay,
<add> fpn_min_level=fpn_min_level,
<add> fpn_max_level=fpn_max_level,
<add> additional_layer_depth=additional_layer_depth,
<add> override_base_feature_extractor_hyperparams=override_base_feature_extractor_hyperparams)
<add>
<add>
<add>class FasterRCNNResnet152FPNKerasFeatureExtractor(
<add> FasterRCNNResnetV1FPNKerasFeatureExtractor):
<add> """Faster RCNN with Resnet152 FPN feature extractor implementation."""
<add>
<add> def __init__(self,
<add> is_training,
<add> first_stage_features_stride=16,
<add> conv_hyperparams=None,
<add> min_depth=16,
<add> depth_multiplier=1,
<add> batch_norm_trainable=False,
<add> weight_decay=0.0,
<add> fpn_min_level=3,
<add> fpn_max_level=7,
<add> additional_layer_depth=256,
<add> override_base_feature_extractor_hyperparams=False):
<add> """Constructor.
<add>
<add> Args:
<add> is_training: See base class.
<add> first_stage_features_stride: See base class.
<add> conv_hyperparams: See base class.
<add> min_depth: See base class.
<add> depth_multiplier: See base class.
<add> batch_norm_trainable: See base class.
<add> weight_decay: See base class.
<add> fpn_min_level: See base class.
<add> fpn_max_level: See base class.
<add> additional_layer_depth: See base class.
<add> override_base_feature_extractor_hyperparams: See base class.
<add> """
<add> super(FasterRCNNResnet50KerasFeatureExtractor, self).__init__(
<add> is_training=is_training,
<add> first_stage_features_stride=first_stage_features_stride,
<add> conv_hyperparams=conv_hyperparameters,
<add> min_depth=min_depth,
<add> depth_multiplier=depth_multiplier,
<add> resnet_v1_base_model=resnet_v1.resnet_v1_152,
<add> resnet_v1_base_model_name='resnet_v1_152',
<add> batch_norm_trainable=batch_norm_trainable,
<add> weight_decay=weight_decay,
<add> fpn_min_level=fpn_min_level,
<add> fpn_max_level=fpn_max_level,
<add> additional_layer_depth=additional_layer_depth,
<add> override_base_feature_extractor_hyperparams=override_base_feature_extractor_hyperparams)
<ide>\ No newline at end of file | 1 |
Ruby | Ruby | remove cbmc from github_prerelease_allowlist | c22c6c4a93a4197046108ecb49a2546454e65aef | <ide><path>Library/Homebrew/utils/shared_audits.rb
<ide> def github_release_data(user, repo, tag)
<ide>
<ide> GITHUB_PRERELEASE_ALLOWLIST = {
<ide> "amd-power-gadget" => :all,
<del> "cbmc" => "5.12.6",
<ide> "elm-format" => "0.8.3",
<ide> "gitless" => "0.8.8",
<ide> "infrakit" => "0.5", | 1 |
Text | Text | fix confusing description of stdout/stdin pipe | c3dff2359dbea4f6f0f001421ddeae4ef76b931f | <ide><path>docs/reference/run.md
<ide> You can specify to which of the three standard streams (`STDIN`, `STDOUT`,
<ide> For interactive processes (like a shell), you must use `-i -t` together in
<ide> order to allocate a tty for the container process. `-i -t` is often written `-it`
<ide> as you'll see in later examples. Specifying `-t` is forbidden when the client
<del>standard output is redirected or piped, such as in:
<add>is receiving its standard input from a pipe, as in:
<ide>
<ide> $ echo test | docker run -i busybox cat
<ide> | 1 |
Text | Text | add empty line after http request headers | 1f62718f52fd676beabca7b796960d4702b175d1 | <ide><path>curriculum/challenges/english/05-apis-and-microservices/basic-node-and-express/use-body-parser-to-parse-post-requests.md
<ide> From: john@example.com
<ide> User-Agent: someBrowser/1.0
<ide> Content-Type: application/x-www-form-urlencoded
<ide> Content-Length: 20
<add>
<ide> name=John+Doe&age=25
<ide> ```
<ide> | 1 |
Python | Python | remove warning for `full` when dtype is set | 7978f3d422e24d1f92d626d19763e5b87193824e | <ide><path>numpy/core/numeric.py
<ide> def full(shape, fill_value, dtype=None, order='C'):
<ide>
<ide> """
<ide> a = empty(shape, dtype, order)
<del> if array(fill_value).dtype != a.dtype:
<add> if dtype is None and array(fill_value).dtype != a.dtype:
<ide> warnings.warn(
<del> "in the future, full(..., {0!r}) will return an array of {1!r}".
<del> format(fill_value, array(fill_value).dtype), FutureWarning)
<add> "in the future, full({0}, {1!r}) will return an array of {2!r}".
<add> format(shape, fill_value, array(fill_value).dtype), FutureWarning)
<ide> multiarray.copyto(a, fill_value, casting='unsafe')
<ide> return a
<ide>
<ide><path>numpy/core/tests/test_deprecations.py
<ide> import warnings
<ide>
<ide> import numpy as np
<del>from numpy.testing import (run_module_suite, assert_raises,
<del> assert_warns, assert_array_equal, assert_)
<add>from numpy.testing import (
<add> run_module_suite, assert_raises, assert_warns, assert_no_warnings,
<add> assert_array_equal, assert_)
<ide>
<ide>
<ide> class _DeprecationTestCase(object):
<ide> class TestFullDefaultDtype:
<ide> def test_full_default_dtype(self):
<ide> assert_warns(FutureWarning, np.full, 1, 1)
<ide> assert_warns(FutureWarning, np.full, 1, None)
<add> assert_no_warnings(np.full, 1, 1, float)
<ide>
<ide>
<ide> if __name__ == "__main__": | 2 |
Text | Text | add return types and props types to os module | f9c98563da6076d27e5ce44c1a023cce52f46cb5 | <ide><path>doc/api/os.md
<ide> const os = require('os');
<ide> added: v0.7.8
<ide> -->
<ide>
<add>* {String}
<add>
<ide> A string constant defining the operating system-specific end-of-line marker:
<ide>
<ide> * `\n` on POSIX
<ide> Equivalent to [`process.arch`][].
<ide>
<ide> ## os.constants
<ide>
<add>* {Object}
<add>
<ide> Returns an object containing commonly used operating system specific constants
<ide> for error codes, process signals, and so on. The specific constants currently
<ide> defined are described in [OS Constants][].
<ide> defined are described in [OS Constants][].
<ide> added: v0.3.3
<ide> -->
<ide>
<add>* Returns: {Array}
<add>
<ide> The `os.cpus()` method returns an array of objects containing information about
<ide> each CPU/core installed.
<ide>
<ide> all processors are always 0.
<ide> added: v0.9.4
<ide> -->
<ide>
<add>* Returns: {String}
<add>
<ide> The `os.endianness()` method returns a string identifying the endianness of the
<ide> CPU *for which the Node.js binary was compiled*.
<ide>
<ide> Possible values are:
<ide> added: v0.3.3
<ide> -->
<ide>
<add>* Returns: {Integer}
<add>
<ide> The `os.freemem()` method returns the amount of free system memory in bytes as
<ide> an integer.
<ide>
<ide> an integer.
<ide> added: v2.3.0
<ide> -->
<ide>
<add>* Returns: {String}
<add>
<ide> The `os.homedir()` method returns the home directory of the current user as a
<ide> string.
<ide>
<ide> string.
<ide> added: v0.3.3
<ide> -->
<ide>
<add>* Returns: {String}
<add>
<ide> The `os.hostname()` method returns the hostname of the operating system as a
<ide> string.
<ide>
<ide> string.
<ide> added: v0.3.3
<ide> -->
<ide>
<add>* Returns: {Array}
<add>
<ide> The `os.loadavg()` method returns an array containing the 1, 5, and 15 minute
<ide> load averages.
<ide>
<ide> Windows platforms. On Windows, the return value is always `[0, 0, 0]`.
<ide> added: v0.6.0
<ide> -->
<ide>
<add>* Returns: {Object}
<add>
<ide> The `os.networkInterfaces()` method returns an object containing only network
<ide> interfaces that have been assigned a network address.
<ide>
<ide> The properties available on the assigned network address object include:
<ide> added: v0.5.0
<ide> -->
<ide>
<add>* Returns: {String}
<add>
<ide> The `os.platform()` method returns a string identifying the operating system
<ide> platform as set during compile time of Node.js.
<ide>
<ide> to be experimental at this time.
<ide> added: v0.3.3
<ide> -->
<ide>
<add>* Returns: {String}
<add>
<ide> The `os.release()` method returns a string identifying the operating system
<ide> release.
<ide>
<ide> https://en.wikipedia.org/wiki/Uname#Examples for more information.
<ide> added: v0.9.9
<ide> -->
<ide>
<add>* Returns: {String}
<add>
<ide> The `os.tmpdir()` method returns a string specifying the operating system's
<ide> default directory for temporary files.
<ide>
<ide> default directory for temporary files.
<ide> added: v0.3.3
<ide> -->
<ide>
<add>* Returns: {Integer}
<add>
<ide> The `os.totalmem()` method returns the total amount of system memory in bytes
<ide> as an integer.
<ide>
<ide> as an integer.
<ide> added: v0.3.3
<ide> -->
<ide>
<add>* Returns: {String}
<add>
<ide> The `os.type()` method returns a string identifying the operating system name
<ide> as returned by uname(3). For example `'Linux'` on Linux, `'Darwin'` on OS X and
<ide> `'Windows_NT'` on Windows.
<ide> information about the output of running uname(3) on various operating systems.
<ide> added: v0.3.3
<ide> -->
<ide>
<add>* Returns: {Integer}
<add>
<ide> The `os.uptime()` method returns the system uptime in number of seconds.
<ide>
<ide> *Note*: Within Node.js' internals, this number is represented as a `double`.
<ide> added: v6.0.0
<ide> * `encoding` {String} Character encoding used to interpret resulting strings.
<ide> If `encoding` is set to `'buffer'`, the `username`, `shell`, and `homedir`
<ide> values will be `Buffer` instances. (Default: 'utf8')
<add>* Returns: {Object}
<ide>
<ide> The `os.userInfo()` method returns information about the currently effective
<ide> user -- on POSIX platforms, this is typically a subset of the password file. The | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.