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
|
|---|---|---|---|---|---|
Python
|
Python
|
fix documentation of the 1d max pooling layer
|
b6f81c6cc3018553adbdae8e86a09825ac5b9b33
|
<ide><path>keras/layers/pooling.py
<ide> class MaxPooling1D(_Pooling1D):
<ide> 3D tensor with shape: `(samples, downsampled_steps, features)`.
<ide>
<ide> # Arguments
<del> pool_length: factor by which to downscale. 2 will halve the input.
<del> stride: integer, or None. Stride value.
<add> pool_length: size of the region to which max pooling is applied
<add> stride: integer, or None. factor by which to downscale.
<add> 2 will halve the input.
<ide> If None, it will default to `pool_length`.
<ide> border_mode: 'valid' or 'same'.
<ide> Note: 'same' will only work with TensorFlow for the time being.
| 1
|
Javascript
|
Javascript
|
fix minor typo in scrollview doc
|
f66c8f2f7eba1b6f293c91e7319ce8baf1ca4b42
|
<ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> const ScrollView = createReactClass({
<ide> * When false, the view cannot be scrolled via touch interaction.
<ide> * The default value is true.
<ide> *
<del> * Note that the view can be always be scrolled by calling `scrollTo`.
<add> * Note that the view can always be scrolled by calling `scrollTo`.
<ide> */
<ide> scrollEnabled: PropTypes.bool,
<ide> /**
| 1
|
Python
|
Python
|
update docstrings of np.sum and np.prod
|
4626b59a490bb5f35830a7b6bb74853a9c14aa63
|
<ide><path>numpy/core/fromnumeric.py
<ide> def sum(a, axis=None, dtype=None, out=None, keepdims=False):
<ide> Elements to sum.
<ide> axis : None or int or tuple of ints, optional
<ide> Axis or axes along which a sum is performed.
<del> The default (`axis` = `None`) is perform a sum over all
<del> the dimensions of the input array. `axis` may be negative, in
<add> The default (`axis` = `None`) will sum all of the elements
<add> of the input array. `axis` may be negative, in
<ide> which case it counts from the last to the first axis.
<add> `axis` = 0 or 1 will sum over the elements of the
<add> columns or rows of the input array.
<ide>
<ide> .. versionadded:: 1.7.0
<ide>
<ide> def prod(a, axis=None, dtype=None, out=None, keepdims=False):
<ide> Input data.
<ide> axis : None or int or tuple of ints, optional
<ide> Axis or axes along which a product is performed.
<del> The default (`axis` = `None`) is perform a product over all
<del> the dimensions of the input array. `axis` may be negative, in
<add> The default (`axis` = `None`) will calculate the product
<add> of all the elements in the input array. `axis` may be negative, in
<ide> which case it counts from the last to the first axis.
<ide>
<ide> .. versionadded:: 1.7.0
| 1
|
PHP
|
PHP
|
update use of deprecated phpunit method
|
f6966cd9eeef459bd3c153b30fd2fbf724869200
|
<ide><path>tests/TestCase/Auth/ControllerAuthorizeTest.php
<ide> public function setUp(): void
<ide> {
<ide> parent::setUp();
<ide> $this->controller = $this->getMockBuilder(Controller::class)
<del> ->setMethods(['isAuthorized'])
<add> ->addMethods(['isAuthorized'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $this->components = new ComponentRegistry($this->controller);
<ide><path>tests/TestCase/Auth/FormAuthenticateTest.php
<ide> public function testAuthenticatePasswordIsEmptyString(): void
<ide> ]);
<ide>
<ide> $this->auth = $this->getMockBuilder(FormAuthenticate::class)
<del> ->setMethods(['_checkFields'])
<add> ->onlyMethods(['_checkFields'])
<ide> ->setConstructorArgs([
<ide> $this->collection,
<ide> ['userModel' => 'Users'],
<ide><path>tests/TestCase/Collection/CollectionTest.php
<ide> public function testEach()
<ide> $items = ['a' => 1, 'b' => 2, 'c' => 3];
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide> $callable->expects($this->at(0))
<ide> ->method('__invoke')
<ide> public function testFilterChaining()
<ide> $items = ['a' => 1, 'b' => 2, 'c' => 3];
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->once())
<ide> public function testEveryReturnTrue()
<ide> $items = ['a' => 1, 'b' => 2, 'c' => 3];
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->at(0))
<ide> public function testEveryReturnFalse()
<ide> $items = ['a' => 1, 'b' => 2, 'c' => 3];
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->at(0))
<ide> public function testEveryReturnFalse()
<ide> $items = [];
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->never())
<ide> public function testSomeReturnTrue()
<ide> $items = ['a' => 1, 'b' => 2, 'c' => 3];
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->at(0))
<ide> public function testSomeReturnFalse()
<ide> $items = ['a' => 1, 'b' => 2, 'c' => 3];
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->at(0))
<ide> public function testReduceWithInitialValue($items)
<ide> {
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->at(0))
<ide> public function testReduceWithoutInitialValue($items)
<ide> {
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->at(0))
<ide> public function testCompile()
<ide> $items = ['a' => 1, 'b' => 2, 'c' => 3];
<ide> $collection = new Collection($items);
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->at(0))
<ide> public function testLazy()
<ide> $items = ['a' => 1, 'b' => 2, 'c' => 3];
<ide> $collection = (new Collection($items))->lazy();
<ide> $callable = $this->getMockBuilder(stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide>
<ide> $callable->expects($this->never())->method('__invoke');
<ide><path>tests/TestCase/Collection/Iterator/FilterIteratorTest.php
<ide> public function testFilter()
<ide> {
<ide> $items = new \ArrayIterator([1, 2, 3]);
<ide> $callable = $this->getMockBuilder(\stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide> $callable->expects($this->at(0))
<ide> ->method('__invoke')
<ide><path>tests/TestCase/Collection/Iterator/ReplaceIteratorTest.php
<ide> public function testReplace()
<ide> {
<ide> $items = new \ArrayIterator([1, 2, 3]);
<ide> $callable = $this->getMockBuilder(\stdClass::class)
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide> $callable->expects($this->at(0))
<ide> ->method('__invoke')
<ide><path>tests/TestCase/Command/PluginAssetsCommandsTest.php
<ide> public function testSymlinkWhenTargetAlreadyExits()
<ide> $output = new ConsoleOutput();
<ide> $io = $this->getMockBuilder(ConsoleIo::class)
<ide> ->setConstructorArgs([$output, $output, null, null])
<del> ->setMethods(['in'])
<add> ->addMethods(['in'])
<ide> ->getMock();
<ide> $parser = new ConsoleOptionParser('cake example');
<ide> $parser->addArgument('name', ['optional' => true]);
<ide> $parser->addOption('overwrite', ['default' => false, 'boolean' => true]);
<ide>
<ide> $command = $this->getMockBuilder('Cake\Command\PluginAssetsSymlinkCommand')
<del> ->setMethods(['getOptionParser', '_createSymlink', '_copyDirectory'])
<add> ->onlyMethods(['getOptionParser', '_createSymlink', '_copyDirectory'])
<ide> ->getMock();
<ide> $command->method('getOptionParser')->will($this->returnValue($parser));
<ide>
<ide><path>tests/TestCase/Command/SchemaCacheCommandsTest.php
<ide> public function setUp(): void
<ide> $this->useCommandRunner();
<ide>
<ide> $this->cache = $this->getMockBuilder(NullEngine::class)
<del> ->setMethods(['set', 'get', 'delete'])
<add> ->onlyMethods(['set', 'get', 'delete'])
<ide> ->getMock();
<ide> Cache::setConfig('orm_cache', $this->cache);
<ide>
<ide> protected function getShell()
<ide> $io = $this->getMockBuilder(ConsoleIo::class)->getMock();
<ide> $shell = $this->getMockBuilder(SchemaCacheShell::class)
<ide> ->setConstructorArgs([$io])
<del> ->setMethods(['_getSchemaCache'])
<add> ->onlyMethods(['_getSchemaCache'])
<ide> ->getMock();
<ide>
<ide> $schemaCache = new SchemaCache($this->connection);
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> public function testRunMissingRootCommand()
<ide> $this->expectException(\RuntimeException::class);
<ide> $this->expectExceptionMessage('Cannot run any commands. No arguments received.');
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunMissingRootCommand()
<ide> public function testRunInvalidCommand()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunInvalidCommand()
<ide> public function testRunInvalidCommandSuggestion()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunInvalidCommandSuggestion()
<ide> public function testRunHelpLongOption()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunHelpLongOption()
<ide> public function testRunHelpShortOption()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunHelpShortOption()
<ide> public function testRunNoCommand()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunNoCommand()
<ide> public function testRunVersionAlias()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunVersionAlias()
<ide> public function testRunValidCommand()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunValidCommand()
<ide> public function testRunValidCommandInflection()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunValidCommandClassHelp()
<ide> public function testRunTriggersBuildCommandsEvent()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide>
<ide> public function testRunTriggersBuildCommandsEvent()
<ide> public function testRunCallsPluginHookMethods()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods([
<add> ->onlyMethods([
<ide> 'middleware', 'bootstrap', 'routes',
<ide> 'pluginBootstrap', 'pluginConsole', 'pluginRoutes',
<ide> ])
<ide> public function testRunCallsPluginHookMethods()
<ide> public function testRunLoadsRoutes()
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap'])
<add> ->onlyMethods(['middleware', 'bootstrap'])
<ide> ->setConstructorArgs([TEST_APP . 'config' . DS])
<ide> ->getMock();
<ide>
<ide> public function testRunLoadsRoutes()
<ide> protected function makeAppWithCommands($commands)
<ide> {
<ide> $app = $this->getMockBuilder(BaseApplication::class)
<del> ->setMethods(['middleware', 'bootstrap', 'console', 'routes'])
<add> ->onlyMethods(['middleware', 'bootstrap', 'console', 'routes'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide> $collection = new CommandCollection($commands);
<ide> protected function getMockIo($output)
<ide> {
<ide> $io = $this->getMockBuilder(ConsoleIo::class)
<ide> ->setConstructorArgs([$output, $output, null, null])
<del> ->setMethods(['in'])
<add> ->addMethods(['in'])
<ide> ->getMock();
<ide>
<ide> return $io;
<ide><path>tests/TestCase/Console/CommandTest.php
<ide> public function testRunCallsInitialize()
<ide> {
<ide> /** @var \Cake\Console\Command|\PHPUnit\Framework\MockObject\MockObject $command */
<ide> $command = $this->getMockBuilder(Command::class)
<del> ->setMethods(['initialize'])
<add> ->onlyMethods(['initialize'])
<ide> ->getMock();
<ide> $command->setName('cake example');
<ide> $command->expects($this->once())->method('initialize');
<ide> public function testRunOptionParserFailure()
<ide> {
<ide> /** @var \Cake\Console\Command|\PHPUnit\Framework\MockObject\MockObject $command */
<ide> $command = $this->getMockBuilder(Command::class)
<del> ->setMethods(['getOptionParser'])
<add> ->onlyMethods(['getOptionParser'])
<ide> ->getMock();
<ide> $parser = new ConsoleOptionParser('cake example');
<ide> $parser->addArgument('name', ['required' => true]);
<ide> protected function getMockIo($output)
<ide> {
<ide> $io = $this->getMockBuilder(ConsoleIo::class)
<ide> ->setConstructorArgs([$output, $output, null, null])
<del> ->setMethods(['in'])
<add> ->addMethods(['in'])
<ide> ->getMock();
<ide>
<ide> return $io;
<ide><path>tests/TestCase/Console/ConsoleOutputTest.php
<ide> public function setUp(): void
<ide> {
<ide> parent::setUp();
<ide> $this->output = $this->getMockBuilder(ConsoleOutput::class)
<del> ->setMethods(['_write'])
<add> ->onlyMethods(['_write'])
<ide> ->getMock();
<ide> $this->output->setOutputAs(ConsoleOutput::COLOR);
<ide> }
<ide><path>tests/TestCase/Console/ShellDispatcherTest.php
<ide> public function setUp(): void
<ide> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']);
<ide> static::setAppNamespace();
<ide> $this->dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['_stop'])
<add> ->addMethods(['_stop'])
<ide> ->getMock();
<ide> }
<ide>
<ide> public function testDispatchShellWithAbort()
<ide> {
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['main'])
<add> ->addMethods(['main'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide> $shell->expects($this->once())
<ide> public function testDispatchShellWithAbort()
<ide> }));
<ide>
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['findShell'])
<add> ->onlyMethods(['findShell'])
<ide> ->getMock();
<ide> $dispatcher->expects($this->any())
<ide> ->method('findShell')
<ide> public function testDispatchShellWithAbort()
<ide> public function testDispatchShellWithMain()
<ide> {
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['findShell'])
<add> ->onlyMethods(['findShell'])
<ide> ->getMock();
<ide> $Shell = $this->getMockBuilder('Cake\Console\Shell')
<ide> ->disableOriginalConstructor()
<ide> public function testDispatchShellWithMain()
<ide> public function testDispatchShellWithIntegerSuccessCode()
<ide> {
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['findShell'])
<add> ->onlyMethods(['findShell'])
<ide> ->getMock();
<ide> $Shell = $this->getMockBuilder('Cake\Console\Shell')
<ide> ->disableOriginalConstructor()
<ide> public function testDispatchShellWithCustomIntegerCodes()
<ide> $customErrorCode = 3;
<ide>
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['findShell'])
<add> ->onlyMethods(['findShell'])
<ide> ->getMock();
<ide> $Shell = $this->getMockBuilder('Cake\Console\Shell')
<ide> ->disableOriginalConstructor()
<ide> public function testDispatchShellWithCustomIntegerCodes()
<ide> public function testDispatchShellWithoutMain()
<ide> {
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['findShell'])
<add> ->onlyMethods(['findShell'])
<ide> ->getMock();
<ide> $Shell = $this->getMockBuilder('Cake\Console\Shell')
<ide> ->disableOriginalConstructor()
<ide> public function testDispatchShellWithoutMain()
<ide> public function testDispatchShortPluginAlias()
<ide> {
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['_shellExists', '_createShell'])
<add> ->onlyMethods(['_shellExists', '_createShell'])
<ide> ->getMock();
<ide> $Shell = $this->getMockBuilder('Cake\Console\Shell')
<ide> ->disableOriginalConstructor()
<ide> public function testDispatchShortPluginAlias()
<ide> public function testDispatchShortPluginAliasCamelized()
<ide> {
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['_shellExists', '_createShell'])
<add> ->onlyMethods(['_shellExists', '_createShell'])
<ide> ->getMock();
<ide> $Shell = $this->getMockBuilder('Cake\Console\Shell')
<ide> ->disableOriginalConstructor()
<ide> public function testDispatchShortPluginAliasCamelized()
<ide> public function testDispatchShortPluginAliasConflict()
<ide> {
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['_shellExists', '_createShell'])
<add> ->onlyMethods(['_shellExists', '_createShell'])
<ide> ->getMock();
<ide> $Shell = $this->getMockBuilder('Cake\Console\Shell')
<ide> ->disableOriginalConstructor()
<ide> public function testHelpOption()
<ide> {
<ide> $this->expectException(Warning::class);
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['_stop'])
<add> ->addMethods(['_stop'])
<ide> ->getMock();
<ide> $dispatcher->args = ['--help'];
<ide> $dispatcher->dispatch();
<ide> public function testVersionOption()
<ide> {
<ide> $this->expectException(Warning::class);
<ide> $dispatcher = $this->getMockBuilder('Cake\Console\ShellDispatcher')
<del> ->setMethods(['_stop'])
<add> ->addMethods(['_stop'])
<ide> ->getMock();
<ide> $dispatcher->args = ['--version'];
<ide> $dispatcher->dispatch();
<ide><path>tests/TestCase/Console/ShellTest.php
<ide> public function testRunCommandMain()
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> /** @var \Cake\Console\Shell|\PHPUnit\Framework\MockObject\MockObject $shell */
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['main', 'startup'])
<add> ->onlyMethods(['startup'])
<add> ->addMethods(['main'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide>
<ide> public function testRunCommandWithMethod()
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> /** @var \Cake\Console\Shell|\PHPUnit\Framework\MockObject\MockObject $shell */
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['hitMe', 'startup'])
<add> ->onlyMethods(['startup'])
<add> ->addMethods(['hitMe'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide>
<ide> public function testRunCommandWithMethod()
<ide> public function testRunCommandWithExtra()
<ide> {
<ide> $Parser = $this->getMockBuilder('Cake\Console\ConsoleOptionParser')
<del> ->setMethods(['help'])
<add> ->onlyMethods(['help'])
<ide> ->setConstructorArgs(['knife'])
<ide> ->getMock();
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> $Shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['getOptionParser', 'slice', '_welcome', 'param'])
<add> ->onlyMethods(['getOptionParser', '_welcome', 'param'])
<add> ->addMethods(['slice'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide> $Parser->addSubCommand('slice');
<ide> public function testRunCommandAutoMethodOff()
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> /** @var \Cake\Console\Shell|\PHPUnit\Framework\MockObject\MockObject $shell */
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['hit_me', 'startup'])
<add> ->onlyMethods(['startup'])
<add> ->addMethods(['hit_me'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide>
<ide> public function testRunCommandAutoMethodOff()
<ide> public function testRunCommandWithMethodNotInSubcommands()
<ide> {
<ide> $parser = $this->getMockBuilder('Cake\Console\ConsoleOptionParser')
<del> ->setMethods(['help'])
<add> ->onlyMethods(['help'])
<ide> ->setConstructorArgs(['knife'])
<ide> ->getMock();
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['getOptionParser', 'roll', 'startup'])
<add> ->onlyMethods(['getOptionParser', 'startup'])
<add> ->addMethods(['roll'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide>
<ide> public function testRunCommandWithMethodNotInSubcommands()
<ide> public function testRunCommandWithMethodInSubcommands()
<ide> {
<ide> $parser = $this->getMockBuilder('Cake\Console\ConsoleOptionParser')
<del> ->setMethods(['help'])
<add> ->onlyMethods(['help'])
<ide> ->setConstructorArgs(['knife'])
<ide> ->getMock();
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['getOptionParser', 'slice', 'startup'])
<add> ->onlyMethods(['getOptionParser', 'startup'])
<add> ->addMethods(['slice'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide>
<ide> public function testRunCommandWithMissingMethodInSubcommands()
<ide> {
<ide> /** @var \Cake\Console\ConsoleOptionParser|\PHPUnit\Framework\MockObject\MockObject $parser */
<ide> $parser = $this->getMockBuilder('Cake\Console\ConsoleOptionParser')
<del> ->setMethods(['help'])
<add> ->onlyMethods(['help'])
<ide> ->setConstructorArgs(['knife'])
<ide> ->getMock();
<ide> $parser->addSubCommand('slice');
<ide>
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> /** @var \Cake\Console\Shell|\PHPUnit\Framework\MockObject\MockObject $shell */
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['getOptionParser', 'startup'])
<add> ->onlyMethods(['getOptionParser', 'startup'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide> $shell->expects($this->any())
<ide> public function testRunCommandBaseClassMethod()
<ide> {
<ide> /** @var \Cake\Console\Shell|\PHPUnit\Framework\MockObject\MockObject $shell */
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['startup', 'getOptionParser', 'hr'])
<add> ->onlyMethods(['startup', 'getOptionParser', 'hr'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $shell->setIo(
<ide> $this->getMockBuilder('Cake\Console\ConsoleIo')
<del> ->setMethods(['err'])
<add> ->onlyMethods(['err'])
<ide> ->getMock()
<ide> );
<ide> $parser = $this->getMockBuilder('Cake\Console\ConsoleOptionParser')
<ide> public function testRunCommandMissingMethod()
<ide> {
<ide> /** @var \Cake\Console\Shell|\PHPUnit\Framework\MockObject\MockObject $shell */
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['startup', 'getOptionParser', 'hr'])
<add> ->onlyMethods(['startup', 'getOptionParser', 'hr'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $shell->setIo(
<ide> $this->getMockBuilder('Cake\Console\ConsoleIo')
<del> ->setMethods(['err'])
<add> ->onlyMethods(['err'])
<ide> ->getMock()
<ide> );
<ide> $parser = $this->getMockBuilder('Cake\Console\ConsoleOptionParser')
<ide> public function testRunCommandTriggeringHelp()
<ide> $parser->expects($this->once())->method('help');
<ide>
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['getOptionParser', 'out', 'startup', '_welcome'])
<add> ->onlyMethods(['getOptionParser', 'out', 'startup', '_welcome'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $shell->setIo($this->getMockBuilder('Cake\Console\ConsoleIo')->getMock());
<ide> public function testRunCommandNotCallUnexposedTask()
<ide> {
<ide> /** @var \Cake\Console\Shell|\PHPUnit\Framework\MockObject\MockObject $shell */
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['startup', 'hasTask'])
<add> ->onlyMethods(['startup', 'hasTask'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $shell->setIo(
<ide> $this->getMockBuilder('Cake\Console\ConsoleIo')
<del> ->setMethods(['err'])
<add> ->onlyMethods(['err'])
<ide> ->getMock()
<ide> );
<ide> $task = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['runCommand'])
<add> ->onlyMethods(['runCommand'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide>
<ide> public function testRunCommandHittingTaskInSubcommand()
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide>
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['hasTask', 'startup', 'getOptionParser'])
<add> ->onlyMethods(['hasTask', 'startup', 'getOptionParser'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $shell->setIo($io);
<ide> $task = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['main', 'runCommand'])
<add> ->onlyMethods(['runCommand'])
<add> ->addMethods(['main'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $task->setIo($io);
<ide> public function testRunCommandInvokeTask()
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide>
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['hasTask', 'getOptionParser'])
<add> ->onlyMethods(['hasTask', 'getOptionParser'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide> $task = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['main', '_welcome'])
<add> ->onlyMethods(['_welcome'])
<add> ->addMethods(['main'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide>
<ide> public function testRunCommandMainMissingArgument()
<ide> {
<ide> $io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();
<ide> $shell = $this->getMockBuilder('Cake\Console\Shell')
<del> ->setMethods(['main', 'startup', 'getOptionParser'])
<add> ->onlyMethods(['startup', 'getOptionParser'])
<add> ->addMethods(['main'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide>
<ide> public function testQuietLog()
<ide> ->with(ConsoleIo::QUIET);
<ide>
<ide> $this->Shell = $this->getMockBuilder(ShellTestShell::class)
<del> ->setMethods(['welcome'])
<add> ->addMethods(['welcome'])
<ide> ->setConstructorArgs([$io])
<ide> ->getMock();
<ide> $this->Shell->runCommand(['foo', '--quiet']);
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testNoAuth(): void
<ide> public function testIdentify(): void
<ide> {
<ide> $AuthLoginFormAuthenticate = $this->getMockBuilder(FormAuthenticate::class)
<del> ->setMethods(['authenticate'])
<add> ->onlyMethods(['authenticate'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $this->Auth->authenticate = [
<ide> public function testIdentify(): void
<ide> public function testIdentifyArrayAccess(): void
<ide> {
<ide> $AuthLoginFormAuthenticate = $this->getMockBuilder(FormAuthenticate::class)
<del> ->setMethods(['authenticate'])
<add> ->onlyMethods(['authenticate'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $this->Auth->authenticate = [
<ide> public function testIsAuthorizedMissingFile(): void
<ide> public function testIsAuthorizedDelegation(): void
<ide> {
<ide> $AuthMockOneAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<del> ->setMethods(['authorize'])
<add> ->onlyMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $AuthMockTwoAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<del> ->setMethods(['authorize'])
<add> ->onlyMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $AuthMockThreeAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<del> ->setMethods(['authorize'])
<add> ->onlyMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide>
<ide> public function testIsAuthorizedDelegation(): void
<ide> public function testIsAuthorizedWithArrayObject(): void
<ide> {
<ide> $AuthMockOneAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<del> ->setMethods(['authorize'])
<add> ->onlyMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide>
<ide> public function testIsAuthorizedWithArrayObject(): void
<ide> public function testIsAuthorizedUsingUserInSession(): void
<ide> {
<ide> $AuthMockFourAuthorize = $this->getMockBuilder(BaseAuthorize::class)
<del> ->setMethods(['authorize'])
<add> ->onlyMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $this->Auth->setConfig('authorize', ['AuthMockFour']);
<ide> public function testNoLoginRedirectForAuthenticatedUser(): void
<ide> $this->Auth->getController()->getRequest()->getSession()->write('Auth.User.id', '1');
<ide> $this->Auth->setConfig('authenticate', ['Form']);
<ide> $this->getMockBuilder(BaseAuthorize::class)
<del> ->setMethods(['authorize'])
<add> ->onlyMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->setMockClassName('NoLoginRedirectMockAuthorize')
<ide> ->getMock();
<ide> public function testDefaultToLoginRedirect(): void
<ide>
<ide> $response = new Response();
<ide> $Controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['on', 'redirect'])
<add> ->onlyMethods(['redirect'])
<add> ->addMethods(['on'])
<ide> ->setConstructorArgs([$request, $response])
<ide> ->getMock();
<ide> $event = new Event('Controller.startup', $Controller);
<ide> public function testRedirectToUnauthorizedRedirect(): void
<ide> {
<ide> $url = '/party/on';
<ide> $this->Auth->Flash = $this->getMockBuilder('Cake\Controller\Component\FlashComponent')
<del> ->setMethods(['set'])
<add> ->onlyMethods(['set'])
<ide> ->setConstructorArgs([$this->Controller->components()])
<ide> ->getMock();
<ide> $request = new ServerRequest([
<ide> public function testRedirectToUnauthorizedRedirect(): void
<ide>
<ide> $response = new Response();
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['on', 'redirect'])
<add> ->onlyMethods(['redirect'])
<add> ->addMethods(['on'])
<ide> ->setConstructorArgs([$request, $response])
<ide> ->getMock();
<ide>
<ide> public function testRedirectToUnauthorizedRedirectLoginAction(): void
<ide> {
<ide> $url = '/party/on';
<ide> $this->Auth->Flash = $this->getMockBuilder('Cake\Controller\Component\FlashComponent')
<del> ->setMethods(['set'])
<add> ->onlyMethods(['set'])
<ide> ->setConstructorArgs([$this->Controller->components()])
<ide> ->getMock();
<ide> $request = new ServerRequest([
<ide> public function testRedirectToUnauthorizedRedirectLoginAction(): void
<ide>
<ide> $response = new Response();
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['on', 'redirect'])
<add> ->onlyMethods(['redirect'])
<add> ->addMethods(['on'])
<ide> ->setConstructorArgs([$request, $response])
<ide> ->getMock();
<ide>
<ide> public function testRedirectToUnauthorizedRedirectSuppressedAuthError(): void
<ide> {
<ide> $url = '/party/on';
<ide> $session = $this->getMockBuilder(Session::class)
<del> ->setMethods(['flash'])
<add> ->addMethods(['flash'])
<ide> ->getMock();
<ide> $request = new ServerRequest([
<ide> 'session' => $session,
<ide> public function testRedirectToUnauthorizedRedirectSuppressedAuthError(): void
<ide>
<ide> $response = new Response();
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['on', 'redirect'])
<add> ->onlyMethods(['redirect'])
<add> ->addMethods(['on'])
<ide> ->setConstructorArgs([$request, $response])
<ide> ->getMock();
<ide>
<ide> public function testForbiddenException(): void
<ide> ->withRequestTarget('/party/on');
<ide> $response = new Response();
<ide> $Controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['on', 'redirect'])
<add> ->onlyMethods(['redirect'])
<add> ->addMethods(['on'])
<ide> ->setConstructorArgs([$request, $response])
<ide> ->getMock();
<ide>
<ide> public function testNoRedirectOnLoginAction(): void
<ide> {
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['redirect'])
<add> ->onlyMethods(['redirect'])
<ide> ->getMock();
<ide> $controller->methods = ['login'];
<ide>
<ide> public function testAfterIdentifyForStatelessAuthentication(): void
<ide> public function testSetUser(): void
<ide> {
<ide> $storage = $this->getMockBuilder('Cake\Auth\Storage\SessionStorage')
<del> ->setMethods(['write'])
<add> ->onlyMethods(['write'])
<ide> ->setConstructorArgs([$this->Controller->getRequest(), $this->Controller->getResponse()])
<ide> ->getMock();
<ide> $this->Auth->storage($storage);
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> public function testPaginateQueryWithLimit(): void
<ide> protected function _getMockPosts(array $methods = [])
<ide> {
<ide> return $this->getMockBuilder('TestApp\Model\Table\PaginatorPostsTable')
<del> ->setMethods($methods)
<add> ->onlyMethods($methods)
<ide> ->setConstructorArgs([[
<ide> 'connection' => ConnectionManager::get('test'),
<ide> 'alias' => 'PaginatorPosts',
<ide> protected function _getMockFindQuery(?RepositoryInterface $table = null)
<ide> {
<ide> /** @var \Cake\ORM\Query|\PHPUnit\Framework\MockObject\MockObject $query */
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['total', 'all', 'count', 'applyOptions'])
<add> ->onlyMethods(['all', 'count', 'applyOptions'])
<add> ->addMethods(['total'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide>
<ide> protected function _getMockFindQuery(?RepositoryInterface $table = null)
<ide> protected function getMockRepository()
<ide> {
<ide> $model = $this->getMockBuilder(RepositoryInterface::class)
<del> ->setMethods([
<add> ->onlyMethods([
<ide> 'getAlias', 'setAlias', 'setRegistryAlias', 'getRegistryAlias', 'hasField',
<ide> 'find', 'get', 'query', 'updateAll', 'deleteAll', 'newEmptyEntity',
<ide> 'exists', 'save', 'delete', 'newEntity', 'newEntities', 'patchEntity', 'patchEntities',
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testConstructorConfig(): void
<ide> ];
<ide> /** @var \Cake\Controller\Controller|\PHPUnit\Framework\MockObject\MockObject $controller */
<ide> $controller = $this->getMockBuilder(Controller::class)
<del> ->setMethods(['redirect'])
<add> ->onlyMethods(['redirect'])
<ide> ->getMock();
<ide> $collection = new ComponentRegistry($controller);
<ide> $requestHandler = new RequestHandlerComponent($collection, $config);
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testReferer(): void
<ide> $this->assertSame('/posts/index', $result);
<ide>
<ide> $request = $this->getMockBuilder('Cake\Http\ServerRequest')
<del> ->setMethods(['referer'])
<add> ->onlyMethods(['referer'])
<ide> ->getMock();
<ide>
<ide> $request = new ServerRequest([
<ide> public function testComponentsWithCustomRegistry(): void
<ide> $request = new ServerRequest(['url' => '/']);
<ide> $response = new Response();
<ide> $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
<del> ->setMethods(['offsetGet'])
<add> ->addMethods(['offsetGet'])
<ide> ->getMock();
<ide>
<ide> $controller = new TestController($request, $response, null, null, $componentRegistry);
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testDisabledDriver()
<ide> $this->expectException(\Cake\Database\Exception\MissingExtensionException::class);
<ide> $this->expectExceptionMessage('Database driver DriverMock cannot be used due to a missing PHP extension or unmet dependency');
<ide> $mock = $this->getMockBuilder(Mysql::class)
<del> ->setMethods(['enabled'])
<add> ->onlyMethods(['enabled'])
<ide> ->setMockClassName('DriverMock')
<ide> ->getMock();
<ide> $connection = new Connection(['driver' => $mock]);
<ide> public function testQuote()
<ide> public function testQuoteIdentifier()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')
<del> ->setMethods(['enabled'])
<add> ->onlyMethods(['enabled'])
<ide> ->getMock();
<ide> $driver->expects($this->once())
<ide> ->method('enabled')
<ide> public function testLogBeginRollbackTransaction()
<ide>
<ide> $connection = $this
<ide> ->getMockBuilder(Connection::class)
<del> ->setMethods(['connect'])
<add> ->onlyMethods(['connect'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $connection->enableQueryLogging(true);
<ide> public function testLogCommitTransaction()
<ide> {
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['connect'])
<add> ->onlyMethods(['connect'])
<ide> ->setConstructorArgs([['driver' => $driver]])
<ide> ->getMock();
<ide>
<ide> public function testTransactionalSuccess()
<ide> {
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['connect', 'commit', 'begin'])
<add> ->onlyMethods(['connect', 'commit', 'begin'])
<ide> ->setConstructorArgs([['driver' => $driver]])
<ide> ->getMock();
<ide> $connection->expects($this->at(0))->method('begin');
<ide> public function testTransactionalFail()
<ide> {
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['connect', 'commit', 'begin', 'rollback'])
<add> ->onlyMethods(['connect', 'commit', 'begin', 'rollback'])
<ide> ->setConstructorArgs([['driver' => $driver]])
<ide> ->getMock();
<ide> $connection->expects($this->at(0))->method('begin');
<ide> public function testTransactionalWithException()
<ide> $this->expectException(\InvalidArgumentException::class);
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['connect', 'commit', 'begin', 'rollback'])
<add> ->onlyMethods(['connect', 'commit', 'begin', 'rollback'])
<ide> ->setConstructorArgs([['driver' => $driver]])
<ide> ->getMock();
<ide> $connection->expects($this->at(0))->method('begin');
<ide> public function testSetSchemaCollection()
<ide> {
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['connect'])
<add> ->onlyMethods(['connect'])
<ide> ->setConstructorArgs([['driver' => $driver]])
<ide> ->getMock();
<ide>
<ide> public function testGetCachedCollection()
<ide> {
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['connect'])
<add> ->onlyMethods(['connect'])
<ide> ->setConstructorArgs([[
<ide> 'driver' => $driver,
<ide> 'name' => 'default',
<ide> public function testGetCachedCollection()
<ide>
<ide> $driver = $this->getMockFormDriver();
<ide> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['connect'])
<add> ->onlyMethods(['connect'])
<ide> ->setConstructorArgs([[
<ide> 'driver' => $driver,
<ide> 'name' => 'default',
<ide><path>tests/TestCase/Database/Driver/MysqlTest.php
<ide> public function setup(): void
<ide> public function testConnectionConfigDefault()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Mysql')
<del> ->setMethods(['_connect', 'getConnection'])
<add> ->onlyMethods(['_connect', 'getConnection'])
<ide> ->getMock();
<ide> $dsn = 'mysql:host=localhost;port=3306;dbname=cake;charset=utf8mb4';
<ide> $expected = [
<ide> public function testConnectionConfigDefault()
<ide> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
<ide> ];
<ide> $connection = $this->getMockBuilder('StdClass')
<del> ->setMethods(['exec'])
<add> ->onlyMethods(['exec'])
<ide> ->getMock();
<ide>
<ide> $driver->expects($this->once())->method('_connect')
<ide> public function testConnectionConfigCustom()
<ide> ],
<ide> ];
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Mysql')
<del> ->setMethods(['_connect', 'getConnection'])
<add> ->onlyMethods(['_connect', 'getConnection'])
<ide> ->setConstructorArgs([$config])
<ide> ->getMock();
<ide> $dsn = 'mysql:host=foo;port=3440;dbname=bar';
<ide> public function testConnectionConfigCustom()
<ide> ];
<ide>
<ide> $connection = $this->getMockBuilder('StdClass')
<del> ->setMethods(['exec'])
<add> ->onlyMethods(['exec'])
<ide> ->getMock();
<ide> $connection->expects($this->at(0))->method('exec')->with('Execute this');
<ide> $connection->expects($this->at(1))->method('exec')->with('this too');
<ide> public function testVersion($dbVersion, $expectedVersion)
<ide> {
<ide> /** @var \PHPUnit\Framework\MockObject\MockObject&\Cake\Database\Connection $connection */
<ide> $connection = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['getAttribute'])
<add> ->onlyMethods(['getAttribute'])
<ide> ->getMock();
<ide> $connection->expects($this->once())
<ide> ->method('getAttribute')
<ide> public function testVersion($dbVersion, $expectedVersion)
<ide>
<ide> /** @var \PHPUnit\Framework\MockObject\MockObject&\Cake\Database\Driver\Mysql $driver */
<ide> $driver = $this->getMockBuilder(Mysql::class)
<del> ->setMethods(['connect'])
<add> ->onlyMethods(['connect'])
<ide> ->getMock();
<ide>
<ide> $driver->setConnection($connection);
<ide><path>tests/TestCase/Database/Driver/PostgresTest.php
<ide> class PostgresTest extends TestCase
<ide> public function testConnectionConfigDefault()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')
<del> ->setMethods(['_connect', 'getConnection'])
<add> ->onlyMethods(['_connect', 'getConnection'])
<ide> ->getMock();
<ide> $dsn = 'pgsql:host=localhost;port=5432;dbname=cake';
<ide> $expected = [
<ide> public function testConnectionConfigDefault()
<ide> ];
<ide>
<ide> $connection = $this->getMockBuilder('stdClass')
<del> ->setMethods(['exec', 'quote'])
<add> ->addMethods(['exec', 'quote'])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide> ->method('quote')
<ide> public function testConnectionConfigCustom()
<ide> 'init' => ['Execute this', 'this too'],
<ide> ];
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')
<del> ->setMethods(['_connect', 'getConnection', 'setConnection'])
<add> ->onlyMethods(['_connect', 'getConnection', 'setConnection'])
<ide> ->setConstructorArgs([$config])
<ide> ->getMock();
<ide> $dsn = 'pgsql:host=foo;port=3440;dbname=bar';
<ide> public function testConnectionConfigCustom()
<ide> ];
<ide>
<ide> $connection = $this->getMockBuilder('stdClass')
<del> ->setMethods(['exec', 'quote'])
<add> ->addMethods(['exec', 'quote'])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide> ->method('quote')
<ide> public function testConnectionConfigCustom()
<ide> public function testInsertReturning()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')
<del> ->setMethods(['_connect', 'getConnection'])
<add> ->onlyMethods(['_connect', 'getConnection'])
<ide> ->setConstructorArgs([[]])
<ide> ->getMock();
<ide> $connection = $this
<ide> ->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['connect'])
<add> ->onlyMethods(['connect'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide>
<ide> public function testInsertReturning()
<ide> public function testHavingReplacesAlias()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')
<del> ->setMethods(['connect', 'getConnection', 'version'])
<add> ->onlyMethods(['connect', 'getConnection', 'version'])
<ide> ->setConstructorArgs([[]])
<ide> ->getMock();
<ide>
<ide> $connection = $this->getMockBuilder('\Cake\Database\Connection')
<del> ->setMethods(['connect', 'getDriver', 'setDriver'])
<add> ->onlyMethods(['connect', 'getDriver', 'setDriver'])
<ide> ->setConstructorArgs([['log' => false]])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide> public function testHavingReplacesAlias()
<ide> public function testHavingWhenNoAliasIsUsed()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')
<del> ->setMethods(['connect', 'getConnection', 'version'])
<add> ->onlyMethods(['connect', 'getConnection', 'version'])
<ide> ->setConstructorArgs([[]])
<ide> ->getMock();
<ide>
<ide> $connection = $this->getMockBuilder('\Cake\Database\Connection')
<del> ->setMethods(['connect', 'getDriver', 'setDriver'])
<add> ->onlyMethods(['connect', 'getDriver', 'setDriver'])
<ide> ->setConstructorArgs([['log' => false]])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide><path>tests/TestCase/Database/Driver/SqliteTest.php
<ide> class SqliteTest extends TestCase
<ide> public function testConnectionConfigDefault()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')
<del> ->setMethods(['_connect'])
<add> ->onlyMethods(['_connect'])
<ide> ->getMock();
<ide> $dsn = 'sqlite::memory:';
<ide> $expected = [
<ide> public function testConnectionConfigCustom()
<ide> 'mask' => 0666,
<ide> ];
<ide> $driver = $this->getMockBuilder('Cake\Database\driver\Sqlite')
<del> ->setMethods(['_connect', 'getConnection'])
<add> ->onlyMethods(['_connect', 'getConnection'])
<ide> ->setConstructorArgs([$config])
<ide> ->getMock();
<ide> $dsn = 'sqlite:bar.db';
<ide> public function testConnectionConfigCustom()
<ide> ];
<ide>
<ide> $connection = $this->getMockBuilder('StdClass')
<del> ->setMethods(['exec'])
<add> ->addMethods(['exec'])
<ide> ->getMock();
<ide> $connection->expects($this->at(0))->method('exec')->with('Execute this');
<ide> $connection->expects($this->at(1))->method('exec')->with('this too');
<ide> public function testSchemaValue($input, $expected)
<ide> {
<ide> $driver = new Sqlite();
<ide> $mock = $this->getMockBuilder(PDO::class)
<del> ->setMethods(['quote', 'quoteIdentifier'])
<add> ->onlyMethods(['quote'])
<add> ->addMethods(['quoteIdentifier'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide><path>tests/TestCase/Database/Driver/SqlserverTest.php
<ide> public function dnsStringDataProvider()
<ide> public function testDnsString($constructorArgs, $dnsString)
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['_connect', 'getConnection'])
<add> ->onlyMethods(['_connect', 'getConnection'])
<ide> ->setConstructorArgs([$constructorArgs])
<ide> ->getMock();
<ide>
<ide> public function testConnectionConfigCustom()
<ide> 'settings' => ['config1' => 'value1', 'config2' => 'value2'],
<ide> ];
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['_connect', 'setConnection', 'getConnection'])
<add> ->onlyMethods(['_connect', 'setConnection', 'getConnection'])
<ide> ->setConstructorArgs([$config])
<ide> ->getMock();
<ide> $dsn = 'sqlsrv:Server=foo;Database=bar;MultipleActiveResultSets=false';
<ide> public function testConnectionConfigCustom()
<ide> $expected['port'] = null;
<ide>
<ide> $connection = $this->getMockBuilder('stdClass')
<del> ->setMethods(['exec', 'quote'])
<add> ->addMethods(['exec', 'quote'])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide> ->method('quote')
<ide> public function testConnectionPersistentFalse()
<ide> 'encoding' => 'a-language',
<ide> ];
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['_connect', 'connection'])
<add> ->onlyMethods(['_connect'])
<ide> ->setConstructorArgs([$config])
<ide> ->getMock();
<ide> $dsn = 'sqlsrv:Server=foo;Database=bar;MultipleActiveResultSets=false';
<ide> public function testConnectionPersistentTrueException()
<ide> 'database' => 'bar',
<ide> ];
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['_connect', 'connection'])
<add> ->onlyMethods(['_connect', 'getConnection'])
<ide> ->setConstructorArgs([$config])
<ide> ->getMock();
<ide> $driver->connect();
<ide> public function testConnectionPersistentTrueException()
<ide> public function testSelectLimitVersion12()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['_connect', 'getConnection', 'version'])
<add> ->onlyMethods(['_connect', 'getConnection', 'version'])
<ide> ->setConstructorArgs([[]])
<ide> ->getMock();
<ide> $driver->method('version')
<ide> ->will($this->returnValue('12'));
<ide>
<ide> $connection = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['connect', 'getDriver', 'setDriver'])
<add> ->onlyMethods(['connect', 'getDriver', 'setDriver'])
<ide> ->setConstructorArgs([['log' => false]])
<ide> ->getMock();
<ide> $connection->method('getDriver')
<ide> public function testSelectLimitVersion12()
<ide> public function testSelectLimitOldServer()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['_connect', 'getConnection', 'version'])
<add> ->onlyMethods(['_connect', 'getConnection', 'version'])
<ide> ->setConstructorArgs([[]])
<ide> ->getMock();
<ide> $driver->expects($this->any())
<ide> ->method('version')
<ide> ->will($this->returnValue('8'));
<ide>
<ide> $connection = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['connect', 'getDriver', 'setDriver'])
<add> ->onlyMethods(['connect', 'getDriver', 'setDriver'])
<ide> ->setConstructorArgs([['log' => false]])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide> public function testSelectLimitOldServer()
<ide> public function testInsertUsesOutput()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['_connect', 'getConnection'])
<add> ->onlyMethods(['_connect', 'getConnection'])
<ide> ->setConstructorArgs([[]])
<ide> ->getMock();
<ide> $connection = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['connect', 'getDriver', 'setDriver'])
<add> ->onlyMethods(['connect', 'getDriver', 'setDriver'])
<ide> ->setConstructorArgs([['log' => false]])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide> public function testInsertUsesOutput()
<ide> public function testHavingReplacesAlias()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['connect', 'getConnection', 'version'])
<add> ->onlyMethods(['connect', 'getConnection', 'version'])
<ide> ->setConstructorArgs([[]])
<ide> ->getMock();
<ide> $driver->expects($this->any())
<ide> ->method('version')
<ide> ->will($this->returnValue('8'));
<ide>
<ide> $connection = $this->getMockBuilder('\Cake\Database\Connection')
<del> ->setMethods(['connect', 'getDriver', 'setDriver'])
<add> ->onlyMethods(['connect', 'getDriver', 'setDriver'])
<ide> ->setConstructorArgs([['log' => false]])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide> public function testHavingReplacesAlias()
<ide> public function testHavingWhenNoAliasIsUsed()
<ide> {
<ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')
<del> ->setMethods(['connect', 'getConnection', 'version'])
<add> ->onlyMethods(['connect', 'getConnection', 'version'])
<ide> ->setConstructorArgs([[]])
<ide> ->getMock();
<ide> $driver->expects($this->any())
<ide> ->method('version')
<ide> ->will($this->returnValue('8'));
<ide>
<ide> $connection = $this->getMockBuilder('\Cake\Database\Connection')
<del> ->setMethods(['connect', 'getDriver', 'setDriver'])
<add> ->onlyMethods(['connect', 'getDriver', 'setDriver'])
<ide> ->setConstructorArgs([['log' => false]])
<ide> ->getMock();
<ide> $connection->expects($this->any())
<ide><path>tests/TestCase/Database/DriverTest.php
<ide> public function testSupportsQuoting()
<ide> {
<ide> $connection = $this->getMockBuilder(PDO::class)
<ide> ->disableOriginalConstructor()
<del> ->setMethods(['getAttribute'])
<add> ->onlyMethods(['getAttribute'])
<ide> ->getMock();
<ide>
<ide> $connection
<ide> public function testSchemaValueConnectionQuoting()
<ide>
<ide> $connection = $this->getMockBuilder(PDO::class)
<ide> ->disableOriginalConstructor()
<del> ->setMethods(['quote'])
<add> ->onlyMethods(['quote'])
<ide> ->getMock();
<ide>
<ide> $connection
<ide> public function testLastInsertId()
<ide> {
<ide> $connection = $this->getMockBuilder(Mysql::class)
<ide> ->disableOriginalConstructor()
<del> ->setMethods(['lastInsertId'])
<add> ->onlyMethods(['lastInsertId'])
<ide> ->getMock();
<ide>
<ide> $connection
<ide> public function testIsConnected()
<ide>
<ide> $connection = $this->getMockBuilder(PDO::class)
<ide> ->disableOriginalConstructor()
<del> ->setMethods(['query'])
<add> ->onlyMethods(['query'])
<ide> ->getMock();
<ide>
<ide> $connection
<ide> public function testAutoQuoting()
<ide> public function testCompileQuery()
<ide> {
<ide> $compiler = $this->getMockBuilder(QueryCompiler::class)
<del> ->setMethods(['compile'])
<add> ->onlyMethods(['compile'])
<ide> ->getMock();
<ide>
<ide> $compiler
<ide> public function testCompileQuery()
<ide> ->willReturn('1');
<ide>
<ide> $driver = $this->getMockBuilder(Driver::class)
<del> ->setMethods(['newCompiler', 'queryTranslator'])
<add> ->onlyMethods(['newCompiler', 'queryTranslator'])
<ide> ->getMockForAbstractClass();
<ide>
<ide> $driver
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testRowCountAndClose()
<ide> $this->loadFixtures('Authors');
<ide>
<ide> $statementMock = $this->getMockBuilder(StatementInterface::class)
<del> ->setMethods(['rowCount', 'closeCursor'])
<add> ->onlyMethods(['rowCount', 'closeCursor'])
<ide> ->getMockForAbstractClass();
<ide>
<ide> $statementMock->expects($this->once())
<ide> public function testRowCountAndClose()
<ide>
<ide> /** @var \Cake\ORM\Query|\PHPUnit\Framework\MockObject\MockObject $queryMock */
<ide> $queryMock = $this->getMockBuilder(Query::class)
<del> ->setMethods(['execute'])
<add> ->onlyMethods(['execute'])
<ide> ->setConstructorArgs([$this->connection])
<ide> ->getMock();
<ide>
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> protected function _getMockedDriver()
<ide> {
<ide> $driver = new Mysql();
<ide> $mock = $this->getMockBuilder(PDO::class)
<del> ->setMethods(['quote', 'quoteIdentifier', 'getAttribute'])
<add> ->onlyMethods(['quote', 'getAttribute'])
<add> ->addMethods(['quoteIdentifier'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> protected function _getMockedDriver()
<ide> {
<ide> $driver = new Postgres();
<ide> $mock = $this->getMockBuilder(PDO::class)
<del> ->setMethods(['quote'])
<add> ->onlyMethods(['quote'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public function testTruncateSql()
<ide> ->will($this->returnValue($driver));
<ide>
<ide> $statement = $this->getMockBuilder('\PDOStatement')
<del> ->setMethods(['execute', 'rowCount', 'closeCursor', 'fetchAll'])
<add> ->onlyMethods(['execute', 'rowCount', 'closeCursor', 'fetchAll'])
<ide> ->getMock();
<ide> $driver->getConnection()->expects($this->once())
<ide> ->method('prepare')
<ide> public function testTruncateSqlNoSequences()
<ide> ->will($this->returnValue($driver));
<ide>
<ide> $statement = $this->getMockBuilder('\PDOStatement')
<del> ->setMethods(['execute', 'rowCount', 'closeCursor', 'fetchAll'])
<add> ->onlyMethods(['execute', 'rowCount', 'closeCursor', 'fetchAll'])
<ide> ->getMock();
<ide> $driver->getConnection()
<ide> ->expects($this->once())
<ide> protected function _getMockedDriver()
<ide> {
<ide> $driver = new Sqlite();
<ide> $mock = $this->getMockBuilder(PDO::class)
<del> ->setMethods(['quote', 'prepare'])
<add> ->onlyMethods(['quote', 'prepare'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> protected function _getMockedDriver()
<ide> {
<ide> $driver = new Sqlserver();
<ide> $mock = $this->getMockBuilder(PDO::class)
<del> ->setMethods(['quote'])
<add> ->onlyMethods(['quote'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide><path>tests/TestCase/Database/Type/StringTypeTest.php
<ide> public function testToPHP()
<ide> public function testToDatabase()
<ide> {
<ide> $obj = $this->getMockBuilder('StdClass')
<del> ->setMethods(['__toString'])
<add> ->addMethods(['__toString'])
<ide> ->getMock();
<ide> $obj->method('__toString')->will($this->returnValue('toString called'));
<ide>
<ide><path>tests/TestCase/Database/ValueBinderTest.php
<ide> public function testAttachTo()
<ide> $valueBinder = new ValueBinder();
<ide> $statementMock = $this->getMockBuilder('Cake\Database\Statement\StatementDecorator')
<ide> ->disableOriginalConstructor()
<del> ->setMethods(['bindValue'])
<add> ->onlyMethods(['bindValue'])
<ide> ->getMock();
<ide>
<ide> $statementMock->expects($this->at(0))->method('bindValue')->with('c0', 'value0', 'string');
<ide><path>tests/TestCase/Datasource/PaginatorTestTrait.php
<ide> public function testPaginateQueryWithLimit()
<ide> protected function _getMockPosts($methods = [])
<ide> {
<ide> return $this->getMockBuilder('TestApp\Model\Table\PaginatorPostsTable')
<del> ->setMethods($methods)
<add> ->onlyMethods($methods)
<ide> ->setConstructorArgs([[
<ide> 'connection' => ConnectionManager::get('test'),
<ide> 'alias' => 'PaginatorPosts',
<ide> protected function _getMockFindQuery($table = null)
<ide> {
<ide> /** @var \Cake\ORM\Query|\PHPUnit\Framework\MockObject\MockObject $query */
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['total', 'all', 'count', 'applyOptions'])
<add> ->onlyMethods(['all', 'count', 'applyOptions'])
<add> ->addMethods(['total'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide>
<ide><path>tests/TestCase/Error/ConsoleErrorHandlerTest.php
<ide> public function setUp(): void
<ide> parent::setUp();
<ide> $this->stderr = new ConsoleOutput();
<ide> $this->Error = $this->getMockBuilder('Cake\Error\ConsoleErrorHandler')
<del> ->setMethods(['_stop'])
<add> ->onlyMethods(['_stop'])
<ide> ->setConstructorArgs([['stderr' => $this->stderr]])
<ide> ->getMock();
<ide> Log::drop('stdout');
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> public function testMissingRenderSafe()
<ide>
<ide> /** @var \Cake\Controller\Controller|\PHPUnit\Framework\MockObject\MockObject $controller */
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['render'])
<add> ->onlyMethods(['render'])
<ide> ->getMock();
<ide> $controller->viewBuilder()->setHelpers(['Fail', 'Boom']);
<ide> $controller->setRequest(new ServerRequest());
<ide> public function testRenderExceptionInBeforeRender()
<ide>
<ide> /** @var \Cake\Controller\Controller|\PHPUnit\Framework\MockObject\MockObject $controller */
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['beforeRender'])
<add> ->onlyMethods(['beforeRender'])
<ide> ->getMock();
<ide> $controller->request = new ServerRequest();
<ide> $controller->expects($this->any())
<ide> public function testMissingPluginRenderSafe()
<ide>
<ide> /** @var \Cake\Controller\Controller|\PHPUnit\Framework\MockObject\MockObject $controller */
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['render'])
<add> ->onlyMethods(['render'])
<ide> ->getMock();
<ide> $controller->setPlugin('TestPlugin');
<ide> $controller->request = new ServerRequest();
<ide> public function testMissingPluginRenderSafeWithPlugin()
<ide>
<ide> /** @var \Cake\Controller\Controller|\PHPUnit\Framework\MockObject\MockObject $controller */
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<del> ->setMethods(['render'])
<add> ->onlyMethods(['render'])
<ide> ->getMock();
<ide> $controller->setPlugin('TestPlugin');
<ide> $controller->request = new ServerRequest();
<ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php
<ide> public function testRendererFactory()
<ide> $this->assertInstanceOf('LogicException', $exception);
<ide> $response = new Response();
<ide> $mock = $this->getMockBuilder(ExceptionRendererInterface::class)
<del> ->setMethods(['render'])
<add> ->onlyMethods(['render'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('render')
<ide> public function testHandleExceptionRenderingFails()
<ide>
<ide> $factory = function ($exception) {
<ide> $mock = $this->getMockBuilder(ExceptionRendererInterface::class)
<del> ->setMethods(['render'])
<add> ->onlyMethods(['render'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('render')
<ide><path>tests/TestCase/Event/EventManagerTest.php
<ide> public function testOnSubscriber()
<ide> $manager = new EventManager();
<ide> /** @var \TestApp\TestCase\Event\CustomTestEventListenerInterface|\PHPUnit\Framework\MockObject\MockObject $listener */
<ide> $listener = $this->getMockBuilder(CustomTestEventListenerInterface::class)
<del> ->setMethods(['secondListenerFunction'])
<add> ->onlyMethods(['secondListenerFunction'])
<ide> ->getMock();
<ide> $manager->on($listener);
<ide>
<ide> public function testOnSubscriberMultiple()
<ide> {
<ide> $manager = new EventManager();
<ide> $listener = $this->getMockBuilder(CustomTestEventListenerInterface::class)
<del> ->setMethods(['listenerFunction', 'thirdListenerFunction'])
<add> ->onlyMethods(['listenerFunction', 'thirdListenerFunction'])
<ide> ->getMock();
<ide> $manager->on($listener);
<ide> $event = new Event('multiple.handlers');
<ide> public function testDetachSubscriber()
<ide> {
<ide> $manager = new EventManager();
<ide> $listener = $this->getMockBuilder(CustomTestEventListenerInterface::class)
<del> ->setMethods(['secondListenerFunction'])
<add> ->onlyMethods(['secondListenerFunction'])
<ide> ->getMock();
<ide> $manager->on($listener);
<ide> $expected = [
<ide> public function testGlobalDispatcherGetter()
<ide> public function testDispatchWithGlobal()
<ide> {
<ide> $generalManager = $this->getMockBuilder('Cake\Event\EventManager')
<del> ->setMethods(['prioritisedListeners'])
<add> ->onlyMethods(['prioritisedListeners'])
<ide> ->getMock();
<ide> $manager = new EventManager();
<ide> $event = new Event('fake.event');
<ide><path>tests/TestCase/Form/FormTest.php
<ide> public function testSetGetSchema()
<ide> public function testGetValidator()
<ide> {
<ide> $form = $this->getMockBuilder(Form::class)
<del> ->setMethods(['buildValidator'])
<add> ->addMethods(['buildValidator'])
<ide> ->getMock();
<ide>
<ide> $form->expects($this->once())
<ide> public function testSetErrors()
<ide> public function testExecuteInvalid()
<ide> {
<ide> $form = $this->getMockBuilder('Cake\Form\Form')
<del> ->setMethods(['_execute'])
<add> ->onlyMethods(['_execute'])
<ide> ->getMock();
<ide> $form->getValidator()
<ide> ->add('email', 'format', ['rule' => 'email']);
<ide><path>tests/TestCase/Http/Client/Adapter/StreamTest.php
<ide> public function setUp(): void
<ide> {
<ide> parent::setUp();
<ide> $this->stream = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['_send'])
<add> ->onlyMethods(['_send'])
<ide> ->getMock();
<ide> stream_wrapper_unregister('http');
<ide> stream_wrapper_register('http', CakeStreamWrapper::class);
<ide><path>tests/TestCase/Http/Client/Auth/DigestTest.php
<ide> public function setUp(): void
<ide> protected function getClientMock()
<ide> {
<ide> return $this->getMockBuilder(Client::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> }
<ide>
<ide><path>tests/TestCase/Http/ClientTest.php
<ide> public function testGetSimpleWithHeadersAndCookies()
<ide> ];
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testGetNoData()
<ide> $response = new Response();
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testGetQuerystring()
<ide> $response = new Response();
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testGetQuerystringString()
<ide> $response = new Response();
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testGetWithContent()
<ide> $response = new Response();
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testInvalidAuthenticationType()
<ide> {
<ide> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->never())
<ide> ->method('send');
<ide> public function testGetWithAuthenticationAndProxy()
<ide> $response = new Response();
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $headers = [
<ide> 'Authorization' => 'Basic ' . base64_encode('mark:secret'),
<ide> public function testMethodsSimple($method)
<ide> $response = new Response();
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testPostWithTypeKey($type, $mime)
<ide> ];
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testPostWithStringDataDefaultsToFormEncoding()
<ide> $data = 'some=value&more=data';
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->any())
<ide> ->method('send')
<ide> public function testExceptionOnUnknownType()
<ide> {
<ide> $this->expectException(\Cake\Core\Exception\Exception::class);
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->never())
<ide> ->method('send');
<ide> public function testExceptionOnUnknownType()
<ide> public function testCookieStorage()
<ide> {
<ide> $adapter = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide>
<ide> $headers = [
<ide> public function testHeadQuerystring()
<ide> $response = new Response();
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testRedirects()
<ide> $url = 'http://cakephp.org';
<ide>
<ide> $adapter = $this->getMockBuilder(Client\Adapter\Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide>
<ide> $redirect = new Response([
<ide> public function testSendRequest()
<ide> ];
<ide>
<ide> $mock = $this->getMockBuilder(Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide> $mock->expects($this->once())
<ide> ->method('send')
<ide> public function testSendRequest()
<ide> public function testRedirectDifferentSubDomains()
<ide> {
<ide> $adapter = $this->getMockBuilder(Client\Adapter\Stream::class)
<del> ->setMethods(['send'])
<add> ->onlyMethods(['send'])
<ide> ->getMock();
<ide>
<ide> $url = 'http://auth.example.org';
<ide><path>tests/TestCase/Http/ResponseEmitterTest.php
<ide> public function setUp(): void
<ide> $GLOBALS['mockedHeaders'] = [];
<ide>
<ide> $this->emitter = $this->getMockBuilder(ResponseEmitter::class)
<del> ->setMethods(['setCookie'])
<add> ->onlyMethods(['setCookie'])
<ide> ->getMock();
<ide>
<ide> $this->emitter->expects($this->any())
<ide><path>tests/TestCase/Http/ServerTest.php
<ide> public function testRunCallingPluginHooks()
<ide>
<ide> /** @var \TestApp\Http\MiddlewareApplication|\PHPUnit\Framework\MockObject\MockObject $app */
<ide> $app = $this->getMockBuilder(MiddlewareApplication::class)
<del> ->setMethods(['pluginBootstrap', 'pluginEvents', 'pluginMiddleware'])
<add> ->onlyMethods(['pluginBootstrap', 'pluginMiddleware'])
<add> ->addMethods(['pluginEvents'])
<ide> ->setConstructorArgs([$this->config])
<ide> ->getMock();
<ide> $app->expects($this->at(0))
<ide><path>tests/TestCase/Log/Engine/SyslogLogTest.php
<ide> public function testOpenLog()
<ide> {
<ide> /** @var \Cake\Log\Engine\SyslogLog|\PHPUnit\Framework\MockObject\MockObject $log */
<ide> $log = $this->getMockBuilder(SyslogLog::class)
<del> ->setMethods(['_open', '_write'])
<add> ->onlyMethods(['_open', '_write'])
<ide> ->getMock();
<ide> $log->expects($this->once())->method('_open')->with('', LOG_ODELAY, LOG_USER);
<ide> $log->log('debug', 'message');
<ide>
<ide> $log = $this->getMockBuilder(SyslogLog::class)
<del> ->setMethods(['_open', '_write'])
<add> ->onlyMethods(['_open', '_write'])
<ide> ->getMock();
<ide> $log->setConfig([
<ide> 'prefix' => 'thing',
<ide> public function testWriteOneLine($type, $expected)
<ide> {
<ide> /** @var \Cake\Log\Engine\SyslogLog|\PHPUnit\Framework\MockObject\MockObject $log */
<ide> $log = $this->getMockBuilder(SyslogLog::class)
<del> ->setMethods(['_open', '_write'])
<add> ->onlyMethods(['_open', '_write'])
<ide> ->getMock();
<ide> $log->expects($this->once())->method('_write')->with($expected, $type . ': Foo');
<ide> $log->log($type, 'Foo');
<ide> public function testWriteMultiLine()
<ide> {
<ide> /** @var \Cake\Log\Engine\SyslogLog|\PHPUnit\Framework\MockObject\MockObject $log */
<ide> $log = $this->getMockBuilder(SyslogLog::class)
<del> ->setMethods(['_open', '_write'])
<add> ->onlyMethods(['_open', '_write'])
<ide> ->getMock();
<ide> $log->expects($this->at(1))->method('_write')->with(LOG_DEBUG, 'debug: Foo');
<ide> $log->expects($this->at(2))->method('_write')->with(LOG_DEBUG, 'debug: Bar');
<ide><path>tests/TestCase/Mailer/MailerTest.php
<ide> public function testRenderWithLayoutAndAttachment()
<ide> public function testSend()
<ide> {
<ide> $mailer = $this->getMockBuilder(Mailer::class)
<del> ->setMethods(['test', 'deliver'])
<add> ->onlyMethods(['deliver'])
<add> ->addMethods(['test'])
<ide> ->getMock();
<ide> $mailer->expects($this->once())
<ide> ->method('test')
<ide> public function testSendAttachment()
<ide> public function testSendWithUnsetTemplateDefaultsToActionName()
<ide> {
<ide> $mailer = $this->getMockBuilder(Mailer::class)
<del> ->setMethods(['test', 'deliver', 'restore'])
<add> ->onlyMethods(['deliver', 'restore'])
<add> ->addMethods(['test'])
<ide> ->getMock();
<ide> $mailer->expects($this->once())
<ide> ->method('test')
<ide> public function testReset()
<ide> public function testSendFailsEmailIsReset()
<ide> {
<ide> $mailer = $this->getMockBuilder(Mailer::class)
<del> ->setMethods(['welcome', 'restore', 'deliver'])
<add> ->onlyMethods(['restore', 'deliver'])
<add> ->addMethods(['welcome'])
<ide> ->getMock();
<ide>
<ide> $mailer->expects($this->once())
<ide> public function testSendWithLogAndScope()
<ide> public function testDefaultProfileRestoration()
<ide> {
<ide> $mailer = $this->getMockBuilder(Mailer::class)
<del> ->setMethods(['test', 'deliver'])
<add> ->onlyMethods(['deliver'])
<add> ->addMethods(['test'])
<ide> ->setConstructorArgs([['template' => 'cakephp']])
<ide> ->getMock();
<ide> $mailer->expects($this->once())
<ide><path>tests/TestCase/Mailer/Transport/MailTransportTest.php
<ide> public function setUp(): void
<ide> {
<ide> parent::setUp();
<ide> $this->MailTransport = $this->getMockBuilder('Cake\Mailer\Transport\MailTransport')
<del> ->setMethods(['_mail'])
<add> ->onlyMethods(['_mail'])
<ide> ->getMock();
<ide> $this->MailTransport->setConfig(['additionalParameters' => '-f']);
<ide> }
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php
<ide> public function setUp(): void
<ide> {
<ide> parent::setUp();
<ide> $this->socket = $this->getMockBuilder('Cake\Network\Socket')
<del> ->setMethods(['read', 'write', 'connect', 'disconnect', 'enableCrypto'])
<add> ->onlyMethods(['read', 'write', 'connect', 'disconnect', 'enableCrypto'])
<ide> ->getMock();
<ide>
<ide> $this->SmtpTransport = new SmtpTestTransport();
<ide> public function testKeepAlive()
<ide>
<ide> /** @var \Cake\Mailer\Message $message */
<ide> $message = $this->getMockBuilder(Message::class)
<del> ->setMethods(['getBody'])
<add> ->onlyMethods(['getBody'])
<ide> ->getMock();
<ide> $message->setFrom('noreply@cakephp.org', 'CakePHP Test');
<ide> $message->setTo('cake@cakephp.org', 'CakePHP');
<ide> public function testSendDefaults()
<ide> {
<ide> /** @var \Cake\Mailer\Message $message */
<ide> $message = $this->getMockBuilder(Message::class)
<del> ->setMethods(['getBody'])
<add> ->onlyMethods(['getBody'])
<ide> ->getMock();
<ide> $message->setFrom('noreply@cakephp.org', 'CakePHP Test');
<ide> $message->setTo('cake@cakephp.org', 'CakePHP');
<ide> public function testSendMessageTooBigOnWindows()
<ide> {
<ide> /** @var \Cake\Mailer\Message $message */
<ide> $message = $this->getMockBuilder(Message::class)
<del> ->setMethods(['getBody'])
<add> ->onlyMethods(['getBody'])
<ide> ->getMock();
<ide> $message->setFrom('noreply@cakephp.org', 'CakePHP Test');
<ide> $message->setTo('cake@cakephp.org', 'CakePHP');
<ide><path>tests/TestCase/Network/SocketTest.php
<ide> public function testConnectToUnixFileSocket()
<ide> {
<ide> $socketName = 'unix:///tmp/test.socket';
<ide> $socket = $this->getMockBuilder(Socket::class)
<del> ->setMethods(['_getStreamSocketClient'])
<add> ->onlyMethods(['_getStreamSocketClient'])
<ide> ->getMock();
<ide> $socket->expects($this->once())
<ide> ->method('_getStreamSocketClient')
<ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide> public function setUp(): void
<ide> {
<ide> parent::setUp();
<ide> $this->tag = $this->getMockBuilder(Table::class)
<del> ->setMethods(['find', 'delete'])
<add> ->onlyMethods(['find', 'delete'])
<ide> ->setConstructorArgs([['alias' => 'Tags', 'table' => 'tags']])
<ide> ->getMock();
<ide> $this->tag->setSchema([
<ide> public function setUp(): void
<ide> ],
<ide> ]);
<ide> $this->article = $this->getMockBuilder(Table::class)
<del> ->setMethods(['find', 'delete'])
<add> ->onlyMethods(['find', 'delete'])
<ide> ->setConstructorArgs([['alias' => 'Articles', 'table' => 'articles']])
<ide> ->getMock();
<ide> $this->article->setSchema([
<ide> public function testJunction()
<ide> public function testJunctionConnection()
<ide> {
<ide> $mock = $this->getMockBuilder(Connection::class)
<del> ->setMethods(['setDriver'])
<add> ->onlyMethods(['setDriver'])
<ide> ->setConstructorArgs([['name' => 'other_source']])
<ide> ->getMock();
<ide> ConnectionManager::setConfig('other_source', $mock);
<ide> public function testFinderOption()
<ide> public function testCascadeDelete()
<ide> {
<ide> $articleTag = $this->getMockBuilder(Table::class)
<del> ->setMethods(['deleteAll'])
<add> ->onlyMethods(['deleteAll'])
<ide> ->getMock();
<ide> $config = [
<ide> 'sourceTable' => $this->article,
<ide> public function testCascadeDelete()
<ide> public function testCascadeDeleteDependent()
<ide> {
<ide> $articleTag = $this->getMockBuilder(Table::class)
<del> ->setMethods(['delete', 'deleteAll'])
<add> ->onlyMethods(['delete', 'deleteAll'])
<ide> ->getMock();
<ide> $config = [
<ide> 'sourceTable' => $this->article,
<ide> public function testLinkSuccessWithMocks()
<ide> {
<ide> $connection = ConnectionManager::get('test');
<ide> $joint = $this->getMockBuilder(Table::class)
<del> ->setMethods(['save', 'getPrimaryKey'])
<add> ->onlyMethods(['save', 'getPrimaryKey'])
<ide> ->setConstructorArgs([['alias' => 'ArticlesTags', 'connection' => $connection]])
<ide> ->getMock();
<ide>
<ide> public function testLinkSetSourceToJunctionEntities()
<ide> $connection = ConnectionManager::get('test');
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $joint */
<ide> $joint = $this->getMockBuilder(Table::class)
<del> ->setMethods(['save', 'getPrimaryKey'])
<add> ->onlyMethods(['save', 'getPrimaryKey'])
<ide> ->setConstructorArgs([['alias' => 'ArticlesTags', 'connection' => $connection]])
<ide> ->getMock();
<ide> $joint->setRegistryAlias('Plugin.ArticlesTags');
<ide> public function testSaveAssociatedEmptySetSuccess($value)
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockBuilder $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['table'])
<add> ->addMethods(['table'])
<ide> ->getMock();
<ide> $table->setSchema([]);
<ide> /** @var \Cake\ORM\Association\BelongsToMany|\PHPUnit\Framework\MockObject\MockObject $assoc */
<ide> $assoc = $this->getMockBuilder(BelongsToMany::class)
<del> ->setMethods(['_saveTarget', 'replaceLinks'])
<add> ->onlyMethods(['_saveTarget', 'replaceLinks'])
<ide> ->setConstructorArgs(['tags', ['sourceTable' => $table]])
<ide> ->getMock();
<ide> $entity = new Entity([
<ide> public function testSaveAssociatedEmptySetUpdateSuccess($value)
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockBuilder $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['table'])
<add> ->addMethods(['table'])
<ide> ->getMock();
<ide> $table->setSchema([]);
<ide> /** @var \Cake\ORM\Association\BelongsToMany|\PHPUnit\Framework\MockObject\MockObject $assoc */
<ide> $assoc = $this->getMockBuilder(BelongsToMany::class)
<del> ->setMethods(['_saveTarget', 'replaceLinks'])
<add> ->onlyMethods(['_saveTarget', 'replaceLinks'])
<ide> ->setConstructorArgs(['tags', ['sourceTable' => $table]])
<ide> ->getMock();
<ide> $entity = new Entity([
<ide> public function testSaveAssociatedWithReplace()
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['table'])
<add> ->addMethods(['table'])
<ide> ->getMock();
<ide> $table->setSchema([]);
<ide> $assoc = $this->getMockBuilder(BelongsToMany::class)
<del> ->setMethods(['replaceLinks'])
<add> ->onlyMethods(['replaceLinks'])
<ide> ->setConstructorArgs(['tags', ['sourceTable' => $table]])
<ide> ->getMock();
<ide> $entity = new Entity([
<ide> public function testSaveAssociatedWithReplaceReturnFalse()
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['table'])
<add> ->addMethods(['table'])
<ide> ->getMock();
<ide> $table->setSchema([]);
<ide> $assoc = $this->getMockBuilder(BelongsToMany::class)
<del> ->setMethods(['replaceLinks'])
<add> ->onlyMethods(['replaceLinks'])
<ide> ->setConstructorArgs(['tags', ['sourceTable' => $table]])
<ide> ->getMock();
<ide> $entity = new Entity([
<ide> public function testSaveAssociatedOnlyEntitiesAppend()
<ide> $connection = ConnectionManager::get('test');
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['saveAssociated', 'schema'])
<add> ->addMethods(['saveAssociated', 'schema'])
<ide> ->setConstructorArgs([['table' => 'tags', 'connection' => $connection]])
<ide> ->getMock();
<ide> $table->setPrimaryKey('id');
<ide><path>tests/TestCase/ORM/Association/BelongsToTest.php
<ide> public function testCascadeDelete()
<ide> public function testSaveAssociatedOnlyEntities()
<ide> {
<ide> $mock = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['saveAssociated'])
<add> ->addMethods(['saveAssociated'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $config = [
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php
<ide> public function setUp(): void
<ide> ]);
<ide> $connection = ConnectionManager::get('test');
<ide> $this->article = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['find', 'deleteAll', 'delete'])
<add> ->onlyMethods(['find', 'deleteAll', 'delete'])
<ide> ->setConstructorArgs([['alias' => 'Articles', 'table' => 'articles', 'connection' => $connection]])
<ide> ->getMock();
<ide> $this->article->setSchema([
<ide> public function testEagerLoaderMultipleKeys()
<ide> $association = new HasMany('Articles', $config);
<ide> $keys = [[1, 10], [2, 20], [3, 30], [4, 40]];
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['all', 'andWhere', 'getRepository'])
<add> ->onlyMethods(['all', 'andWhere', 'getRepository'])
<ide> ->setConstructorArgs([ConnectionManager::get('test'), $this->article])
<ide> ->getMock();
<ide> $query->method('getRepository')
<ide> public function testCascadeDeleteCallbacksRuleFailure()
<ide> public function testSaveAssociatedOnlyEntities()
<ide> {
<ide> $mock = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['saveAssociated'])
<add> ->addMethods(['saveAssociated'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $config = [
<ide><path>tests/TestCase/ORM/Association/HasOneTest.php
<ide> public function testAttachToMultiPrimaryKey()
<ide> $association = new HasOne('Profiles', $config);
<ide>
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['join', 'select'])
<add> ->onlyMethods(['join', 'select'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $field1 = new IdentifierExpression('Profiles.user_id');
<ide> public function testAttachToMultiPrimaryKeyMismatch()
<ide> $this->expectException(\RuntimeException::class);
<ide> $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')
<del> ->setMethods(['join', 'select'])
<add> ->onlyMethods(['join', 'select'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $config = [
<ide> public function testAttachToMultiPrimaryKeyMismatch()
<ide> public function testSaveAssociatedOnlyEntities()
<ide> {
<ide> $mock = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['saveAssociated'])
<add> ->addMethods(['saveAssociated'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $config = [
<ide><path>tests/TestCase/ORM/AssociationCollectionTest.php
<ide> public function testRemoveAll()
<ide> public function testGetByProperty()
<ide> {
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['table'])
<add> ->addMethods(['table'])
<ide> ->getMock();
<ide> $table->setSchema([]);
<ide> $belongsTo = new BelongsTo('Users', [
<ide> public function testCascadeDelete()
<ide> public function testSaveParents()
<ide> {
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['table'])
<add> ->addMethods(['table'])
<ide> ->getMock();
<ide> $table->setSchema([]);
<ide> $mockOne = $this->getMockBuilder('Cake\ORM\Association\BelongsTo')
<del> ->setMethods(['saveAssociated'])
<add> ->onlyMethods(['saveAssociated'])
<ide> ->setConstructorArgs(['Parent', [
<ide> 'sourceTable' => $table,
<ide> ]])
<ide> ->getMock();
<ide> $mockTwo = $this->getMockBuilder('Cake\ORM\Association\HasMany')
<del> ->setMethods(['saveAssociated'])
<add> ->onlyMethods(['saveAssociated'])
<ide> ->setConstructorArgs(['Child', [
<ide> 'sourceTable' => $table,
<ide> ]])
<ide> public function testSaveParents()
<ide> public function testSaveParentsFiltered()
<ide> {
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['table'])
<add> ->addMethods(['table'])
<ide> ->getMock();
<ide> $table->setSchema([]);
<ide> $mockOne = $this->getMockBuilder('Cake\ORM\Association\BelongsTo')
<del> ->setMethods(['saveAssociated'])
<add> ->onlyMethods(['saveAssociated'])
<ide> ->setConstructorArgs(['Parents', [
<ide> 'sourceTable' => $table,
<ide> ]])
<ide> ->getMock();
<ide> $mockTwo = $this->getMockBuilder('Cake\ORM\Association\BelongsTo')
<del> ->setMethods(['saveAssociated'])
<add> ->onlyMethods(['saveAssociated'])
<ide> ->setConstructorArgs(['Categories', [
<ide> 'sourceTable' => $table,
<ide> ]])
<ide> public function testSaveParentsFiltered()
<ide> public function testSaveChildrenFiltered()
<ide> {
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['table'])
<add> ->addMethods(['table'])
<ide> ->getMock();
<ide> $table->setSchema([]);
<ide> $mockOne = $this->getMockBuilder('Cake\ORM\Association\HasMany')
<del> ->setMethods(['saveAssociated'])
<add> ->onlyMethods(['saveAssociated'])
<ide> ->setConstructorArgs(['Comments', [
<ide> 'sourceTable' => $table,
<ide> ]])
<ide> ->getMock();
<ide> $mockTwo = $this->getMockBuilder('Cake\ORM\Association\HasOne')
<del> ->setMethods(['saveAssociated'])
<add> ->onlyMethods(['saveAssociated'])
<ide> ->setConstructorArgs(['Profiles', [
<ide> 'sourceTable' => $table,
<ide> ]])
<ide> public function testErrorOnUnknownAlias()
<ide> $this->expectException(\InvalidArgumentException::class);
<ide> $this->expectExceptionMessage('Cannot save Profiles, it is not associated to Users');
<ide> $table = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['save'])
<add> ->onlyMethods(['save'])
<ide> ->setConstructorArgs([['alias' => 'Users']])
<ide> ->getMock();
<ide>
<ide><path>tests/TestCase/ORM/AssociationProxyTest.php
<ide> public function testAssociationMethodProxy()
<ide> {
<ide> $articles = $this->getTableLocator()->get('articles');
<ide> $mock = $this->getMockBuilder('Cake\ORM\Table')
<del> ->setMethods(['crazy'])
<add> ->addMethods(['crazy'])
<ide> ->getMock();
<ide> $articles->belongsTo('authors', [
<ide> 'targetTable' => $mock,
<ide><path>tests/TestCase/ORM/AssociationTest.php
<ide> public function setUp(): void
<ide> 'joinType' => 'INNER',
<ide> ];
<ide> $this->association = $this->getMockBuilder(Association::class)
<del> ->setMethods([
<add> ->onlyMethods([
<ide> '_options', 'attachTo', '_joinCondition', 'cascadeDelete', 'isOwningSide',
<ide> 'saveAssociated', 'eagerLoader', 'type', 'requiresKeys',
<ide> ])
<ide> public function testSetNameToTargetAlias()
<ide> public function testSetttingClassNameFromAlias()
<ide> {
<ide> $association = $this->getMockBuilder(Association::class)
<del> ->setMethods(['type', 'eagerLoader', 'cascadeDelete', 'isOwningSide', 'saveAssociated'])
<add> ->onlyMethods(['type', 'eagerLoader', 'cascadeDelete', 'isOwningSide', 'saveAssociated'])
<ide> ->setConstructorArgs(['Foo'])
<ide> ->getMock();
<ide>
<ide> public function testClassNameUnnormalized()
<ide> 'className' => 'Test',
<ide> ];
<ide> $this->association = $this->getMockBuilder('Cake\ORM\Association')
<del> ->setMethods([
<add> ->onlyMethods([
<ide> '_options', 'attachTo', '_joinCondition', 'cascadeDelete', 'isOwningSide',
<ide> 'saveAssociated', 'eagerLoader', 'type', 'requiresKeys',
<ide> ])
<ide> public function testInvalidTableFetchedFromRegistry()
<ide> 'className' => TestTable::class,
<ide> ];
<ide> $this->association = $this->getMockBuilder('Cake\ORM\Association')
<del> ->setMethods([
<add> ->onlyMethods([
<ide> '_options', 'attachTo', '_joinCondition', 'cascadeDelete', 'isOwningSide',
<ide> 'saveAssociated', 'eagerLoader', 'type', 'requiresKeys',
<ide> ])
<ide> public function testTargetTableDescendant()
<ide> 'className' => $className,
<ide> ];
<ide> $this->association = $this->getMockBuilder('Cake\ORM\Association')
<del> ->setMethods([
<add> ->onlyMethods([
<ide> '_options', 'attachTo', '_joinCondition', 'cascadeDelete', 'isOwningSide',
<ide> 'saveAssociated', 'eagerLoader', 'type', 'requiresKeys',
<ide> ])
<ide> public function testTargetPlugin()
<ide> ];
<ide>
<ide> $this->association = $this->getMockBuilder('Cake\ORM\Association')
<del> ->setMethods([
<add> ->onlyMethods([
<ide> 'type', 'eagerLoader', 'cascadeDelete', 'isOwningSide', 'saveAssociated',
<ide> 'requiresKeys',
<ide> ])
<ide> public function testPropertyNameExplicitySet()
<ide> 'propertyName' => 'foo',
<ide> ];
<ide> $association = $this->getMockBuilder('Cake\ORM\Association')
<del> ->setMethods([
<add> ->onlyMethods([
<ide> '_options', 'attachTo', '_joinCondition', 'cascadeDelete', 'isOwningSide',
<ide> 'saveAssociated', 'eagerLoader', 'type', 'requiresKeys',
<ide> ])
<ide> public function testFinderInConstructor()
<ide> 'finder' => 'published',
<ide> ];
<ide> $assoc = $this->getMockBuilder('Cake\ORM\Association')
<del> ->setMethods([
<add> ->onlyMethods([
<ide> 'type', 'eagerLoader', 'cascadeDelete', 'isOwningSide', 'saveAssociated',
<ide> 'requiresKeys',
<ide> ])
<ide> public function testLocatorInConstructor()
<ide> 'tableLocator' => $locator,
<ide> ];
<ide> $assoc = $this->getMockBuilder('Cake\ORM\Association')
<del> ->setMethods([
<add> ->onlyMethods([
<ide> 'type', 'eagerLoader', 'cascadeDelete', 'isOwningSide', 'saveAssociated',
<ide> 'requiresKeys',
<ide> ])
<ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php
<ide> public function testCall()
<ide> {
<ide> $this->Behaviors->load('Sluggable');
<ide> $mockedBehavior = $this->getMockBuilder('Cake\ORM\Behavior')
<del> ->setMethods(['slugify'])
<add> ->addMethods(['slugify'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $this->Behaviors->set('Sluggable', $mockedBehavior);
<ide> public function testCallFinder()
<ide> {
<ide> $this->Behaviors->load('Sluggable');
<ide> $mockedBehavior = $this->getMockBuilder('Cake\ORM\Behavior')
<del> ->setMethods(['findNoSlug'])
<add> ->addMethods(['findNoSlug'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $this->Behaviors->set('Sluggable', $mockedBehavior);
<ide><path>tests/TestCase/ORM/CompositeKeysTest.php
<ide> public function testFindThreadedCompositeKeys()
<ide> {
<ide> $table = $this->getTableLocator()->get('SiteAuthors');
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['_addDefaultFields', 'execute'])
<add> ->onlyMethods(['_addDefaultFields', 'execute'])
<ide> ->setConstructorArgs([$table->getConnection(), $table])
<ide> ->getMock();
<ide>
<ide><path>tests/TestCase/ORM/EagerLoaderTest.php
<ide> public function testContainToJoinsOneLevel()
<ide> ];
<ide>
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['join'])
<add> ->onlyMethods(['join'])
<ide> ->setConstructorArgs([$this->connection, $this->table])
<ide> ->getMock();
<ide>
<ide> public function testNormalizedPath()
<ide> ];
<ide>
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['join'])
<add> ->onlyMethods(['join'])
<ide> ->setConstructorArgs([$this->connection, $this->table])
<ide> ->getMock();
<ide>
<ide><path>tests/TestCase/ORM/EntityTest.php
<ide> public function testExtractOriginalValues()
<ide> public function testSetOneParamWithSetter()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_setName'])
<add> ->addMethods(['_setName'])
<ide> ->getMock();
<ide> $entity->expects($this->once())->method('_setName')
<ide> ->with('Jones')
<ide> public function testSetOneParamWithSetter()
<ide> public function testMultipleWithSetter()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_setName', '_setStuff'])
<add> ->addMethods(['_setName', '_setStuff'])
<ide> ->getMock();
<ide> $entity->setAccess('*', true);
<ide> $entity->expects($this->once())->method('_setName')
<ide> public function testMultipleWithSetter()
<ide> public function testBypassSetters()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_setName', '_setStuff'])
<add> ->addMethods(['_setName', '_setStuff'])
<ide> ->getMock();
<ide> $entity->setAccess('*', true);
<ide>
<ide> public function testBypassSetters()
<ide> public function testConstructor()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['set'])
<add> ->onlyMethods(['set'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $entity->expects($this->at(0))
<ide> public function testConstructor()
<ide> public function testConstructorWithGuard()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['set'])
<add> ->onlyMethods(['set'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $entity->expects($this->once())
<ide> public function testGetNoGetters()
<ide> public function testGetCustomGetters()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getName'])
<add> ->addMethods(['_getName'])
<ide> ->getMock();
<ide> $entity->expects($this->any())
<ide> ->method('_getName')
<ide> public function testGetCustomGetters()
<ide> public function testGetCustomGettersAfterSet()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getName'])
<add> ->addMethods(['_getName'])
<ide> ->getMock();
<ide> $entity->expects($this->any())
<ide> ->method('_getName')
<ide> public function testGetCacheClearedByUnset()
<ide> {
<ide> /** @var \Cake\ORM\Entity|\PHPUnit\Framework\MockObject\MockObject $entity */
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getName'])
<add> ->addMethods(['_getName'])
<ide> ->getMock();
<ide> $entity->expects($this->any())->method('_getName')
<ide> ->will($this->returnCallback(function ($name) {
<ide> public function testGetCacheClearedByUnset()
<ide> public function testGetCamelCasedProperties()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getListIdName'])
<add> ->addMethods(['_getListIdName'])
<ide> ->getMock();
<ide> $entity->expects($this->any())->method('_getListIdName')
<ide> ->will($this->returnCallback(function ($name) {
<ide> public function testMagicSet()
<ide> public function testMagicSetWithSetter()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_setName'])
<add> ->addMethods(['_setName'])
<ide> ->getMock();
<ide> $entity->expects($this->once())->method('_setName')
<ide> ->with('Jones')
<ide> public function testMagicSetWithSetter()
<ide> public function testMagicSetWithSetterTitleCase()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_setName'])
<add> ->addMethods(['_setName'])
<ide> ->getMock();
<ide> $entity->expects($this->once())
<ide> ->method('_setName')
<ide> public function testMagicSetWithSetterTitleCase()
<ide> public function testMagicGetWithGetter()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getName'])
<add> ->addMethods(['_getName'])
<ide> ->getMock();
<ide> $entity->expects($this->once())->method('_getName')
<ide> ->with('Jones')
<ide> public function testMagicGetWithGetter()
<ide> public function testMagicGetWithGetterTitleCase()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getName'])
<add> ->addMethods(['_getName'])
<ide> ->getMock();
<ide> $entity->expects($this->once())
<ide> ->method('_getName')
<ide> public function testHas()
<ide> $this->assertFalse($entity->has(['id', 'nope']));
<ide>
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getThings'])
<add> ->addMethods(['_getThings'])
<ide> ->getMock();
<ide> $entity->expects($this->once())->method('_getThings')
<ide> ->will($this->returnValue(0));
<ide> public function testMagicIsset()
<ide> public function testMagicUnset()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['unset'])
<add> ->onlyMethods(['unset'])
<ide> ->getMock();
<ide> $entity->expects($this->at(0))
<ide> ->method('unset')
<ide> public function testIssetArrayAccess()
<ide> public function testGetArrayAccess()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['get'])
<add> ->onlyMethods(['get'])
<ide> ->getMock();
<ide> $entity->expects($this->at(0))
<ide> ->method('get')
<ide> public function testGetArrayAccess()
<ide> public function testSetArrayAccess()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['set'])
<add> ->onlyMethods(['set'])
<ide> ->getMock();
<ide> $entity->setAccess('*', true);
<ide>
<ide> public function testUnsetArrayAccess()
<ide> {
<ide> /** @var \Cake\ORM\Entity|\PHPUnit\Framework\MockObject\MockObject $entity */
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['unset'])
<add> ->onlyMethods(['unset'])
<ide> ->getMock();
<ide> $entity->expects($this->at(0))
<ide> ->method('unset')
<ide> public function testMethodCache()
<ide> {
<ide> /** @var \Cake\ORM\Entity|\PHPUnit\Framework\MockObject\MockObject $entity */
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_setFoo', '_getBar'])
<add> ->addMethods(['_setFoo', '_getBar'])
<ide> ->getMock();
<ide> /** @var \Cake\ORM\Entity|\PHPUnit\Framework\MockObject\MockObject $entity2 */
<ide> $entity2 = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_setBar'])
<add> ->addMethods(['_setBar'])
<ide> ->getMock();
<ide> $entity->expects($this->once())->method('_setFoo');
<ide> $entity->expects($this->once())->method('_getBar');
<ide> public function testSetGetLongPropertyNames()
<ide> {
<ide> /** @var \Cake\ORM\Entity|\PHPUnit\Framework\MockObject\MockObject $entity */
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getVeryLongProperty', '_setVeryLongProperty'])
<add> ->addMethods(['_getVeryLongProperty', '_setVeryLongProperty'])
<ide> ->getMock();
<ide> $entity->expects($this->once())->method('_getVeryLongProperty');
<ide> $entity->expects($this->once())->method('_setVeryLongProperty');
<ide> public function testPhpSerialize()
<ide> public function testJsonSerializeRecursive()
<ide> {
<ide> $phone = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['jsonSerialize'])
<add> ->onlyMethods(['jsonSerialize'])
<ide> ->getMock();
<ide> $phone->expects($this->once())->method('jsonSerialize')->will($this->returnValue(['something']));
<ide> $data = ['name' => 'James', 'age' => 20, 'phone' => $phone];
<ide> public function testIsNew()
<ide> public function testConstructorWithClean()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['clean'])
<add> ->onlyMethods(['clean'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $entity->expects($this->never())->method('clean');
<ide> $entity->__construct(['a' => 'b', 'c' => 'd']);
<ide>
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['clean'])
<add> ->onlyMethods(['clean'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $entity->expects($this->once())->method('clean');
<ide> public function testConstructorWithClean()
<ide> public function testConstructorWithMarkNew()
<ide> {
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['setNew', 'clean'])
<add> ->onlyMethods(['setNew', 'clean'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $entity->expects($this->never())->method('clean');
<ide> $entity->__construct(['a' => 'b', 'c' => 'd']);
<ide>
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['setNew'])
<add> ->onlyMethods(['setNew'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $entity->expects($this->once())->method('setNew');
<ide> public function testToArrayWithAccessor()
<ide> {
<ide> /** @var \Cake\ORM\Entity|\PHPUnit\Framework\MockObject\MockObject $entity */
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getName'])
<add> ->addMethods(['_getName'])
<ide> ->getMock();
<ide> $entity->setAccess('*', true);
<ide> $entity->set(['name' => 'Mark', 'email' => 'mark@example.com']);
<ide> public function testToArrayVirtualProperties()
<ide> {
<ide> /** @var \Cake\ORM\Entity|\PHPUnit\Framework\MockObject\MockObject $entity */
<ide> $entity = $this->getMockBuilder(Entity::class)
<del> ->setMethods(['_getName'])
<add> ->addMethods(['_getName'])
<ide> ->getMock();
<ide> $entity->setAccess('*', true);
<ide>
<ide><path>tests/TestCase/ORM/QueryTest.php
<ide> public function testClearContain()
<ide> {
<ide> /** @var \Cake\ORM\Query $query */
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['all'])
<add> ->onlyMethods(['all'])
<ide> ->setConstructorArgs([$this->connection, $this->table])
<ide> ->getMock();
<ide>
<ide> public function testClearContain()
<ide> public function testCollectionProxy($method, $arg, $return)
<ide> {
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['all'])
<add> ->onlyMethods(['all'])
<ide> ->setConstructorArgs([$this->connection, $this->table])
<ide> ->getMock();
<ide> $query->select();
<ide> public function testCacheErrorOnNonSelect()
<ide> public function testCacheReadIntegration()
<ide> {
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['execute'])
<add> ->onlyMethods(['execute'])
<ide> ->setConstructorArgs([$this->connection, $this->table])
<ide> ->getMock();
<ide> $resultSet = $this->getMockBuilder('Cake\ORM\ResultSet')
<ide> public function testCountCache()
<ide> {
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<ide> ->disableOriginalConstructor()
<del> ->setMethods(['_performCount'])
<add> ->onlyMethods(['_performCount'])
<ide> ->getMock();
<ide>
<ide> $query->expects($this->once())
<ide> public function testCountCacheDirty()
<ide> {
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<ide> ->disableOriginalConstructor()
<del> ->setMethods(['_performCount'])
<add> ->onlyMethods(['_performCount'])
<ide> ->getMock();
<ide>
<ide> $query->expects($this->at(0))
<ide><path>tests/TestCase/ORM/Rule/LinkConstraintTest.php
<ide> public function testNonMatchingKeyFields(): void
<ide> $ruleMock = $this
<ide> ->getMockBuilder(LinkConstraint::class)
<ide> ->setConstructorArgs(['Comments', LinkConstraint::STATUS_NOT_LINKED])
<del> ->setMethods(['_aliasFields'])
<add> ->onlyMethods(['_aliasFields'])
<ide> ->getMock();
<ide> $ruleMock
<ide> ->expects($this->once())
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testTableMethod()
<ide>
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['find'])
<add> ->onlyMethods(['find'])
<ide> ->setMockClassName('SpecialThingsTable')
<ide> ->getMock();
<ide> $this->assertSame('special_things', $table->getTable());
<ide> public function testSetAlias()
<ide>
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['find'])
<add> ->onlyMethods(['find'])
<ide> ->setMockClassName('SpecialThingTable')
<ide> ->getMock();
<ide> $this->assertSame('SpecialThing', $table->getAlias());
<ide> public function testSchemaInitialize()
<ide> {
<ide> $schema = $this->connection->getSchemaCollection()->describe('users');
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_initializeSchema'])
<add> ->onlyMethods(['_initializeSchema'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $table->expects($this->once())
<ide> public function testUpdateAllFailure()
<ide> {
<ide> $this->expectException(\Cake\Database\Exception::class);
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query'])
<add> ->onlyMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['execute'])
<add> ->onlyMethods(['execute'])
<ide> ->setConstructorArgs([$this->connection, $table])
<ide> ->getMock();
<ide> $table->expects($this->once())
<ide> public function testDeleteAllFailure()
<ide> {
<ide> $this->expectException(\Cake\Database\Exception::class);
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query'])
<add> ->onlyMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['execute'])
<add> ->onlyMethods(['execute'])
<ide> ->setConstructorArgs([$this->connection, $table])
<ide> ->getMock();
<ide> $table->expects($this->once())
<ide> public function testDeleteAllFailure()
<ide> public function testFindApplyOptions()
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query', 'findAll'])
<add> ->onlyMethods(['query', 'findAll'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<ide> public function testFindThreadedNoHydration()
<ide> public function testStackingFinders()
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['find', 'findList'])
<add> ->onlyMethods(['find', 'findList'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $params = [$this->connection, $table];
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['addDefaultTypes'])
<add> ->onlyMethods(['addDefaultTypes'])
<ide> ->setConstructorArgs($params)
<ide> ->getMock();
<ide>
<ide> public function testImplementedEvents()
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods([
<add> ->addMethods([
<ide> 'buildValidator',
<ide> 'beforeMarshal',
<ide> 'beforeFind',
<ide> public function testSaveNewEntityNoExists()
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['exists'])
<add> ->onlyMethods(['exists'])
<ide> ->setConstructorArgs([[
<ide> 'connection' => $this->connection,
<ide> 'alias' => 'Users',
<ide> public function testSavePrimaryKeyEntityExists()
<ide> $this->skipIfSqlServer();
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['exists'])
<add> ->onlyMethods(['exists'])
<ide> ->setConstructorArgs([[
<ide> 'connection' => $this->connection,
<ide> 'alias' => 'Users',
<ide> public function testSavePrimaryKeyEntityNoExists()
<ide> $this->skipIfSqlServer();
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['exists'])
<add> ->onlyMethods(['exists'])
<ide> ->setConstructorArgs([[
<ide> 'connection' => $this->connection,
<ide> 'alias' => 'Users',
<ide> public function testAfterSaveNotCalled()
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query'])
<add> ->onlyMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['execute', 'addDefaultTypes'])
<add> ->onlyMethods(['execute', 'addDefaultTypes'])
<ide> ->setConstructorArgs([$this->connection, $table])
<ide> ->getMock();
<ide> $statement = $this->getMockBuilder(StatementInterface::class)->getMock();
<ide> public function testAtomicSave()
<ide> $config = ConnectionManager::getConfig('test');
<ide>
<ide> $connection = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['begin', 'commit', 'inTransaction'])
<add> ->onlyMethods(['begin', 'commit', 'inTransaction'])
<ide> ->setConstructorArgs([$config])
<ide> ->getMock();
<ide> $connection->setDriver($this->connection->getDriver());
<ide>
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['getConnection'])
<add> ->onlyMethods(['getConnection'])
<ide> ->setConstructorArgs([['table' => 'users']])
<ide> ->getMock();
<ide> $table->expects($this->any())->method('getConnection')
<ide> public function testAtomicSaveRollback()
<ide> {
<ide> $this->expectException(\PDOException::class);
<ide> $connection = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['begin', 'rollback'])
<add> ->onlyMethods(['begin', 'rollback'])
<ide> ->setConstructorArgs([ConnectionManager::getConfig('test')])
<ide> ->getMock();
<ide> $connection->setDriver(ConnectionManager::get('test')->getDriver());
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query', 'getConnection'])
<add> ->onlyMethods(['query', 'getConnection'])
<ide> ->setConstructorArgs([['table' => 'users']])
<ide> ->getMock();
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['execute', 'addDefaultTypes'])
<add> ->onlyMethods(['execute', 'addDefaultTypes'])
<ide> ->setConstructorArgs([$connection, $table])
<ide> ->getMock();
<ide> $table->expects($this->any())->method('getConnection')
<ide> public function testAtomicSaveRollback()
<ide> public function testAtomicSaveRollbackOnFailure()
<ide> {
<ide> $connection = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['begin', 'rollback'])
<add> ->onlyMethods(['begin', 'rollback'])
<ide> ->setConstructorArgs([ConnectionManager::getConfig('test')])
<ide> ->getMock();
<ide> $connection->setDriver(ConnectionManager::get('test')->getDriver());
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query', 'getConnection', 'exists'])
<add> ->onlyMethods(['query', 'getConnection', 'exists'])
<ide> ->setConstructorArgs([['table' => 'users']])
<ide> ->getMock();
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['execute', 'addDefaultTypes'])
<add> ->onlyMethods(['execute', 'addDefaultTypes'])
<ide> ->setConstructorArgs([$connection, $table])
<ide> ->getMock();
<ide>
<ide> public function testSaveUpdateWithHint()
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['exists'])
<add> ->onlyMethods(['exists'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => ConnectionManager::get('test')]])
<ide> ->getMock();
<ide> $entity = new Entity([
<ide> public function testSaveUpdatePrimaryKeyNotModified()
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query'])
<add> ->onlyMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> ->getMock();
<ide>
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['execute', 'addDefaultTypes', 'set'])
<add> ->onlyMethods(['execute', 'addDefaultTypes', 'set'])
<ide> ->setConstructorArgs([$this->connection, $table])
<ide> ->getMock();
<ide>
<ide> public function testUpdateNoChange()
<ide> {
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query'])
<add> ->onlyMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $table->expects($this->never())->method('query');
<ide> public function testUpdateNoPrimaryButOtherKeys()
<ide> $this->expectException(\InvalidArgumentException::class);
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query'])
<add> ->onlyMethods(['query'])
<ide> ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $table->expects($this->never())->method('query');
<ide> public function testDeleteIsNew()
<ide>
<ide> /** @var \Cake\ORM\Table|\PHPUnit\Framework\MockObject\MockObject $table */
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['query'])
<add> ->onlyMethods(['query'])
<ide> ->setConstructorArgs([['connection' => $this->connection]])
<ide> ->getMock();
<ide> $table->expects($this->never())
<ide> public function testValidatorBehavior()
<ide> public function testValidationWithDefiner()
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['validationForOtherStuff'])
<add> ->addMethods(['validationForOtherStuff'])
<ide> ->getMock();
<ide> $table->expects($this->once())->method('validationForOtherStuff')
<ide> ->will($this->returnArgument(0));
<ide> public function testValidationWithDefiner()
<ide> public function testValidationWithBadDefiner()
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['validationBad'])
<add> ->addMethods(['validationBad'])
<ide> ->getMock();
<ide> $table->expects($this->once())
<ide> ->method('validationBad');
<ide> public function testSaveWithOptionBuilder()
<ide> public function testSaveCleanEntity()
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_processSave'])
<add> ->onlyMethods(['_processSave'])
<ide> ->getMock();
<ide> $entity = new Entity(
<ide> ['id' => 'foo'],
<ide> public function testBelongsToManyIntegration()
<ide> public function testSaveDeepAssociationOptions()
<ide> {
<ide> $articles = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert'])
<add> ->onlyMethods(['_insert'])
<ide> ->setConstructorArgs([['table' => 'articles', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $authors = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert'])
<add> ->onlyMethods(['_insert'])
<ide> ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $supervisors = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert', 'validate'])
<add> ->onlyMethods(['_insert'])
<add> ->addMethods(['validate'])
<ide> ->setConstructorArgs([[
<ide> 'table' => 'authors',
<ide> 'alias' => 'supervisors',
<ide> 'connection' => $this->connection,
<ide> ]])
<ide> ->getMock();
<ide> $tags = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert'])
<add> ->onlyMethods(['_insert'])
<ide> ->setConstructorArgs([['table' => 'tags', 'connection' => $this->connection]])
<ide> ->getMock();
<ide>
<ide> public function testBelongsToFluentInterface()
<ide> {
<ide> /** @var \TestApp\Model\Table\ArticlesTable $articles */
<ide> $articles = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert'])
<add> ->onlyMethods(['_insert'])
<ide> ->setConstructorArgs([['table' => 'articles', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> $authors = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert'])
<add> ->onlyMethods(['_insert'])
<ide> ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
<ide> ->getMock();
<ide>
<ide> public function testHasOneFluentInterface()
<ide> {
<ide> /** @var \TestApp\Model\Table\AuthorsTable $authors */
<ide> $authors = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert'])
<add> ->onlyMethods(['_insert'])
<ide> ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
<ide> ->getMock();
<ide>
<ide> public function testHasManyFluentInterface()
<ide> {
<ide> /** @var \TestApp\Model\Table\AuthorsTable $authors */
<ide> $authors = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert'])
<add> ->onlyMethods(['_insert'])
<ide> ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
<ide> ->getMock();
<ide>
<ide> public function testBelongsToManyFluentInterface()
<ide> {
<ide> /** @var \TestApp\Model\Table\AuthorsTable $authors */
<ide> $authors = $this->getMockBuilder(Table::class)
<del> ->setMethods(['_insert'])
<add> ->onlyMethods(['_insert'])
<ide> ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
<ide> ->getMock();
<ide> try {
<ide> public function testUnlinkHasManyEmpty()
<ide> public function testReplaceHasManyOnErrorDependentCascadeCallbacks()
<ide> {
<ide> $articles = $this->getMockBuilder(Table::class)
<del> ->setMethods(['delete'])
<add> ->onlyMethods(['delete'])
<ide> ->setConstructorArgs([[
<ide> 'connection' => $this->connection,
<ide> 'alias' => 'Articles',
<ide> public function testReplaceHasManyOnErrorDependentCascadeCallbacks()
<ide> $associations = new AssociationCollection();
<ide>
<ide> $hasManyArticles = $this->getMockBuilder('Cake\ORM\Association\HasMany')
<del> ->setMethods(['getTarget'])
<add> ->onlyMethods(['getTarget'])
<ide> ->setConstructorArgs([
<ide> 'articles',
<ide> [
<ide> function (EventInterface $event, EntityInterface $entity, ArrayObject $options)
<ide> public function testSimplifiedFind()
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['callFinder'])
<add> ->onlyMethods(['callFinder'])
<ide> ->setConstructorArgs([[
<ide> 'connection' => $this->connection,
<ide> 'schema' => ['id' => ['type' => 'integer']],
<ide> public function providerForTestGet()
<ide> public function testGet($options)
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['callFinder', 'query'])
<add> ->onlyMethods(['callFinder', 'query'])
<ide> ->setConstructorArgs([[
<ide> 'connection' => $this->connection,
<ide> 'schema' => [
<ide> public function testGet($options)
<ide> ->getMock();
<ide>
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
<add> ->onlyMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
<ide> ->setConstructorArgs([$this->connection, $table])
<ide> ->getMock();
<ide>
<ide> public function providerForTestGetWithCustomFinder()
<ide> public function testGetWithCustomFinder($options)
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['callFinder', 'query'])
<add> ->onlyMethods(['callFinder', 'query'])
<ide> ->setConstructorArgs([[
<ide> 'connection' => $this->connection,
<ide> 'schema' => [
<ide> public function testGetWithCustomFinder($options)
<ide> ->getMock();
<ide>
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
<add> ->onlyMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
<ide> ->setConstructorArgs([$this->connection, $table])
<ide> ->getMock();
<ide>
<ide> public function providerForTestGetWithCache()
<ide> public function testGetWithCache($options, $cacheKey, $cacheConfig)
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['callFinder', 'query'])
<add> ->onlyMethods(['callFinder', 'query'])
<ide> ->setConstructorArgs([[
<ide> 'connection' => $this->connection,
<ide> 'schema' => [
<ide> public function testGetWithCache($options, $cacheKey, $cacheConfig)
<ide> $table->setTable('table_name');
<ide>
<ide> $query = $this->getMockBuilder('Cake\ORM\Query')
<del> ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
<add> ->onlyMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
<ide> ->setConstructorArgs([$this->connection, $table])
<ide> ->getMock();
<ide>
<ide> public function testGetExceptionOnTooMuchData()
<ide> public function testPatchEntityMarshallerUsage()
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['marshaller'])
<add> ->onlyMethods(['marshaller'])
<ide> ->getMock();
<ide> $marshaller = $this->getMockBuilder('Cake\ORM\Marshaller')
<ide> ->setConstructorArgs([$table])
<ide> public function testPatchEntity()
<ide> public function testPatchEntitiesMarshallerUsage()
<ide> {
<ide> $table = $this->getMockBuilder(Table::class)
<del> ->setMethods(['marshaller'])
<add> ->onlyMethods(['marshaller'])
<ide> ->getMock();
<ide> $marshaller = $this->getMockBuilder('Cake\ORM\Marshaller')
<ide> ->setConstructorArgs([$table])
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php
<ide> public function testRoutesHookCallsPluginHook()
<ide>
<ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/app/articles']);
<ide> $app = $this->getMockBuilder(Application::class)
<del> ->setMethods(['pluginRoutes'])
<add> ->onlyMethods(['pluginRoutes'])
<ide> ->setConstructorArgs([CONFIG])
<ide> ->getMock();
<ide> $app->expects($this->once())
<ide><path>tests/TestCase/Routing/Route/RouteTest.php
<ide> public function testParseRequestDelegates()
<ide> {
<ide> /** @var \Cake\Routing\Route\Route|\PHPUnit\Framework\MockObject\MockObject $route */
<ide> $route = $this->getMockBuilder('Cake\Routing\Route\Route')
<del> ->setMethods(['parse'])
<add> ->onlyMethods(['parse'])
<ide> ->setConstructorArgs(['/forward', ['controller' => 'Articles', 'action' => 'index']])
<ide> ->getMock();
<ide>
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> public function testRegisterMiddleware()
<ide> $this->assertSame($result, $this->collection);
<ide>
<ide> $mock = $this->getMockBuilder('\stdClass')
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide> $result = $this->collection->registerMiddleware('callable', $mock);
<ide> $this->assertSame($result, $this->collection);
<ide> public function testMiddlewareGroup()
<ide> });
<ide>
<ide> $mock = $this->getMockBuilder('\stdClass')
<del> ->setMethods(['__invoke'])
<add> ->addMethods(['__invoke'])
<ide> ->getMock();
<ide> $result = $this->collection->registerMiddleware('callable', $mock);
<ide> $this->collection->registerMiddleware('callable', $mock);
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testUrlFullUrlReturnFromRoute()
<ide> $url = 'http://example.com/posts/view/1';
<ide>
<ide> $route = $this->getMockBuilder('Cake\Routing\Route\Route')
<del> ->setMethods(['match'])
<add> ->onlyMethods(['match'])
<ide> ->setConstructorArgs(['/:controller/:action/*'])
<ide> ->getMock();
<ide> $route->expects($this->any())
<ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php
<ide> public function testLoadConnectionAliasUsage()
<ide>
<ide> // This connection should _not_ be used.
<ide> $other = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['execute'])
<add> ->onlyMethods(['execute'])
<ide> ->setConstructorArgs([['driver' => $connection->getDriver()]])
<ide> ->getMock();
<ide> $other->expects($this->never())
<ide> public function testLoadConnectionAliasUsage()
<ide> // This connection should be used instead of
<ide> // the 'other' connection as the alias should not be ignored.
<ide> $testOther = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['execute'])
<add> ->onlyMethods(['execute'])
<ide> ->setConstructorArgs([[
<ide> 'database' => $connection->config()['database'],
<ide> 'driver' => $connection->getDriver(),
<ide> public function testLoadConnectionAliasUsage()
<ide> public function testLoadSingle()
<ide> {
<ide> $test = $this->getMockBuilder('Cake\TestSuite\TestCase')
<del> ->setMethods(['getFixtures'])
<add> ->onlyMethods(['getFixtures'])
<ide> ->getMock();
<ide> $test->autoFixtures = false;
<ide> $test->expects($this->any())
<ide> public function testExceptionOnLoad()
<ide> ->willReturn(['core.Products']);
<ide>
<ide> $manager = $this->getMockBuilder(FixtureManager::class)
<del> ->setMethods(['_runOperation'])
<add> ->onlyMethods(['_runOperation'])
<ide> ->getMock();
<ide> $manager->expects($this->any())
<ide> ->method('_runOperation')
<ide> public function testExceptionOnLoad()
<ide> public function testExceptionOnLoadFixture($method, $expectedMessage)
<ide> {
<ide> $fixture = $this->getMockBuilder('Cake\Test\Fixture\ProductsFixture')
<del> ->setMethods([$method])
<add> ->onlyMethods([$method])
<ide> ->getMock();
<ide> $fixture->expects($this->once())
<ide> ->method($method)
<ide> public function testExceptionOnLoadFixture($method, $expectedMessage)
<ide>
<ide> /** @var \Cake\TestSuite\Fixture\FixtureManager|\PHPUnit\Framework\MockObject\MockObject $manager */
<ide> $manager = $this->getMockBuilder(FixtureManager::class)
<del> ->setMethods(['_fixtureConnections'])
<add> ->onlyMethods(['_fixtureConnections'])
<ide> ->getMock();
<ide> $manager->expects($this->any())
<ide> ->method('_fixtureConnections')
<ide><path>tests/TestCase/TestSuite/TestFixtureTest.php
<ide> public function testInitNoImportNoFields()
<ide> $this->assertSame(['id', 'letter'], $fixture->getTableSchema()->columns());
<ide>
<ide> $db = $this->getMockBuilder('Cake\Database\Connection')
<del> ->setMethods(['prepare', 'execute'])
<add> ->onlyMethods(['prepare', 'execute'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<ide> $db->expects($this->never())
<ide><path>tests/TestCase/TestSuite/TestSuiteTest.php
<ide> public function testAddTestDirectory()
<ide> $count = count(glob($testFolder . DS . '*Test.php'));
<ide>
<ide> $suite = $this->getMockBuilder('Cake\TestSuite\TestSuite')
<del> ->setMethods(['addTestFile'])
<add> ->onlyMethods(['addTestFile'])
<ide> ->getMock();
<ide> $suite
<ide> ->expects($this->exactly($count))
<ide> public function testAddTestDirectoryRecursive()
<ide> $count += count(glob($testFolder . DS . 'Engine/*Test.php'));
<ide>
<ide> $suite = $this->getMockBuilder('Cake\TestSuite\TestSuite')
<del> ->setMethods(['addTestFile'])
<add> ->onlyMethods(['addTestFile'])
<ide> ->getMock();
<ide> $suite
<ide> ->expects($this->exactly($count))
<ide> public function testAddTestDirectoryRecursiveWithHidden()
<ide> touch($path . DS . '.HiddenTest.php');
<ide>
<ide> $suite = $this->getMockBuilder('Cake\TestSuite\TestSuite')
<del> ->setMethods(['addTestFile'])
<add> ->onlyMethods(['addTestFile'])
<ide> ->getMock();
<ide> $suite
<ide> ->expects($this->exactly(1))
<ide> public function testAddTestDirectoryRecursiveWithNonPhp()
<ide> touch($path . DS . 'NotHiddenTest.php');
<ide>
<ide> $suite = $this->getMockBuilder('Cake\TestSuite\TestSuite')
<del> ->setMethods(['addTestFile'])
<add> ->onlyMethods(['addTestFile'])
<ide> ->getMock();
<ide> $suite
<ide> ->expects($this->exactly(1))
<ide><path>tests/TestCase/Validation/ValidatorTest.php
<ide> public function testErrorsFromCustomProvider()
<ide> ->add('title', 'cool', ['rule' => 'isCool', 'provider' => 'thing']);
<ide>
<ide> $thing = $this->getMockBuilder('\stdClass')
<del> ->setMethods(['isCool'])
<add> ->addMethods(['isCool'])
<ide> ->getMock();
<ide> $thing->expects($this->once())->method('isCool')
<ide> ->will($this->returnCallback(function ($data, $context) use ($thing) {
<ide> public function testMethodsWithExtraArguments()
<ide> 'provider' => 'thing',
<ide> ]);
<ide> $thing = $this->getMockBuilder('\stdClass')
<del> ->setMethods(['isCool'])
<add> ->addMethods(['isCool'])
<ide> ->getMock();
<ide> $thing->expects($this->once())->method('isCool')
<ide> ->will($this->returnCallback(function ($data, $a, $b, $context) use ($thing) {
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function setUp(): void
<ide> Router::setRequest($request);
<ide>
<ide> $this->View = $this->getMockBuilder(View::class)
<del> ->setMethods(['append'])
<add> ->onlyMethods(['append'])
<ide> ->setConstructorArgs([$request])
<ide> ->getMock();
<ide> $this->Html = new HtmlHelper($this->View);
<ide><path>tests/TestCase/View/Helper/NumberHelperTest.php
<ide> public function methodProvider()
<ide> public function testNumberHelperProxyMethodCalls($method)
<ide> {
<ide> $number = $this->getMockBuilder(NumberMock::class)
<del> ->setMethods([$method])
<add> ->addMethods([$method])
<ide> ->getMock();
<ide> $helper = new NumberHelperTestObject($this->View, ['engine' => NumberMock::class]);
<ide> $helper->attach($number);
<ide><path>tests/TestCase/View/Helper/TextHelperTest.php
<ide> public function testTextHelperProxyMethodCalls()
<ide> 'stripLinks', 'toList',
<ide> ];
<ide> $String = $this->getMockBuilder(TextMock::class)
<del> ->setMethods($methods)
<add> ->addMethods($methods)
<ide> ->getMock();
<ide> $Text = new TextHelperTestObject($this->View, ['engine' => TextMock::class]);
<ide> $Text->attach($String);
<ide> public function testTextHelperProxyMethodCalls()
<ide> 'excerpt',
<ide> ];
<ide> $String = $this->getMockBuilder(TextMock::class)
<del> ->setMethods($methods)
<add> ->addMethods($methods)
<ide> ->getMock();
<ide> $Text = new TextHelperTestObject($this->View, ['engine' => TextMock::class]);
<ide> $Text->attach($String);
<ide> public function testTextHelperProxyMethodCalls()
<ide> 'highlight',
<ide> ];
<ide> $String = $this->getMockBuilder(TextMock::class)
<del> ->setMethods($methods)
<add> ->addMethods($methods)
<ide> ->getMock();
<ide> $Text = new TextHelperTestObject($this->View, ['engine' => TextMock::class]);
<ide> $Text->attach($String);
<ide> public function testTextHelperProxyMethodCalls()
<ide> 'tail', 'truncate',
<ide> ];
<ide> $String = $this->getMockBuilder(TextMock::class)
<del> ->setMethods($methods)
<add> ->addMethods($methods)
<ide> ->getMock();
<ide> $Text = new TextHelperTestObject($this->View, ['engine' => TextMock::class]);
<ide> $Text->attach($String);
| 70
|
Java
|
Java
|
use correct header for version in connected frame
|
364bc357095e34504b10bc138b8c59da578dd14f
|
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompProtocolHandler.java
<ide> protected void handleConnect(WebSocketSession session, Message<?> message) throw
<ide>
<ide> Set<String> acceptVersions = connectHeaders.getAcceptVersion();
<ide> if (acceptVersions.contains("1.2")) {
<del> connectedHeaders.setAcceptVersion("1.2");
<add> connectedHeaders.setVersion("1.2");
<ide> }
<ide> else if (acceptVersions.contains("1.1")) {
<del> connectedHeaders.setAcceptVersion("1.1");
<add> connectedHeaders.setVersion("1.1");
<ide> }
<ide> else if (acceptVersions.isEmpty()) {
<ide> // 1.0
| 1
|
Text
|
Text
|
add additional test to telephone regex challenge
|
02f232caf4314a3f8593f11732de6f76a4c60d18
|
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.md
<ide> assert(telephoneCheck('(555-555-5555') === false);
<ide> assert(telephoneCheck('(555)5(55?)-5555') === false);
<ide> ```
<ide>
<add>`telephoneCheck("55 55-55-555-5")` should return `false`.
<add>
<add>```js
<add>assert(telephoneCheck('55 55-55-555-5') === false);
<add>```
<add>
<ide> # --seed--
<ide>
<ide> ## --seed-contents--
| 1
|
Text
|
Text
|
add example for update_all vs. update
|
eae7043405b4efd6007848cd1d56361bfbfe0eb9
|
<ide><path>guides/source/active_record_basics.md
<ide> hand, you'd like to update several records in bulk, you may find the
<ide> User.update_all "max_login_attempts = 3, must_change_password = 'true'"
<ide> ```
<ide>
<add>This is the same as if you wrote:
<add>
<add>```ruby
<add>User.update(:all, max_login_attempts: 3, must_change_password: true)
<add>```
<add>
<ide> ### Delete
<ide>
<ide> Likewise, once retrieved an Active Record object can be destroyed which removes
| 1
|
Javascript
|
Javascript
|
show meaningful values for boxed primitives
|
8874a317484b8865c5fbad74d3af6155994df583
|
<ide><path>lib/util.js
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> keys = Object.getOwnPropertyNames(value);
<ide> }
<ide>
<add> // This could be a boxed primitive (new String(), etc.), check valueOf()
<add> // NOTE: Avoid calling `valueOf` on `Date` instance because it will return
<add> // a number which, when object has some additional user-stored `keys`,
<add> // will be printed out.
<add> var formatted;
<add> var raw = value;
<add> try {
<add> // the .valueOf() call can fail for a multitude of reasons
<add> if (!isDate(value))
<add> raw = value.valueOf();
<add> } catch (e) {
<add> // ignore...
<add> }
<add>
<add> if (isString(raw)) {
<add> // for boxed Strings, we have to remove the 0-n indexed entries,
<add> // since they just noisey up the output and are redundant
<add> keys = keys.filter(function(key) {
<add> return !(key >= 0 && key < raw.length);
<add> });
<add> }
<add>
<ide> // Some type of object without properties can be shortcutted.
<ide> if (keys.length === 0) {
<ide> if (isFunction(value)) {
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> if (isError(value)) {
<ide> return formatError(value);
<ide> }
<add> // now check the `raw` value to handle boxed primitives
<add> if (isString(raw)) {
<add> formatted = formatPrimitiveNoColor(ctx, raw);
<add> return ctx.stylize('[String: ' + formatted + ']', 'string');
<add> }
<add> if (isNumber(raw)) {
<add> formatted = formatPrimitiveNoColor(ctx, raw);
<add> return ctx.stylize('[Number: ' + formatted + ']', 'number');
<add> }
<add> if (isBoolean(raw)) {
<add> formatted = formatPrimitiveNoColor(ctx, raw);
<add> return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean');
<add> }
<ide> }
<ide>
<ide> var base = '', array = false, braces = ['{', '}'];
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> base = ' ' + formatError(value);
<ide> }
<ide>
<add> // Make boxed primitive Strings look like such
<add> if (isString(raw)) {
<add> formatted = formatPrimitiveNoColor(ctx, raw);
<add> base = ' ' + '[String: ' + formatted + ']';
<add> }
<add>
<add> // Make boxed primitive Numbers look like such
<add> if (isNumber(raw)) {
<add> formatted = formatPrimitiveNoColor(ctx, raw);
<add> base = ' ' + '[Number: ' + formatted + ']';
<add> }
<add>
<add> // Make boxed primitive Booleans look like such
<add> if (isBoolean(raw)) {
<add> formatted = formatPrimitiveNoColor(ctx, raw);
<add> base = ' ' + '[Boolean: ' + formatted + ']';
<add> }
<add>
<ide> if (keys.length === 0 && (!array || value.length == 0)) {
<ide> return braces[0] + base + braces[1];
<ide> }
<ide> function formatPrimitive(ctx, value) {
<ide> }
<ide>
<ide>
<add>function formatPrimitiveNoColor(ctx, value) {
<add> var stylize = ctx.stylize;
<add> ctx.stylize = stylizeNoColor;
<add> var str = formatPrimitive(ctx, value);
<add> ctx.stylize = stylize;
<add> return str;
<add>}
<add>
<add>
<ide> function formatError(value) {
<ide> return '[' + Error.prototype.toString.call(value) + ']';
<ide> }
<ide><path>test/simple/test-util-inspect.js
<ide> test_lines({
<ide> very_long_key: 'very_long_value',
<ide> even_longer_key: ['with even longer value in array']
<ide> });
<add>
<add>// test boxed primitives output the correct values
<add>assert.equal(util.inspect(new String('test')), '[String: \'test\']');
<add>assert.equal(util.inspect(new Boolean(false)), '[Boolean: false]');
<add>assert.equal(util.inspect(new Boolean(true)), '[Boolean: true]');
<add>assert.equal(util.inspect(new Number(0)), '[Number: 0]');
<add>assert.equal(util.inspect(new Number(-0)), '[Number: -0]');
<add>assert.equal(util.inspect(new Number(-1.1)), '[Number: -1.1]');
<add>assert.equal(util.inspect(new Number(13.37)), '[Number: 13.37]');
<add>
<add>// test boxed primitives with own properties
<add>var str = new String('baz');
<add>str.foo = 'bar';
<add>assert.equal(util.inspect(str), '{ [String: \'baz\'] foo: \'bar\' }');
<add>
<add>var bool = new Boolean(true);
<add>bool.foo = 'bar';
<add>assert.equal(util.inspect(bool), '{ [Boolean: true] foo: \'bar\' }');
<add>
<add>var num = new Number(13.37);
<add>num.foo = 'bar';
<add>assert.equal(util.inspect(num), '{ [Number: 13.37] foo: \'bar\' }');
| 2
|
Text
|
Text
|
remove git conflict markers in documentation
|
6d1959b265d8ccee81bd32f59bb71b71b070a06a
|
<ide><path>share/doc/homebrew/Formula-Cookbook.md
<ide> For example, Ruby 1.9’s gems should be installed to `var/lib/ruby/` so that ge
<ide>
<ide> ### launchd plist files
<ide>
<del><<<<<<< 12f42a6761cb29ed3c9715fe2cbccff02bdc448f
<del>Homebrew provides two Formula methods for launchd plist files. `plist_name` will return `homebrew.mxcl.<formula>`, and `plist_path` will return, for example, `/usr/local/Cellar/foo/0.1/homebrew.mxcl.foo.plist`.
<add>Homebrew provides two Formula methods for launchd plist files. [`plist_name`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#plist_name-instance_method) will return e.g. `homebrew.mxcl.<formula>` and [`plist_path`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#plist_path-instance_method) will return e.g. `/usr/local/Cellar/foo/0.1/homebrew.mxcl.foo.plist`.
<ide>
<ide> ## Updating formulae
<ide>
<ide> Homebrew wants to maintain a consistent Ruby style across all formulae based on
<ide> * The order of methods in a formula should be consistent with other formulae (e.g.: `def patches` goes before `def install`)
<ide> * An empty line is required before the `__END__` line
<ide>
<del>
<del>=======
<del>Homebrew provides two Formula methods for launchd plist files. [`plist_name`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#plist_name-instance_method) will return e.g. `homebrew.mxcl.<formula>` and [`plist_path`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#plist_path-instance_method) will return e.g. `/usr/local/Cellar/foo/0.1/homebrew.mxcl.foo.plist`.
<del>>>>>>>> Overhaul, simplify and cleanup documentation.
<del>
<ide> # Troubleshooting for people writing new formulae
<ide>
<ide> ### Version detection fails
| 1
|
Ruby
|
Ruby
|
improve the performance of reading attributes
|
08576b94ad4f19dfc368619d7751e211d23dcad8
|
<ide><path>activerecord/lib/active_record/aggregations.rb
<ide> def composed_of(part_id, options = {})
<ide> private
<ide> def reader_method(name, class_name, mapping, allow_nil, constructor)
<ide> define_method(name) do
<del> if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|key, _| !read_attribute(key).nil? })
<del> attrs = mapping.collect {|key, _| read_attribute(key)}
<add> if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|key, _| !_read_attribute(key).nil? })
<add> attrs = mapping.collect {|key, _| _read_attribute(key)}
<ide> object = constructor.respond_to?(:call) ?
<ide> constructor.call(*attrs) :
<ide> class_name.constantize.send(constructor, *attrs)
<ide><path>activerecord/lib/active_record/associations/has_many_association.rb
<ide> def empty?
<ide> # the loaded flag is set to true as well.
<ide> def count_records
<ide> count = if has_cached_counter?
<del> owner.read_attribute cached_counter_attribute_name
<add> owner._read_attribute cached_counter_attribute_name
<ide> else
<ide> scope.count
<ide> end
<ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb
<ide> def initialize(owner, reflection)
<ide> # SELECT query will be generated by using #length instead.
<ide> def size
<ide> if has_cached_counter?
<del> owner.read_attribute cached_counter_attribute_name(reflection)
<add> owner._read_attribute cached_counter_attribute_name(reflection)
<ide> elsif loaded?
<ide> target.size
<ide> else
<ide><path>activerecord/lib/active_record/attribute_methods.rb
<ide> def attribute_for_inspect(attr_name)
<ide> # task.attribute_present?(:title) # => true
<ide> # task.attribute_present?(:is_done) # => true
<ide> def attribute_present?(attribute)
<del> value = read_attribute(attribute)
<add> value = _read_attribute(attribute)
<ide> !value.nil? && !(value.respond_to?(:empty?) && value.empty?)
<ide> end
<ide>
<ide> def pk_attribute?(name)
<ide> end
<ide>
<ide> def typecasted_attribute_value(name)
<del> read_attribute(name)
<add> _read_attribute(name)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb
<ide> def old_attribute_value(attr)
<ide> if attribute_changed?(attr)
<ide> changed_attributes[attr]
<ide> else
<del> clone_attribute_value(:read_attribute, attr)
<add> clone_attribute_value(:_read_attribute, attr)
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/attribute_methods/primary_key.rb
<ide> def to_key
<ide> def id
<ide> if pk = self.class.primary_key
<ide> sync_with_transaction_state
<del> read_attribute(pk)
<add> _read_attribute(pk)
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/attribute_methods/read.rb
<ide> def method_body(method_name, const_name)
<ide> <<-EOMETHOD
<ide> def #{method_name}
<ide> name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name}
<del> read_attribute(name) { |n| missing_attribute(n, caller) }
<add> _read_attribute(name) { |n| missing_attribute(n, caller) }
<ide> end
<ide> EOMETHOD
<ide> end
<ide> def define_method_attribute(name)
<ide> generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
<ide> def #{temp_method}
<ide> name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name}
<del> read_attribute(name) { |n| missing_attribute(n, caller) }
<add> _read_attribute(name) { |n| missing_attribute(n, caller) }
<ide> end
<ide> STR
<ide>
<ide> def #{temp_method}
<ide> def read_attribute(attr_name, &block)
<ide> name = attr_name.to_s
<ide> name = self.class.primary_key if name == ID
<del> @attributes.fetch_value(name, &block)
<add> _read_attribute(name, &block)
<add> end
<add>
<add> # This method exists to avoid the expensive primary_key check internally, without
<add> # breaking compatibility with the read_attribute API
<add> def _read_attribute(attr_name) # :nodoc:
<add> @attributes.fetch_value(attr_name.to_s) { |n| yield n if block_given? }
<ide> end
<ide>
<ide> private
<ide>
<ide> def attribute(attribute_name)
<del> read_attribute(attribute_name)
<add> _read_attribute(attribute_name)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/attribute_set.rb
<ide> def keys
<ide> attributes.initialized_keys
<ide> end
<ide>
<del> def fetch_value(name, &block)
<del> self[name].value(&block)
<add> def fetch_value(name)
<add> self[name].value { |n| yield n if block_given? }
<ide> end
<ide>
<ide> def write_from_database(name, value)
<ide><path>activerecord/lib/active_record/enum.rb
<ide> def _enum_methods_module
<ide> private
<ide> def save_changed_attribute(attr_name, old)
<ide> if (mapping = self.class.defined_enums[attr_name.to_s])
<del> value = read_attribute(attr_name)
<add> value = _read_attribute(attr_name)
<ide> if attribute_changed?(attr_name)
<ide> if mapping[old] == value
<ide> clear_attribute_changes([attr_name])
<ide><path>activerecord/lib/active_record/reflection.rb
<ide> def initialize(name, scope, options, active_record)
<ide> def association_scope_cache(conn, owner)
<ide> key = conn.prepared_statements
<ide> if polymorphic?
<del> key = [key, owner.read_attribute(@foreign_type)]
<add> key = [key, owner._read_attribute(@foreign_type)]
<ide> end
<ide> @association_scope_cache[key] ||= @scope_lock.synchronize {
<ide> @association_scope_cache[key] ||= yield
<ide><path>activerecord/lib/active_record/validations/uniqueness.rb
<ide> def scope_relation(record, table, relation)
<ide> scope_value = record.send(reflection.foreign_key)
<ide> scope_item = reflection.foreign_key
<ide> else
<del> scope_value = record.read_attribute(scope_item)
<add> scope_value = record._read_attribute(scope_item)
<ide> end
<ide> relation = relation.and(table[scope_item].eq(scope_value))
<ide> end
<ide><path>activerecord/test/cases/inheritance_test.rb
<ide> def test_class_with_blank_sti_name
<ide> company = Company.first
<ide> company = company.dup
<ide> company.extend(Module.new {
<del> def read_attribute(name)
<add> def _read_attribute(name)
<ide> return ' ' if name == 'type'
<ide> super
<ide> end
| 12
|
Text
|
Text
|
create model card for roberta-hindi-guj-san
|
fa265230a200f037592377987c6d963d2601e6d0
|
<ide><path>model_cards/surajp/RoBERTa-hindi-guj-san/README.md
<add>---
<add>language: "multilingual"
<add>tags:
<add>- Hindi
<add>- Sanskrit
<add>- Gujarati
<add>- Indic
<add>- roberta
<add>license: "MIT"
<add>datasets:
<add>- Wikipedia (Hindi, Sanskrit, Gujarati)
<add>metrics:
<add>- perplexity
<add>---
<add>
<add># RoBERTa-hindi-guj-san
<add>
<add>## Model description
<add>
<add>Multillingual RoBERTa like model trained on Wikipedia articles of Hindi, Sanskrit, Gujarati languages. The tokenizer was trained on combined text.
<add>However, Hindi text was used to pre-train the model and then it was fine-tuned on Sanskrit and Gujarati Text combined hoping that pre-training with Hindi
<add>will help the model learn similar languages.
<add>
<add>### Configuration
<add>
<add>| Parameter | Value |
<add>|---|---|
<add>| `hidden_size` | 768 |
<add>| `num_attention_heads` | 12 |
<add>| `num_hidden_layers` | 6 |
<add>| `vocab_size` | 30522 |
<add>|`model_type`|`roberta`|
<add>
<add>## Intended uses & limitations
<add>
<add>#### How to use
<add>
<add>```python
<add># Example usage
<add>from transformers import AutoTokenizer, AutoModelWithLMHead, pipeline
<add>
<add>tokenizer = AutoTokenizer.from_pretrained("surajp/RoBERTa-hindi-guj-san")
<add>model = AutoModelWithLMHead.from_pretrained("surajp/RoBERTa-hindi-guj-san")
<add>
<add>fill_mask = pipeline(
<add> "fill-mask",
<add> model=model,
<add> tokenizer=tokenizer
<add>)
<add>
<add># Sanskrit: इयं भाषा न केवलं भारतस्य अपि तु विश्वस्य प्राचीनतमा भाषा इति मन्यते।
<add># Hindi: अगर आप अब अभ्यास नहीं करते हो तो आप अपने परीक्षा में मूर्खतापूर्ण गलतियाँ करोगे।
<add># Gujarati: ગુજરાતમાં ૧૯મી માર્ચ સુધી કોઈ સકારાત્મક (પોઝીટીવ) રીપોર્ટ આવ્યો <mask> હતો.
<add>fill_mask("ગુજરાતમાં ૧૯મી માર્ચ સુધી કોઈ સકારાત્મક (પોઝીટીવ) રીપોર્ટ આવ્યો <mask> હતો.")
<add>
<add>'''
<add>Output:
<add>--------
<add>[
<add>{'score': 0.07849744707345963, 'sequence': '<s> ગુજરાતમાં ૧૯મી માર્ચ સુધી કોઈ સકારાત્મક (પોઝીટીવ) રીપોર્ટ આવ્યો જ હતો.</s>', 'token': 390},
<add>{'score': 0.06273336708545685, 'sequence': '<s> ગુજરાતમાં ૧૯મી માર્ચ સુધી કોઈ સકારાત્મક (પોઝીટીવ) રીપોર્ટ આવ્યો ન હતો.</s>', 'token': 478},
<add>{'score': 0.05160355195403099, 'sequence': '<s> ગુજરાતમાં ૧૯મી માર્ચ સુધી કોઈ સકારાત્મક (પોઝીટીવ) રીપોર્ટ આવ્યો થઇ હતો.</s>', 'token': 2075},
<add>{'score': 0.04751499369740486, 'sequence': '<s> ગુજરાતમાં ૧૯મી માર્ચ સુધી કોઈ સકારાત્મક (પોઝીટીવ) રીપોર્ટ આવ્યો એક હતો.</s>', 'token': 600},
<add>{'score': 0.03788900747895241, 'sequence': '<s> ગુજરાતમાં ૧૯મી માર્ચ સુધી કોઈ સકારાત્મક (પોઝીટીવ) રીપોર્ટ આવ્યો પણ હતો.</s>', 'token': 840}
<add>]
<add>
<add>```
<add>
<add>## Training data
<add>
<add>Cleaned wikipedia articles in Hindi, Sanskrit and Gujarati on Kaggle. It contains training as well as evaluation text.
<add>Used in [iNLTK](https://github.com/goru001/inltk)
<add>
<add>- [Hindi](https://www.kaggle.com/disisbig/hindi-wikipedia-articles-172k)
<add>- [Gujarati](https://www.kaggle.com/disisbig/gujarati-wikipedia-articles)
<add>- [Sanskrit](https://www.kaggle.com/disisbig/sanskrit-wikipedia-articles)
<add>
<add>## Training procedure
<add>
<add>- On TPU (using `xla_spawn.py`)
<add>- For language modelling
<add>- Iteratively increasing `--block_size` from 128 to 256 over epochs
<add>- Tokenizer trained on combined text
<add>- Pre-training with Hindi and fine-tuning on Sanskrit and Gujarati texts
<add>
<add>```
<add>--model_type distillroberta-base \
<add>--model_name_or_path "/content/SanHiGujBERTa" \
<add>--mlm_probability 0.20 \
<add>--line_by_line \
<add>--save_total_limit 2 \
<add>--per_device_train_batch_size 128 \
<add>--per_device_eval_batch_size 128 \
<add>--num_train_epochs 5 \
<add>--block_size 256 \
<add>--seed 108 \
<add>--overwrite_output_dir \
<add>```
<add>
<add>## Eval results
<add>
<add>perplexity = 2.920005983224673
<add>
<add>
<add>
<add>> Created by [Suraj Parmar/@parmarsuraj99](https://twitter.com/parmarsuraj99) | [LinkedIn](https://www.linkedin.com/in/parmarsuraj99/)
<add>
<add>> Made with <span style="color: #e25555;">♥</span> in India
| 1
|
Javascript
|
Javascript
|
upgrade chrome in saucelabs to latest
|
75893ae9e78a5dcaed58f393c5dee676e1966fd0
|
<ide><path>karma-shared.conf.js
<ide> module.exports = function(config, specificOptions) {
<ide> 'SL_Chrome': {
<ide> base: 'SauceLabs',
<ide> browserName: 'chrome',
<del> version: '43'
<add> version: '45'
<ide> },
<ide> 'SL_Firefox': {
<ide> base: 'SauceLabs',
| 1
|
Javascript
|
Javascript
|
add util.inspect test for null maxstringlength
|
382ed92fa8a27aa84f235d412560c0cf8ba6c175
|
<ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(
<ide> util.inspect(x, { maxStringLength: 4 }),
<ide> "'aaaa'... 999996 more characters"
<ide> );
<add> assert.match(util.inspect(x, { maxStringLength: null }), /a'$/);
<ide> }
<ide>
<ide> {
| 1
|
Python
|
Python
|
join default max retries now 5
|
54a41a870e90d41e403f53a083ee1b93a0e36fde
|
<ide><path>funtests/stress/stress/suite.py
<ide> def _revoketerm(self, wait=None, terminate=True,
<ide> def missing_results(self, r):
<ide> return [res.id for res in r if res.id not in res.backend._cache]
<ide>
<del> def join(self, r, propagate=False, max_retries=1, **kwargs):
<add> def join(self, r, propagate=False, max_retries=5, **kwargs):
<ide> received = []
<ide>
<ide> def on_result(task_id, value):
<ide><path>funtests/stress/stress/templates.py
<ide> class default(object):
<ide> CELERY_DEFAULT_QUEUE = CSTRESS_QUEUE
<ide> CELERY_TASK_SERIALIZER = 'json'
<ide> CELERY_RESULT_SERIALIZER = 'json'
<del> CELERY_RESULT_PERSISTENT = False
<ide> CELERY_QUEUES = [
<ide> Queue(CSTRESS_QUEUE,
<ide> exchange=Exchange(CSTRESS_QUEUE),
| 2
|
Go
|
Go
|
use diff ids from image configuration
|
633f9252b8e066ef7a1a738ddc84c3970379844e
|
<ide><path>distribution/pull_v2.go
<ide> func (p *v2Puller) pullV2Repository(ctx context.Context, ref reference.Named) (e
<ide>
<ide> type v2LayerDescriptor struct {
<ide> digest digest.Digest
<add> diffID layer.DiffID
<ide> repoInfo *registry.RepositoryInfo
<ide> repo distribution.Repository
<ide> V2MetadataService metadata.V2MetadataService
<ide> func (ld *v2LayerDescriptor) ID() string {
<ide> }
<ide>
<ide> func (ld *v2LayerDescriptor) DiffID() (layer.DiffID, error) {
<add> if ld.diffID != "" {
<add> return ld.diffID, nil
<add> }
<ide> return ld.V2MetadataService.GetDiffID(ld.digest)
<ide> }
<ide>
<ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s
<ide> if configRootFS == nil {
<ide> return "", "", errRootFSInvalid
<ide> }
<add>
<add> if len(descriptors) != len(configRootFS.DiffIDs) {
<add> return "", "", errRootFSMismatch
<add> }
<add>
<add> // Populate diff ids in descriptors to avoid downloading foreign layers
<add> // which have been side loaded
<add> for i := range descriptors {
<add> descriptors[i].(*v2LayerDescriptor).diffID = configRootFS.DiffIDs[i]
<add> }
<ide> }
<ide>
<ide> if p.config.DownloadManager != nil {
| 1
|
PHP
|
PHP
|
remove finder delegation
|
c79eab2de3acd03140fc9ceb730c175c3d3c26fb
|
<ide><path>Cake/ORM/Table.php
<ide> public function callFinder($type, Query $query, $options = []) {
<ide> * Magic method to be able to call scoped finders & behaviors
<ide> * without the find prefix.
<ide> *
<del> * ## Finder delegation
<del> *
<del> * You can use this feature to invoke finder methods, without
<del> * adding the 'find' prefix or preparing a query ahead of time.
<del> * For example, if your Table provided a `findRecent` finder, you
<del> * could call `$table->recent()` instead.
<del> *
<ide> * ## Behavior delegation
<ide> *
<ide> * If your Table uses any behaviors you can call them as if
<ide> public function __call($method, $args) {
<ide> return $this->_behaviors->call($method, $args);
<ide> }
<ide>
<del> $query = null;
<del> if (isset($args[0]) && $args[0] instanceof Query) {
<del> $query = array_shift($args);
<del> }
<del> $options = array_shift($args) ?: [];
<del> if ($query === null) {
<del> return $this->find($method, $options);
<del> }
<del> return $this->callFinder($method, $query, $options);
<add> throw new \BadMethodCallException(
<add> __d('cake_dev', 'Unknown method "%s"', $method)
<add> );
<ide> }
<ide>
<ide> }
<ide><path>Cake/Test/TestCase/ORM/TableTest.php
<ide> public function testFindThreadedNoHydration() {
<ide> $this->assertEquals($expected, $results);
<ide> }
<ide>
<del>/**
<del> * Tests that finders can be called directly
<del> *
<del> * @return void
<del> */
<del> public function testCallingFindersDirectly() {
<del> $table = $this->getMock('\Cake\ORM\Table', ['find'], [], '', false);
<del> $query = $this->getMock('\Cake\ORM\Query', [], [$this->connection, $table]);
<del> $table->expects($this->once())
<del> ->method('find')
<del> ->with('list', [])
<del> ->will($this->returnValue($query));
<del> $this->assertSame($query, $table->list());
<del>
<del> $table = $this->getMock('\Cake\ORM\Table', ['find'], [], '', false);
<del> $table->expects($this->once())
<del> ->method('find')
<del> ->with('threaded', ['order' => ['name' => 'ASC']])
<del> ->will($this->returnValue($query));
<del> $this->assertSame($query, $table->threaded(['order' => ['name' => 'ASC']]));
<del> }
<del>
<ide> /**
<ide> * Tests that finders can be stacked
<ide> *
<ide> public function testStackingFinders() {
<ide> ->will($this->returnValue($query));
<ide>
<ide> $result = $table
<del> ->threaded(['order' => ['name' => 'ASC']])
<add> ->find('threaded', ['order' => ['name' => 'ASC']])
<ide> ->list(['keyPath' => 'id']);
<ide> $this->assertSame($query, $result);
<ide> }
<ide> public function testCallBehaviorFinder() {
<ide> $table = TableRegistry::get('article');
<ide> $table->addBehavior('Sluggable');
<ide>
<del> $query = $table->noSlug();
<del> $this->assertInstanceOf('Cake\ORM\Query', $query);
<del> $this->assertNotEmpty($query->clause('where'));
<del>
<ide> $query = $table->find('noSlug');
<ide> $this->assertInstanceOf('Cake\ORM\Query', $query);
<ide> $this->assertNotEmpty($query->clause('where'));
| 2
|
Javascript
|
Javascript
|
add link to reference for the sample patterns
|
3c8cb97f516f2c29bc78224f2bce58ab9e7934a5
|
<ide><path>examples/js/postprocessing/MSAAPass.js
<ide> THREE.MSAAPass.normalizedJitterOffsets = function( jitterVectors ) {
<ide> // These jitter vectors are specified in integers because it is easier.
<ide> // I am assuming a [-8,8] integer grid, but it needs to be mapped onto [-0.5,0.5]
<ide> // before being used, thus these integers need to be scaled by 1/16.
<add>//
<add>// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
<ide> THREE.MSAAPass.JitterVectors = [
<ide> THREE.MSAAPass.normalizedJitterOffsets( [
<ide> [ 0, 0 ]
| 1
|
Javascript
|
Javascript
|
name anonymous functions in _http_server
|
02c3c205f1a00b8dca0caca7f093969251f1fee5
|
<ide><path>lib/_http_server.js
<ide> function ServerResponse(req) {
<ide> }
<ide> util.inherits(ServerResponse, OutgoingMessage);
<ide>
<del>ServerResponse.prototype._finish = function() {
<add>ServerResponse.prototype._finish = function _finish() {
<ide> DTRACE_HTTP_SERVER_RESPONSE(this.connection);
<ide> LTTNG_HTTP_SERVER_RESPONSE(this.connection);
<ide> COUNTER_HTTP_SERVER_RESPONSE();
<ide> function onServerResponseClose() {
<ide> if (this._httpMessage) this._httpMessage.emit('close');
<ide> }
<ide>
<del>ServerResponse.prototype.assignSocket = function(socket) {
<add>ServerResponse.prototype.assignSocket = function assignSocket(socket) {
<ide> assert(!socket._httpMessage);
<ide> socket._httpMessage = this;
<ide> socket.on('close', onServerResponseClose);
<ide> ServerResponse.prototype.assignSocket = function(socket) {
<ide> this._flush();
<ide> };
<ide>
<del>ServerResponse.prototype.detachSocket = function(socket) {
<add>ServerResponse.prototype.detachSocket = function detachSocket(socket) {
<ide> assert(socket._httpMessage === this);
<ide> socket.removeListener('close', onServerResponseClose);
<ide> socket._httpMessage = null;
<ide> this.socket = this.connection = null;
<ide> };
<ide>
<del>ServerResponse.prototype.writeContinue = function(cb) {
<add>ServerResponse.prototype.writeContinue = function writeContinue(cb) {
<ide> this._writeRaw('HTTP/1.1 100 Continue' + CRLF + CRLF, 'ascii', cb);
<ide> this._sent100 = true;
<ide> };
<ide>
<del>ServerResponse.prototype._implicitHeader = function() {
<add>ServerResponse.prototype._implicitHeader = function _implicitHeader() {
<ide> this.writeHead(this.statusCode);
<ide> };
<ide>
<del>ServerResponse.prototype.writeHead = function(statusCode, reason, obj) {
<add>ServerResponse.prototype.writeHead = writeHead;
<add>function writeHead(statusCode, reason, obj) {
<ide> var headers;
<ide>
<ide> if (typeof reason === 'string') {
<ide> ServerResponse.prototype.writeHead = function(statusCode, reason, obj) {
<ide> }
<ide>
<ide> this._storeHeader(statusLine, headers);
<del>};
<add>}
<ide>
<del>ServerResponse.prototype.writeHeader = function() {
<add>ServerResponse.prototype.writeHeader = function writeHeader() {
<ide> this.writeHead.apply(this, arguments);
<ide> };
<ide>
<ide> function Server(requestListener) {
<ide> util.inherits(Server, net.Server);
<ide>
<ide>
<del>Server.prototype.setTimeout = function(msecs, callback) {
<add>Server.prototype.setTimeout = function setTimeout(msecs, callback) {
<ide> this.timeout = msecs;
<ide> if (callback)
<ide> this.on('timeout', callback);
| 1
|
Ruby
|
Ruby
|
fix hash spaces and use 1.9 style hash [ci skip]
|
087ce9d52dba2c8465ffa3db31399a5305057803
|
<ide><path>actionpack/lib/action_view/template.rb
<ide> def supports_streaming?
<ide> # we use a bang in this instrumentation because you don't want to
<ide> # consume this in production. This is only slow if it's being listened to.
<ide> def render(view, locals, buffer=nil, &block)
<del> ActiveSupport::Notifications.instrument("!render_template.action_view", :virtual_path => @virtual_path, :identifier=>@identifier) do
<add> ActiveSupport::Notifications.instrument("!render_template.action_view", virtual_path: @virtual_path, identifier: @identifier) do
<ide> compile!(view)
<ide> view.send(method_name, locals, buffer, &block)
<ide> end
| 1
|
Java
|
Java
|
fix aspect of some completable marbles
|
8b9740840f21d131595dac2115241b1f739b03f2
|
<ide><path>src/main/java/io/reactivex/Completable.java
<ide> public static <T> Completable fromObservable(final ObservableSource<T> observabl
<ide> * Returns a Completable instance that subscribes to the given publisher, ignores all values and
<ide> * emits only the terminal event.
<ide> * <p>
<del> * <img width="640" height="442" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromPublisher.png" alt="">
<add> * <img width="640" height="422" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.fromPublisher.png" alt="">
<ide> * <p>
<ide> * The {@link Publisher} must follow the
<ide> * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive-Streams specification</a>.
<ide> public final <T> Flowable<T> toFlowable() {
<ide>
<ide> /**
<ide> * Converts this Completable into a {@link Maybe}.
<del> * <p>
<del> * <img width="640" height="293" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.toObservable.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code toMaybe} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final <T> Maybe<T> toMaybe() {
<ide> /**
<ide> * Returns an Observable which when subscribed to subscribes to this Completable and
<ide> * relays the terminal events to the subscriber.
<add> * <p>
<add> * <img width="640" height="293" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.toObservable.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code toObservable} does not operate by default on a particular {@link Scheduler}.</dd>
| 1
|
PHP
|
PHP
|
adapt changes in to use undeprecated methods
|
2e67e5768a4d07daecc854dc10d3a7f9b3fbc6a6
|
<ide><path>src/Http/Client.php
<ide> public function send(Request $request, $options = [])
<ide> $handleRedirect = $response->isRedirect() && $redirects-- > 0;
<ide> if ($handleRedirect) {
<ide> $url = $request->getUri();
<del> $request->cookie($this->_cookies->get($url));
<add> $request = $this->_cookies->addToRequest($request, []);
<ide>
<ide> $location = $response->getHeaderLine('Location');
<ide> $locationUrl = $this->buildUrl($location, [], [
| 1
|
PHP
|
PHP
|
remove silently usage of old response + phpcs
|
35e5537a535944cd77dbddda70f58130c96fa523
|
<ide><path>src/Network/CorsBuilder.php
<ide> */
<ide> namespace Cake\Network;
<ide>
<add>use Cake\Http\Response;
<add>
<ide> /**
<ide> * A builder object that assists in defining Cross Origin Request related
<ide> * headers.
<ide><path>tests/test_app/TestApp/Error/TestAppsExceptionRenderer.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Error\ExceptionRenderer;
<del>use Cake\Network\Request;
<ide> use Cake\Http\Response;
<add>use Cake\Network\Request;
<ide> use Cake\Routing\Router;
<ide> use TestApp\Controller\TestAppsErrorController;
<ide>
| 2
|
Python
|
Python
|
fix typos to enable sync training
|
0319908c2c4bb7e71341daeaa302c4862ebc9f46
|
<ide><path>research/object_detection/trainer.py
<ide> def train(create_tensor_dict_fn, create_model_fn, train_config, master, task,
<ide>
<ide> sync_optimizer = None
<ide> if train_config.sync_replicas:
<del> training_optimizer = tf.SyncReplicasOptimizer(
<add> training_optimizer = tf.train.SyncReplicasOptimizer(
<ide> training_optimizer,
<ide> replicas_to_aggregate=train_config.replicas_to_aggregate,
<del> total_num_replicas=train_config.worker_replicas)
<add> total_num_replicas=worker_replicas)
<ide> sync_optimizer = training_optimizer
<ide>
<ide> # Create ops required to initialize the model from a given checkpoint.
| 1
|
Python
|
Python
|
fix error getting floating ip instance_id
|
204313794e2e79e8d8835b108f93fabcd9f88f6b
|
<ide><path>libcloud/compute/drivers/openstack.py
<ide> def _to_floating_ip(self, obj):
<ide> port.extra["mac_address"]}
<ide>
<ide> if 'port_details' in obj and obj['port_details']:
<del> if obj['port_details']['device_owner'] == 'compute:nova':
<add> if obj['port_details']['device_owner'] in ['compute:nova',
<add> 'compute:None']:
<ide> instance_id = obj['port_details']['device_id']
<ide>
<ide> ip_address = obj['floating_ip_address']
| 1
|
Javascript
|
Javascript
|
prevent infinite test execution
|
82ec250c75d4a4ea540c3861b18c85b25ee7cf6c
|
<ide><path>curriculum/test/test-challenges.js
<ide> const jQueryScript = fs.readFileSync(
<ide> ));
<ide>
<ide> describe('Check challenges tests', async function() {
<del> this.timeout(200000);
<add> this.timeout(5000);
<ide>
<ide> allChallenges.forEach(challenge => {
<ide> describe(challenge.title || 'No title', async function() {
<ide> function isPromise(value) {
<ide> );
<ide> }
<ide>
<add>function timeout(milliseconds) {
<add> return new Promise(resolve => setTimeout(resolve, milliseconds));
<add>}
<add>
<ide> function transformSass(solution) {
<ide> const fragment = JSDOM.fragment(`<div>${solution}</div>`);
<ide> const styleTags = fragment.querySelectorAll('style[type="text/sass"]');
<ide> A required file can not have both a src and a link: src = ${src}, link = ${link}
<ide> </head>
<ide> `;
<ide>
<del> solution = transformSass(solution);
<add> const sandbox = { solution, transformSass };
<add> const context = vm.createContext(sandbox);
<add> vm.runInContext(
<add> 'solution = transformSass(solution);',
<add> context,
<add> {
<add> timeout: 2000
<add> }
<add> );
<add> solution = sandbox.solution;
<ide> solution = replaceColorNames(solution);
<ide>
<ide> const dom = new JSDOM(`
<ide> A required file can not have both a src and a link: src = ${src}, link = ${link}
<ide> `, options);
<ide>
<ide> if (links || challengeType === challengeTypes.modern) {
<del> await new Promise(resolve => setTimeout(resolve, 1000));
<add> await timeout(1000);
<ide> }
<ide>
<ide> dom.window.code = code;
<ide> async function runTestInJsdom(dom, testString, scriptString = '') {
<ide> }
<ide> })();`;
<ide> const script = new vm.Script(scriptString);
<del> dom.runVMScript(script);
<add> dom.runVMScript(script, { timeout: 5000 });
<ide> await dom.window.__result;
<ide> if (dom.window.__error) {
<ide> throw dom.window.__error;
| 1
|
Python
|
Python
|
use the whole sys.version string
|
6b28ceba83c3b76eea2e5a89327318af67404298
|
<ide><path>flask/cli.py
<ide> def get_version(ctx, param, value):
<ide> message = 'Flask %(version)s\nPython %(python_version)s'
<ide> click.echo(message % {
<ide> 'version': __version__,
<del> 'python_version': sys.version[:3],
<add> 'python_version': sys.version,
<ide> }, color=ctx.color)
<ide> ctx.exit()
<ide>
| 1
|
PHP
|
PHP
|
fix some formatting
|
2808b6c83d454e082d50efc91cd2711d3f6d8dd0
|
<ide><path>src/Illuminate/Filesystem/FilesystemManager.php
<ide> public function createLocalDriver(array $config)
<ide> */
<ide> public function createS3Driver(array $config)
<ide> {
<del> $s3Config = ['key' => $config['key'], 'secret' => $config['secret']];
<del>
<del> if (isset($config['region']))
<del> {
<del> $s3Config['region'] = $config['region'];
<del> }
<add> $s3Config = array_only($config, ['key', 'region', 'secret', 'signature']);
<ide>
<ide> return $this->adapt(
<ide> new Flysystem(new S3Adapter(S3Client::factory($s3Config), $config['bucket']))
| 1
|
Javascript
|
Javascript
|
add note about flicker when toggling elements
|
98e0e047b0f705005b256c70feb4e6368ff3a591
|
<ide><path>src/ng/directive/ngShowHide.js
<ide> var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
<ide> });
<ide> </file>
<ide> </example>
<add> *
<add> * @knownIssue
<add> *
<add> * ### Flickering when using ngShow to toggle between elements
<add> *
<add> * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can
<add> * happen that both the element to show and the element to hide are visible for a very short time.
<add> *
<add> * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations
<add> * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than
<add> * other browsers.
<add> *
<add> * There are several way to mitigate this problem:
<add> *
<add> * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}.
<add> * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}.
<add> * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements.
<add> * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}.
<add> * - Define an animation on the affected elements.
<ide> */
<ide> var ngShowDirective = ['$animate', function($animate) {
<ide> return {
<ide> var ngShowDirective = ['$animate', function($animate) {
<ide> });
<ide> </file>
<ide> </example>
<add> *
<add> * @knownIssue
<add> *
<add> * ### Flickering when using ngHide to toggle between elements
<add> *
<add> * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can
<add> * happen that both the element to show and the element to hide are visible for a very short time.
<add> *
<add> * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations
<add> * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than
<add> * other browsers.
<add> *
<add> * There are several way to mitigate this problem:
<add> *
<add> * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}.
<add> * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}.
<add> * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements.
<add> * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}.
<add> * - Define an animation on the affected elements.
<ide> */
<ide> var ngHideDirective = ['$animate', function($animate) {
<ide> return {
| 1
|
Python
|
Python
|
define the upload_to for file fields
|
c6d89afdf7473c6b9f2af41a4bbc9bdaa83d39d1
|
<ide><path>rest_framework/tests/models.py
<ide> class AMOAFModel(RESTFrameworkModel):
<ide> comma_separated_integer_field = models.CommaSeparatedIntegerField(max_length=1024, blank=True)
<ide> decimal_field = models.DecimalField(max_digits=64, decimal_places=32, blank=True)
<ide> email_field = models.EmailField(max_length=1024, blank=True)
<del> file_field = models.FileField(max_length=1024, blank=True)
<del> image_field = models.ImageField(max_length=1024, blank=True)
<add> file_field = models.FileField(upload_to='test', max_length=1024, blank=True)
<add> image_field = models.ImageField(upload_to='test', max_length=1024, blank=True)
<ide> slug_field = models.SlugField(max_length=1024, blank=True)
<ide> url_field = models.URLField(max_length=1024, blank=True)
<ide>
<ide> class DVOAFModel(RESTFrameworkModel):
<ide> positive_integer_field = models.PositiveIntegerField(blank=True)
<ide> positive_small_integer_field = models.PositiveSmallIntegerField(blank=True)
<ide> email_field = models.EmailField(blank=True)
<del> file_field = models.FileField(blank=True)
<del> image_field = models.ImageField(blank=True)
<add> file_field = models.FileField(upload_to='test', blank=True)
<add> image_field = models.ImageField(upload_to='test', blank=True)
<ide> slug_field = models.SlugField(blank=True)
<ide> url_field = models.URLField(blank=True)
<ide>
| 1
|
Python
|
Python
|
translate non-ascii characters
|
a4af964c1ad2c419ef51cd9d717f5aac7ed60b39
|
<ide><path>airflow/kubernetes/kubernetes_helper_functions.py
<ide> from typing import Dict, Optional
<ide>
<ide> from dateutil import parser
<add>from slugify import slugify
<ide>
<ide> from airflow.models.taskinstance import TaskInstanceKey
<ide>
<ide> def _strip_unsafe_kubernetes_special_chars(string: str) -> str:
<ide> :param string: The requested Pod name
<ide> :return: Pod name stripped of any unsafe characters
<ide> """
<del> return ''.join(ch.lower() for ch in list(string) if ch.isalnum())
<add> return slugify(string, separator='', lowercase=True)
<ide>
<ide>
<ide> def create_pod_id(dag_id: str, task_id: str) -> str:
<ide><path>tests/executors/test_kubernetes_executor.py
<ide> def _cases(self):
<ide> ("MYDAGID", "MYTASKID"),
<ide> ("my_dag_id", "my_task_id"),
<ide> ("mydagid" * 200, "my_task_id" * 200),
<add> ("my_dág_id", "my_tásk_id"),
<add> ("Компьютер", "niedołężność"),
<add> ("影師嗎", "中華民國;$"),
<ide> ]
<ide>
<ide> cases.extend(
| 2
|
Text
|
Text
|
hide solution from tests
|
bdbbeb0cbab973f5c6d929181b3f24ccfa954ca7
|
<ide><path>curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-area-without-creating-an-areas-template.spanish.md
<ide> localeTitle: Usar área de cuadrícula sin crear una plantilla de áreas
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>item5</code> clase <code>item5</code> debe tener una propiedad de <code>grid-area</code> que tenga el valor de <code>3/1/4/4</code> .
<del> testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-area\s*?:\s*?3\s*?\/\s*?1\s*?\/\s*?4\s*?\/\s*?4\s*?;[\s\S]*}/gi), "<code>item5</code> class should have a <code>grid-area</code> property that has the value of <code>3/1/4/4</code>.");'
<add> - text: La clase <code>item5</code> debe tener una propiedad de <code>grid-area</code> de modo que esté entre las líneas horizontales tercera y cuarta y entre las líneas verticales primera y cuarta.
<add> testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-area\s*?:\s*?3\s*?\/\s*?1\s*?\/\s*?4\s*?\/\s*?4\s*?;[\s\S]*}/gi), "La clase <code>item5</code> debe tener una propiedad de <code>grid-area</code> de modo que esté entre las líneas horizontales tercera y cuarta y entre las líneas verticales primera y cuarta.");'
<ide>
<ide> ```
<ide>
| 1
|
Go
|
Go
|
use logrus everywhere for logging
|
7c62cee51edc91634046b4faa6c6f1841cd53ec1
|
<ide><path>api/client/commands.go
<ide> import (
<ide> "text/template"
<ide> "time"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/graph"
<ide> "github.com/docker/docker/nat"
<ide> "github.com/docker/docker/opts"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide><path>api/client/hijack.go
<ide> import (
<ide> "runtime"
<ide> "strings"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/dockerversion"
<del> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/promise"
<ide> "github.com/docker/docker/pkg/stdcopy"
<ide> "github.com/docker/docker/pkg/term"
<ide><path>api/client/utils.go
<ide> import (
<ide> "strings"
<ide> "syscall"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/stdcopy"
<ide> "github.com/docker/docker/pkg/term"
<ide> "github.com/docker/docker/registry"
<ide><path>api/common.go
<ide> import (
<ide> "mime"
<ide> "strings"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/version"
<ide> )
<ide><path>api/server/server.go
<ide> import (
<ide> "github.com/docker/libcontainer/user"
<ide> "github.com/gorilla/mux"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/listenbuffer"
<del> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/stdcopy"
<ide> "github.com/docker/docker/pkg/systemd"
<ide><path>builder/dispatchers.go
<ide> import (
<ide> "regexp"
<ide> "strings"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/nat"
<del> "github.com/docker/docker/pkg/log"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide><path>builder/evaluator.go
<ide> import (
<ide> "path"
<ide> "strings"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/builder/parser"
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/tarsum"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/runconfig"
<ide><path>builder/internals.go
<ide> import (
<ide> "syscall"
<ide> "time"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/builder/parser"
<ide> "github.com/docker/docker/daemon"
<ide> imagepkg "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/symlink"
<ide> "github.com/docker/docker/pkg/system"
<ide><path>daemon/attach.go
<ide> import (
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/jsonlog"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/promise"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide><path>daemon/container.go
<ide> import (
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/broadcastwriter"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/networkfs/etchosts"
<ide> "github.com/docker/docker/pkg/networkfs/resolvconf"
<ide> "github.com/docker/docker/pkg/promise"
<ide><path>daemon/daemon.go
<ide> import (
<ide>
<ide> "github.com/docker/libcontainer/label"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/daemon/execdriver"
<ide> "github.com/docker/docker/daemon/execdriver/execdrivers"
<ide> "github.com/docker/docker/daemon/execdriver/lxc"
<ide> import (
<ide> "github.com/docker/docker/pkg/broadcastwriter"
<ide> "github.com/docker/docker/pkg/graphdb"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/namesgenerator"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> func (daemon *Daemon) restore() error {
<ide> )
<ide>
<ide> if !debug {
<del> log.Infof("Loading containers: ")
<add> log.Infof("Loading containers: start.")
<ide> }
<ide> dir, err := ioutil.ReadDir(daemon.repository)
<ide> if err != nil {
<ide> func (daemon *Daemon) restore() error {
<ide> }
<ide>
<ide> if !debug {
<del> log.Infof(": done.")
<add> fmt.Println()
<add> log.Infof("Loading containers: done.")
<ide> }
<ide>
<ide> return nil
<ide><path>daemon/daemon_aufs.go
<ide> import (
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/daemon/graphdriver/aufs"
<ide> "github.com/docker/docker/graph"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> // Given the graphdriver ad, if it is aufs, then migrate it.
<ide><path>daemon/delete.go
<ide> import (
<ide> "path"
<ide>
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> func (daemon *Daemon) ContainerRm(job *engine.Job) engine.Status {
<ide><path>daemon/exec.go
<ide> import (
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/broadcastwriter"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/promise"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide><path>daemon/execdriver/lxc/driver.go
<ide> import (
<ide> "github.com/kr/pty"
<ide>
<ide> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/term"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/libcontainer/cgroups"
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> mountpk "github.com/docker/docker/pkg/mount"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/libcontainer/label"
<ide><path>daemon/graphdriver/aufs/mount.go
<ide> import (
<ide> "os/exec"
<ide> "syscall"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> func Unmount(target string) error {
<ide><path>daemon/graphdriver/devmapper/attach_loopback.go
<ide> import (
<ide> "os"
<ide> "syscall"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> func stringToLoopName(src string) [LoNameSize]uint8 {
<ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/units"
<ide> "github.com/docker/libcontainer/label"
<ide><path>daemon/graphdriver/devmapper/devmapper.go
<ide> import (
<ide> "runtime"
<ide> "syscall"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> type DevmapperLogger interface {
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> import (
<ide> "path"
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/mount"
<ide> "github.com/docker/docker/pkg/units"
<ide> )
<ide><path>daemon/graphdriver/fsdiff.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide><path>daemon/info.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> "github.com/docker/docker/pkg/parsers/operatingsystem"
<ide> "github.com/docker/docker/registry"
<ide><path>daemon/logs.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/jsonlog"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/tailfile"
<ide> "github.com/docker/docker/pkg/timeutils"
<ide> )
<ide><path>daemon/monitor.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide>
<ide><path>daemon/networkdriver/bridge/driver.go
<ide> import (
<ide> "github.com/docker/docker/daemon/networkdriver/portmapper"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/iptables"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/networkfs/resolvconf"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> "github.com/docker/libcontainer/netlink"
<ide><path>daemon/networkdriver/portmapper/mapper.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/daemon/networkdriver/portallocator"
<ide> "github.com/docker/docker/pkg/iptables"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> type mapping struct {
<ide><path>daemon/volumes.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/daemon/execdriver"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/symlink"
<ide> "github.com/docker/docker/volumes"
<ide> )
<ide><path>docker/daemon.go
<ide> package main
<ide>
<ide> import (
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/builtins"
<ide> "github.com/docker/docker/daemon"
<ide> _ "github.com/docker/docker/daemon/execdriver/lxc"
<ide> _ "github.com/docker/docker/daemon/execdriver/native"
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/log"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/signal"
<ide> )
<ide><path>docker/docker.go
<ide> func main() {
<ide> if reexec.Init() {
<ide> return
<ide> }
<add>
<ide> flag.Parse()
<ide> // FIXME: validate daemon flags here
<ide>
<ide> func main() {
<ide> os.Setenv("DEBUG", "1")
<ide> }
<ide>
<add> initLogging(*flDebug)
<add>
<ide> if len(flHosts) == 0 {
<ide> defaultHost := os.Getenv("DOCKER_HOST")
<ide> if defaultHost == "" || *flDaemon {
<ide><path>docker/log.go
<add>package main
<add>
<add>import (
<add> "os"
<add>
<add> log "github.com/Sirupsen/logrus"
<add>)
<add>
<add>func initLogging(debug bool) {
<add> log.SetOutput(os.Stderr)
<add> if debug {
<add> log.SetLevel(log.DebugLevel)
<add> } else {
<add> log.SetLevel(log.InfoLevel)
<add> }
<add>}
<ide><path>graph/export.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> )
<ide>
<ide><path>graph/graph.go
<ide> import (
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/truncindex"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide><path>graph/load.go
<ide> import (
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> // Loads a set of images into the repository. This is the complementary of ImageExport.
<ide><path>graph/pull.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/image"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/libtrust"
<ide><path>graph/push.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide><path>graph/service.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/image"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> func (s *TagStore) Install(eng *engine.Engine) error {
<ide><path>image/image.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide><path>integration/commands_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/client"
<ide> "github.com/docker/docker/daemon"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/term"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/libtrust"
<ide><path>integration/runtime_test.go
<ide> import (
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/nat"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/reexec"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide><path>integration/utils_test.go
<ide> import (
<ide> "github.com/docker/docker/builtins"
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/log"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/sysinfo"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
<add>type Fataler interface {
<add> Fatal(...interface{})
<add>}
<add>
<ide> // This file contains utility functions for docker's unit test suite.
<ide> // It has to be named XXX_test.go, apparently, in other to access private functions
<ide> // from other XXX_test.go functions.
<ide>
<ide> // Create a temporary daemon suitable for unit testing.
<ide> // Call t.Fatal() at the first error.
<del>func mkDaemon(f log.Fataler) *daemon.Daemon {
<add>func mkDaemon(f Fataler) *daemon.Daemon {
<ide> eng := newTestEngine(f, false, "")
<ide> return mkDaemonFromEngine(eng, f)
<ide> // FIXME:
<ide> func mkDaemon(f log.Fataler) *daemon.Daemon {
<ide> // [...]
<ide> }
<ide>
<del>func createNamedTestContainer(eng *engine.Engine, config *runconfig.Config, f log.Fataler, name string) (shortId string) {
<add>func createNamedTestContainer(eng *engine.Engine, config *runconfig.Config, f Fataler, name string) (shortId string) {
<ide> job := eng.Job("create", name)
<ide> if err := job.ImportEnv(config); err != nil {
<ide> f.Fatal(err)
<ide> func createNamedTestContainer(eng *engine.Engine, config *runconfig.Config, f lo
<ide> return engine.Tail(outputBuffer, 1)
<ide> }
<ide>
<del>func createTestContainer(eng *engine.Engine, config *runconfig.Config, f log.Fataler) (shortId string) {
<add>func createTestContainer(eng *engine.Engine, config *runconfig.Config, f Fataler) (shortId string) {
<ide> return createNamedTestContainer(eng, config, f, "")
<ide> }
<ide>
<del>func startContainer(eng *engine.Engine, id string, t log.Fataler) {
<add>func startContainer(eng *engine.Engine, id string, t Fataler) {
<ide> job := eng.Job("start", id)
<ide> if err := job.Run(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }
<ide>
<del>func containerRun(eng *engine.Engine, id string, t log.Fataler) {
<add>func containerRun(eng *engine.Engine, id string, t Fataler) {
<ide> startContainer(eng, id, t)
<ide> containerWait(eng, id, t)
<ide> }
<ide>
<del>func containerFileExists(eng *engine.Engine, id, dir string, t log.Fataler) bool {
<add>func containerFileExists(eng *engine.Engine, id, dir string, t Fataler) bool {
<ide> c := getContainer(eng, id, t)
<ide> if err := c.Mount(); err != nil {
<ide> t.Fatal(err)
<ide> func containerFileExists(eng *engine.Engine, id, dir string, t log.Fataler) bool
<ide> return true
<ide> }
<ide>
<del>func containerAttach(eng *engine.Engine, id string, t log.Fataler) (io.WriteCloser, io.ReadCloser) {
<add>func containerAttach(eng *engine.Engine, id string, t Fataler) (io.WriteCloser, io.ReadCloser) {
<ide> c := getContainer(eng, id, t)
<ide> i, err := c.StdinPipe()
<ide> if err != nil {
<ide> func containerAttach(eng *engine.Engine, id string, t log.Fataler) (io.WriteClos
<ide> return i, o
<ide> }
<ide>
<del>func containerWait(eng *engine.Engine, id string, t log.Fataler) int {
<add>func containerWait(eng *engine.Engine, id string, t Fataler) int {
<ide> ex, _ := getContainer(eng, id, t).WaitStop(-1 * time.Second)
<ide> return ex
<ide> }
<ide>
<del>func containerWaitTimeout(eng *engine.Engine, id string, t log.Fataler) error {
<add>func containerWaitTimeout(eng *engine.Engine, id string, t Fataler) error {
<ide> _, err := getContainer(eng, id, t).WaitStop(500 * time.Millisecond)
<ide> return err
<ide> }
<ide>
<del>func containerKill(eng *engine.Engine, id string, t log.Fataler) {
<add>func containerKill(eng *engine.Engine, id string, t Fataler) {
<ide> if err := eng.Job("kill", id).Run(); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }
<ide>
<del>func containerRunning(eng *engine.Engine, id string, t log.Fataler) bool {
<add>func containerRunning(eng *engine.Engine, id string, t Fataler) bool {
<ide> return getContainer(eng, id, t).IsRunning()
<ide> }
<ide>
<del>func containerAssertExists(eng *engine.Engine, id string, t log.Fataler) {
<add>func containerAssertExists(eng *engine.Engine, id string, t Fataler) {
<ide> getContainer(eng, id, t)
<ide> }
<ide>
<del>func containerAssertNotExists(eng *engine.Engine, id string, t log.Fataler) {
<add>func containerAssertNotExists(eng *engine.Engine, id string, t Fataler) {
<ide> daemon := mkDaemonFromEngine(eng, t)
<ide> if c := daemon.Get(id); c != nil {
<ide> t.Fatal(fmt.Errorf("Container %s should not exist", id))
<ide> func containerAssertNotExists(eng *engine.Engine, id string, t log.Fataler) {
<ide>
<ide> // assertHttpNotError expect the given response to not have an error.
<ide> // Otherwise the it causes the test to fail.
<del>func assertHttpNotError(r *httptest.ResponseRecorder, t log.Fataler) {
<add>func assertHttpNotError(r *httptest.ResponseRecorder, t Fataler) {
<ide> // Non-error http status are [200, 400)
<ide> if r.Code < http.StatusOK || r.Code >= http.StatusBadRequest {
<ide> t.Fatal(fmt.Errorf("Unexpected http error: %v", r.Code))
<ide> func assertHttpNotError(r *httptest.ResponseRecorder, t log.Fataler) {
<ide>
<ide> // assertHttpError expect the given response to have an error.
<ide> // Otherwise the it causes the test to fail.
<del>func assertHttpError(r *httptest.ResponseRecorder, t log.Fataler) {
<add>func assertHttpError(r *httptest.ResponseRecorder, t Fataler) {
<ide> // Non-error http status are [200, 400)
<ide> if !(r.Code < http.StatusOK || r.Code >= http.StatusBadRequest) {
<ide> t.Fatal(fmt.Errorf("Unexpected http success code: %v", r.Code))
<ide> }
<ide> }
<ide>
<del>func getContainer(eng *engine.Engine, id string, t log.Fataler) *daemon.Container {
<add>func getContainer(eng *engine.Engine, id string, t Fataler) *daemon.Container {
<ide> daemon := mkDaemonFromEngine(eng, t)
<ide> c := daemon.Get(id)
<ide> if c == nil {
<ide> func getContainer(eng *engine.Engine, id string, t log.Fataler) *daemon.Containe
<ide> return c
<ide> }
<ide>
<del>func mkDaemonFromEngine(eng *engine.Engine, t log.Fataler) *daemon.Daemon {
<add>func mkDaemonFromEngine(eng *engine.Engine, t Fataler) *daemon.Daemon {
<ide> iDaemon := eng.Hack_GetGlobalVar("httpapi.daemon")
<ide> if iDaemon == nil {
<ide> panic("Legacy daemon field not set in engine")
<ide> func mkDaemonFromEngine(eng *engine.Engine, t log.Fataler) *daemon.Daemon {
<ide> return daemon
<ide> }
<ide>
<del>func newTestEngine(t log.Fataler, autorestart bool, root string) *engine.Engine {
<add>func newTestEngine(t Fataler, autorestart bool, root string) *engine.Engine {
<ide> if root == "" {
<ide> if dir, err := newTestDirectory(unitTestStoreBase); err != nil {
<ide> t.Fatal(err)
<ide> func newTestEngine(t log.Fataler, autorestart bool, root string) *engine.Engine
<ide> return eng
<ide> }
<ide>
<del>func NewTestEngine(t log.Fataler) *engine.Engine {
<add>func NewTestEngine(t Fataler) *engine.Engine {
<ide> return newTestEngine(t, false, "")
<ide> }
<ide>
<ide><path>pkg/archive/archive.go
<ide> import (
<ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide>
<ide> "github.com/docker/docker/pkg/fileutils"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/docker/docker/pkg/promise"
<ide> "github.com/docker/docker/pkg/system"
<ide><path>pkg/archive/changes.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/docker/docker/pkg/system"
<ide> )
<ide><path>pkg/broadcastwriter/broadcastwriter.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/jsonlog"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> // BroadcastWriter accumulate multiple io.WriteCloser by stream.
<ide><path>pkg/fileutils/fileutils.go
<ide> package fileutils
<ide>
<ide> import (
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "path/filepath"
<ide> )
<ide>
<ide><path>pkg/httputils/resumablerequestreader.go
<ide> import (
<ide> "net/http"
<ide> "time"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> type resumableRequestReader struct {
<ide><path>pkg/iptables/iptables.go
<ide> import (
<ide> "strconv"
<ide> "strings"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> type Action string
<ide><path>pkg/log/log.go
<ide> import (
<ide> "strings"
<ide> "time"
<ide>
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/timeutils"
<ide> )
<ide>
<add>func init() {
<add> log.SetOutput(os.Stderr)
<add> log.SetLevel(log.InfoLevel)
<add> if os.Getenv("DEBUG") != "" {
<add> log.SetLevel(log.DebugLevel)
<add> }
<add>}
<add>
<ide> type priority int
<ide>
<ide> const (
<ide><path>pkg/signal/trap.go
<ide> import (
<ide> "sync/atomic"
<ide> "syscall"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> // Trap sets up a simplified signal "trap", appropriate for common
<ide><path>pkg/stdcopy/stdcopy.go
<ide> import (
<ide> "errors"
<ide> "io"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> const (
<ide><path>pkg/tarsum/tarsum.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> const (
<ide><path>registry/endpoint.go
<ide> import (
<ide> "net/url"
<ide> "strings"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> // scans string for api version in the URL path. returns the trimmed hostname, if version found, string and API version.
<ide><path>registry/registry_mock_test.go
<ide> import (
<ide>
<ide> "github.com/gorilla/mux"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> var (
<ide><path>registry/session.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/httputils"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/tarsum"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide><path>registry/session_v2.go
<ide> import (
<ide> "net/url"
<ide> "strconv"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/gorilla/mux"
<ide> )
<ide><path>runconfig/merge.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/nat"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> func Merge(userConf, imageConf *Config) error {
<ide><path>trust/service.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/libtrust"
<ide> )
<ide>
<ide><path>trust/trusts.go
<ide> import (
<ide> "sync"
<ide> "time"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/libtrust/trustgraph"
<ide> )
<ide>
<ide><path>utils/http.go
<ide> import (
<ide> "net/http"
<ide> "strings"
<ide>
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> // VersionInfo is used to model entities which has a version.
<ide><path>utils/utils.go
<ide> import (
<ide> "github.com/docker/docker/dockerversion"
<ide> "github.com/docker/docker/pkg/fileutils"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> )
<ide>
<ide> type KeyValuePair struct {
<ide><path>volumes/repository.go
<ide> import (
<ide> "sync"
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<del> "github.com/docker/docker/pkg/log"
<add> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
| 61
|
Python
|
Python
|
add dep to supertag
|
7a33f1e2b7a3b457bc3484767a12c184c73942a2
|
<ide><path>bin/parser/train_ud.py
<ide> def read_conllx(loc, n=0):
<ide> id_ = int(id_) - 1
<ide> head = (int(head) - 1) if head != '0' else id_
<ide> dep = 'ROOT' if dep == 'root' else dep #'unlabelled'
<del> tokens.append((id_, word, pos+'__'+morph, head, dep, 'O'))
<add> tag = pos+'__'+dep+'__'+morph
<add> Spanish.Defaults.tag_map[tag] = {POS: pos}
<add> tokens.append((id_, word, tag, head, dep, 'O'))
<ide> except:
<ide> raise
<ide> tuples = [list(t) for t in zip(*tokens)]
<ide> def read_conllx(loc, n=0):
<ide> break
<ide>
<ide>
<del>def score_model(vocab, encoder, tagger, parser, Xs, ys, verbose=False):
<add>def score_model(vocab, encoder, parser, Xs, ys, verbose=False):
<ide> scorer = Scorer()
<ide> correct = 0.
<ide> total = 0.
<ide> for doc, gold in zip(Xs, ys):
<ide> doc = Doc(vocab, words=[w.text for w in doc])
<ide> encoder(doc)
<del> tagger(doc)
<ide> parser(doc)
<ide> PseudoProjectivity.deprojectivize(doc)
<ide> scorer.score(doc, gold, verbose=verbose)
<ide> for token, tag in zip(doc, gold.tags):
<del> univ_guess, _ = token.tag_.split('_', 1)
<add> if '_' in token.tag_:
<add> univ_guess, _ = token.tag_.split('_', 1)
<add> else:
<add> univ_guess = ''
<ide> univ_truth, _ = tag.split('_', 1)
<ide> correct += univ_guess == univ_truth
<ide> total += 1
| 1
|
Python
|
Python
|
remove i18n from log messages
|
5da624c2020b7fad0b25a836433cb1c9116c6c20
|
<ide><path>glances/__init__.py
<ide> def main():
<ide>
<ide> # Test if client and server are in the same major version
<ide> if not client.login():
<del> logger.critical(
<del> _("The server version is not compatible with the client"))
<add> logger.critical("The server version is not compatible with the client")
<ide> sys.exit(2)
<ide>
<ide> # Start the client loop
<ide> def main():
<ide> server = GlancesServer(cached_time=core.cached_time,
<ide> config=core.get_config(),
<ide> args=args)
<del> print(_("Glances server is running on {0}:{1}").format(
<del> args.bind_address, args.port))
<add> print(_("Glances server is running on {0}:{1}").format(args.bind_address, args.port))
<ide>
<ide> # Set the server login/password (if -P/--password tag)
<ide> if args.password != "":
<ide><path>glances/core/glances_client.py
<ide> def __init__(self, config=None, args=None, timeout=7, return_to_browser=False):
<ide> try:
<ide> self.client = ServerProxy(uri, transport=transport)
<ide> except Exception as e:
<del> msg = _("Client couldn't create socket {0}: {1}").format(uri, e)
<add> msg = "Client couldn't create socket {0}: {1}".format(uri, e)
<ide> if not return_to_browser:
<ide> logger.critical(msg)
<ide> sys.exit(2)
<ide> def login(self, return_to_browser=False):
<ide> except ProtocolError as err:
<ide> # Others errors
<ide> if str(err).find(" 401 ") > 0:
<del> msg = _("Connection to server failed (Bad password)")
<add> msg = "Connection to server failed (bad password)"
<ide> else:
<del> msg = _("Connection to server failed ({0})").format(err)
<add> msg = "Connection to server failed ({0})".format(err)
<ide> if not return_to_browser:
<ide> logger.critical(msg)
<ide> sys.exit(2)
<ide> def update(self):
<ide> return self.update_snmp()
<ide> else:
<ide> self.end()
<del> logger.critical(_("Unknown server mode: {0}").format(self.get_mode()))
<add> logger.critical("Unknown server mode: {0}".format(self.get_mode()))
<ide> sys.exit(2)
<ide>
<ide> def update_glances(self):
<ide><path>glances/core/glances_config.py
<ide> def load(self):
<ide> self.parser.read(config_file, encoding='utf-8')
<ide> else:
<ide> self.parser.read(config_file)
<del> logger.info(_("Read configuration file %s") % config_file)
<add> logger.info("Read configuration file '{0}'".format(config_file))
<ide> except UnicodeDecodeError as e:
<del> logger.error(
<del> _("Cannot decode configuration file '{0}': {1}").format(config_file, e))
<add> logger.error("Cannot decode configuration file '{0}': {1}".format(config_file, e))
<ide> sys.exit(1)
<ide> # Save the loaded configuration file path (issue #374)
<ide> self._loaded_config_file = config_file
<ide><path>glances/core/glances_main.py
<ide> def parse_args(self):
<ide>
<ide> # Filter is only available in standalone mode
<ide> if args.process_filter is not None and not self.is_standalone():
<del> logger.critical(
<del> _("Process filter is only available in standalone mode"))
<add> logger.critical("Process filter is only available in standalone mode")
<ide> sys.exit(2)
<ide>
<ide> # Check graph output path
<ide> if args.enable_history and args.path_history is not None:
<ide> if not os.access(args.path_history, os.W_OK):
<del> logger.critical(
<del> _("History output path (%s) do not exist or is not writable") % args.path_history)
<add> logger.critical("History output path {0} do not exist or is not writable".format(args.path_history))
<ide> sys.exit(2)
<del> logger.debug(_("History output path is set to %s") %
<del> args.path_history)
<add> logger.debug("History output path is set to {0}".format(args.path_history))
<ide>
<ide> return args
<ide>
<ide><path>glances/core/glances_monitor_list.py
<ide> def __set_monitor_list(self, section, key):
<ide> countmin = self.config.get_raw_option(section, key + "countmin")
<ide> countmax = self.config.get_raw_option(section, key + "countmax")
<ide> except Exception as e:
<del> logger.error(_("Cannot read monitored list: {0}").format(e))
<add> logger.error("Cannot read monitored list: {0}".format(e))
<ide> pass
<ide> else:
<ide> if description is not None and regex is not None:
<ide><path>glances/core/glances_password.py
<ide> def get_password(self, description='', confirm=False, clear=False):
<ide> """
<ide> if os.path.exists(self.password_filepath) and not clear:
<ide> # If the password file exist then use it
<del> logger.info(_("Read password from file: {0}").format(self.password_filepath))
<add> logger.info("Read password from file {0}".format(self.password_filepath))
<ide> password = self.load_password()
<ide> else:
<ide> # Else enter the password from the command line
<ide> def get_password(self, description='', confirm=False, clear=False):
<ide> password_confirm = hashlib.sha256(getpass.getpass(_("Password (confirm): ")).encode('utf-8')).hexdigest()
<ide>
<ide> if not self.check_password(password_hashed, password_confirm):
<del> logger.critical(_("Sorry, but passwords did not match..."))
<add> logger.critical("Sorry, passwords do not match. Exit.")
<ide> sys.exit(1)
<ide>
<ide> # Return the plain or hashed password
<ide> def save_password(self, hashed_password):
<ide> try:
<ide> os.makedirs(self.password_path)
<ide> except OSError as e:
<del> logger.error(_("Cannot create Glances directory: {0}").format(e))
<add> logger.error("Cannot create Glances directory: {0}".format(e))
<ide> return
<ide>
<ide> # Create/overwrite the password file
<ide><path>glances/core/glances_processes.py
<ide> def get_max_processes(self):
<ide>
<ide> def set_process_filter(self, value):
<ide> """Set the process filter"""
<del> logger.info(_("Set process filter to %s") % value)
<add> logger.info("Set process filter to {0}".format(value))
<ide> self.process_filter = value
<ide> if value is not None:
<ide> try:
<ide> self.process_filter_re = re.compile(value)
<del> logger.debug(
<del> _("Process filter regular expression compilation OK: %s") % self.get_process_filter())
<add> logger.debug("Process filter regex compilation OK: {0}".format(self.get_process_filter()))
<ide> except Exception:
<del> logger.error(
<del> _("Can not compile process filter regular expression: %s") % value)
<add> logger.error("Cannot compile process filter regex: {0}".format(value))
<ide> self.process_filter_re = None
<ide> else:
<ide> self.process_filter_re = None
<ide><path>glances/core/glances_server.py
<ide> def __init__(self, bind_address, bind_port=61209,
<ide> try:
<ide> self.address_family = socket.getaddrinfo(bind_address, bind_port)[0][0]
<ide> except socket.error as e:
<del> logger.error(_("Couldn't open socket: {0}").format(e))
<add> logger.error("Couldn't open socket: {0}".format(e))
<ide> sys.exit(1)
<ide>
<ide> SimpleXMLRPCServer.__init__(self, (bind_address, bind_port),
<ide> def __init__(self, requestHandler=GlancesXMLRPCHandler,
<ide> try:
<ide> self.server = GlancesXMLRPCServer(args.bind_address, args.port, requestHandler)
<ide> except Exception as e:
<del> logger.critical(_("Cannot start Glances server: {0}").format(e))
<add> logger.critical("Cannot start Glances server: {0}".format(e))
<ide> sys.exit(2)
<ide>
<ide> # The users dict
<ide><path>glances/core/glances_snmp.py
<ide> try:
<ide> from pysnmp.entity.rfc3413.oneliner import cmdgen
<ide> except ImportError:
<del> logger.critical(_("PySNMP library not found."))
<del> print(_("Install it using pip: # pip install pysnmp"))
<add> logger.critical("PySNMP library not found. To install it: pip install pysnmp")
<ide> sys.exit(2)
<ide>
<ide>
<ide><path>glances/core/glances_standalone.py
<ide> def __init__(self, config=None, args=None):
<ide>
<ide> # If process extended stats is disabled by user
<ide> if not args.enable_process_extended:
<del> logger.info(_("Extended stats for top process are disabled (default behavior)"))
<add> logger.info("Extended stats for top process are disabled (default behavior)")
<ide> glances_processes.disable_extended()
<ide> else:
<del> logger.debug(_("Extended stats for top process are enabled"))
<add> logger.debug("Extended stats for top process are enabled")
<ide> glances_processes.enable_extended()
<ide>
<ide> # Manage optionnal process filter
<ide><path>glances/core/glances_stats.py
<ide> def load_plugins(self, args=None):
<ide> # Restoring system path
<ide> sys.path = sys_path
<ide> # Log plugins list
<del> logger.debug(_("Available plugins list: %s"), self.getAllPlugins())
<add> logger.debug("Available plugins list: {0}".format(self.getAllPlugins()))
<ide>
<ide> def getAllPlugins(self):
<ide> """Return the plugins list."""
<ide> def load_limits(self, config=None):
<ide> """Load the stats limits."""
<ide> # For each plugins, call the init_limits method
<ide> for p in self._plugins:
<del> # logger.debug(_("Load limits for %s") % p)
<add> # logger.debug("Load limits for %s" % p)
<ide> self._plugins[p].load_limits(config)
<ide>
<ide> def __update__(self, input_stats):
<ide> def __update__(self, input_stats):
<ide> # For standalone and server modes
<ide> # For each plugins, call the update method
<ide> for p in self._plugins:
<del> # logger.debug(_("Update %s stats") % p)
<add> # logger.debug("Update %s stats" % p)
<ide> self._plugins[p].update()
<ide> else:
<ide> # For Glances client mode
<ide> def set_plugins(self, input_plugins):
<ide> # The key is the plugin name
<ide> # for example, the file glances_xxx.py
<ide> # generate self._plugins_list["xxx"] = ...
<del> logger.debug(_("Init %s plugin") % item)
<add> logger.debug("Init {0} plugin".format(item))
<ide> self._plugins[item] = plugin.Plugin()
<ide> # Restoring system path
<ide> sys.path = sys_path
<ide> def check_snmp(self):
<ide> oid_os_name = clientsnmp.get_by_oid("1.3.6.1.2.1.1.1.0")
<ide> try:
<ide> self.system_name = self.get_system_name(oid_os_name['1.3.6.1.2.1.1.1.0'])
<del> logger.info(_('SNMP system name detected: {0}').format(self.system_name))
<add> logger.info("SNMP system name detected: {0}".format(self.system_name))
<ide> except KeyError:
<ide> self.system_name = None
<del> logger.warning(_('Can not detect SNMP system name'))
<add> logger.warning("Cannot detect SNMP system name")
<ide>
<ide> return ret
<ide>
<ide> def update(self):
<ide> try:
<ide> self._plugins[p].update()
<ide> except Exception as e:
<del> logger.error(_("Error: Update {0} failed: {1}").format(p, e))
<add> logger.error("Update {0} failed: {1}".format(p, e))
<ide><path>glances/outputs/glances_colorconsole.py
<ide> import time
<ide>
<ide> import msvcrt
<add>
<add>from glances.core.glances_globals import logger
<add>
<ide> try:
<ide> import colorconsole
<ide> import colorconsole.terminal
<ide> except ImportError:
<del> logger.critical(_('Colorconsole module not found. Glances cannot start in standalone mode.'))
<add> logger.critical("Colorconsole module not found. Glances cannot start in standalone mode.")
<ide> sys.exit(1)
<ide>
<ide> try:
<ide><path>glances/outputs/glances_csv.py
<ide> def __init__(self, args=None):
<ide> self.csv_file = open(self.csv_filename, 'wb')
<ide> self.writer = csv.writer(self.csv_file)
<ide> except IOError as e:
<del> logger.critical(_("Error: Cannot create the CSV file: {0}").format(e))
<add> logger.critical("Cannot create the CSV file: {0}".format(e))
<ide> sys.exit(2)
<ide>
<del> logger.info(_("Stats dumped to CSV file: {0}").format(self.csv_filename))
<add> logger.info("Stats dumped to CSV file: {0}".format(self.csv_filename))
<ide>
<ide> def exit(self):
<ide> """Close the CSV file."""
<ide><path>glances/outputs/glances_curses.py
<ide> import curses.panel
<ide> from curses.textpad import Textbox
<ide> except ImportError:
<del> logger.critical(
<del> 'Curses module not found. Glances cannot start in standalone mode.')
<add> logger.critical("Curses module not found. Glances cannot start in standalone mode.")
<ide> sys.exit(1)
<ide> else:
<ide> from glances.outputs.glances_colorconsole import WCurseLight
<ide> def __init__(self, args=None):
<ide> # Init the curses screen
<ide> self.screen = curses.initscr()
<ide> if not self.screen:
<del> logger.critical(_("Error: Cannot init the curses library.\n"))
<add> logger.critical("Cannot init the curses library.\n")
<ide> sys.exit(1)
<ide>
<ide> # Set curses options
<ide><path>glances/plugins/glances_batpercent.py
<ide> try:
<ide> import batinfo
<ide> except ImportError:
<del> logger.debug(_("Cannot grab battery sensor. Missing BatInfo library."))
<add> logger.debug("Batinfo library not found. Glances cannot grab battery info.")
<add> pass
<ide>
<ide>
<ide> class Plugin(GlancesPlugin):
<ide><path>glances/plugins/glances_monitor.py
<ide> def __init__(self, args=None):
<ide>
<ide> def load_limits(self, config):
<ide> """Load the monitored list from the conf file."""
<del> logger.debug(_("Monitor plugin configuration detected in the configuration file"))
<add> logger.debug("Monitor plugin configuration detected in the configuration file")
<ide> self.glances_monitors = glancesMonitorList(config)
<ide>
<ide> def update(self):
<ide><path>glances/plugins/glances_plugin.py
<ide> def __init__(self, args=None, items_history_list=None):
<ide> """Init the plugin of plugins class."""
<ide> # Plugin name (= module name without glances_)
<ide> self.plugin_name = self.__class__.__module__[len('glances_'):]
<del> # logger.debug(_("Init plugin %s") % self.plugin_name)
<add> # logger.debug("Init plugin %s" % self.plugin_name)
<ide>
<ide> # Init the args
<ide> self.args = args
<ide> def init_stats_history(self):
<ide> ret = None
<ide> if self.args is not None and self.args.enable_history and self.get_items_history_list() is not None:
<ide> iList = [i['name'] for i in self.get_items_history_list()]
<del> logger.debug(_("Stats history activated for plugin %s (items: %s)") % (
<del> self.plugin_name, iList))
<add> logger.debug("Stats history activated for plugin {0} (items: {0})".format(self.plugin_name, iList))
<ide> ret = {}
<ide> return ret
<ide>
<ide> def reset_stats_history(self):
<ide> """Reset the stats history (dict of list)"""
<ide> if self.args is not None and self.args.enable_history and self.get_items_history_list() is not None:
<ide> iList = [i['name'] for i in self.get_items_history_list()]
<del> logger.debug(
<del> _("Reset history for plugin %s (items: %s)") % (self.plugin_name, iList))
<add> logger.debug("Reset history for plugin {0} (items: {0})".format(self.plugin_name, iList))
<ide> self.stats_history = {}
<ide> return self.stats_history
<ide>
<ide> def get_stats_item(self, item):
<ide> try:
<ide> return json.dumps({item: self.stats[item]})
<ide> except KeyError as e:
<del> logger.error(_("Can not get item %s (%s)") % (item, e))
<add> logger.error("Cannot get item {0} ({1})".format(item, e))
<ide> else:
<ide> return None
<ide> else:
<ide> def get_stats_item(self, item):
<ide> # http://stackoverflow.com/questions/4573875/python-get-index-of-dictionary-item-in-list
<ide> return json.dumps({item: map(itemgetter(item), self.stats)})
<ide> except (KeyError, ValueError) as e:
<del> logger.error(_("Can not get item %s (%s)") % (item, e))
<add> logger.error("Cannot get item {0} ({1})".format(item, e))
<ide> return None
<ide>
<ide> def get_stats_value(self, item, value):
<ide> def get_stats_value(self, item, value):
<ide> try:
<ide> return json.dumps({value: [i for i in self.stats if i[item] == value]})
<ide> except (KeyError, ValueError) as e:
<del> logger.error(
<del> _("Can not get item(%s)=value(%s) (%s)") % (item, value, e))
<add> logger.error("Cannot get item({0})=value({1}) ({2})".format(item, value, e))
<ide> return None
<ide>
<ide> def load_limits(self, config):
| 17
|
Go
|
Go
|
fix testrunwithruntime* on arm
|
bd6317031bb8f7e1a82cbfd254fe60e0de703524
|
<ide><path>integration-cli/docker_cli_daemon_test.go
<ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) {
<ide> }
<ide> `
<ide> ioutil.WriteFile(configName, []byte(config), 0644)
<del> err = s.d.Start("--config-file", configName)
<add> err = s.d.StartWithBusybox("--config-file", configName)
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> // Run with default runtime
<ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) {
<del> err := s.d.Start("--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
<add> err := s.d.StartWithBusybox("--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> // Run with default runtime
<ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) {
<ide>
<ide> // Start a daemon without any extra runtimes
<ide> s.d.Stop()
<del> err = s.d.Start()
<add> err = s.d.StartWithBusybox()
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> // Run with default runtime
<ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) {
<ide>
<ide> // Check that we can select a default runtime
<ide> s.d.Stop()
<del> err = s.d.Start("--default-runtime=vm", "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
<add> err = s.d.StartWithBusybox("--default-runtime=vm", "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
| 1
|
Go
|
Go
|
checkt t.fatalf information for reference path
|
4b1ff89faed5a04d1220c2953b8e72eb4e651dcb
|
<ide><path>reference/reference_test.go
<ide> func TestParseRepositoryInfo(t *testing.T) {
<ide> t.Fatalf("Invalid normalized reference for %q. Expected %q, got %q", r, expected, actual)
<ide> }
<ide> if expected, actual := tcase.FullName, r.FullName(); expected != actual {
<del> t.Fatalf("Invalid normalized reference for %q. Expected %q, got %q", r, expected, actual)
<add> t.Fatalf("Invalid fullName for %q. Expected %q, got %q", r, expected, actual)
<ide> }
<ide> if expected, actual := tcase.Hostname, r.Hostname(); expected != actual {
<ide> t.Fatalf("Invalid hostname for %q. Expected %q, got %q", r, expected, actual)
<ide><path>reference/store_test.go
<ide> func TestInvalidTags(t *testing.T) {
<ide> }
<ide> err = store.AddTag(ref, id, true)
<ide> if err == nil {
<del> t.Fatalf("expected setting digest %q to fail", ref)
<add> t.Fatalf("expected setting tag %q to fail", ref)
<ide> }
<ide>
<ide> }
| 2
|
Mixed
|
Ruby
|
add maildeliveryjob for unified mail delivery
|
f5050d998def98563f8fa4b381c09f563681f159
|
<ide><path>actionmailer/CHANGELOG.md
<del>* Deliver parameterized mail with `ActionMailer::DeliveryJob` and remove `ActionMailer::Parameterized::DeliveryJob`.
<add>* Add `MailDeliveryJob` for delivering both regular and parameterized mail. Deprecate using `DeliveryJob` and `Parameterized::DeliveryJob`.
<ide>
<ide> *Gannon McGibbon*
<ide>
<ide><path>actionmailer/lib/action_mailer.rb
<ide> module ActionMailer
<ide> autoload :TestHelper
<ide> autoload :MessageDelivery
<ide> autoload :DeliveryJob
<add> autoload :MailDeliveryJob
<ide>
<ide> def self.eager_load!
<ide> super
<ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def _protected_ivars # :nodoc:
<ide>
<ide> helper ActionMailer::MailHelper
<ide>
<del> class_attribute :delivery_job, default: ::ActionMailer::DeliveryJob
<add> class_attribute :delivery_job, default: ::ActionMailer::MailDeliveryJob
<ide> class_attribute :default_params, default: {
<ide> mime_version: "1.0",
<ide> charset: "UTF-8",
<ide><path>actionmailer/lib/action_mailer/delivery_job.rb
<ide> class DeliveryJob < ActiveJob::Base # :nodoc:
<ide>
<ide> rescue_from StandardError, with: :handle_exception_with_mailer_class
<ide>
<del> def perform(mailer, mail_method, delivery_method, params, *args) #:nodoc:
<del> mailer_class = params ? mailer.constantize.with(params) : mailer.constantize
<del> mailer_class.public_send(mail_method, *args).send(delivery_method)
<add> before_perform do
<add> ActiveSupport::Deprecation.warn <<~MSG.squish
<add> Sending mail with DeliveryJob and Parameterized::DeliveryJob
<add> is deprecated and will be removed in Rails 6.1.
<add> Please use MailDeliveryJob instead.
<add> MSG
<add> end
<add>
<add> def perform(mailer, mail_method, delivery_method, *args) #:nodoc:
<add> mailer.constantize.public_send(mail_method, *args).send(delivery_method)
<ide> end
<ide>
<ide> private
<ide><path>actionmailer/lib/action_mailer/mail_delivery_job.rb
<add># frozen_string_literal: true
<add>
<add>require "active_job"
<add>
<add>module ActionMailer
<add> # The <tt>ActionMailer::NewDeliveryJob</tt> class is used when you
<add> # want to send emails outside of the request-response cycle. It supports
<add> # sending either parameterized or normal mail.
<add> #
<add> # Exceptions are rescued and handled by the mailer class.
<add> class MailDeliveryJob < ActiveJob::Base # :nodoc:
<add> queue_as { ActionMailer::Base.deliver_later_queue_name }
<add>
<add> rescue_from StandardError, with: :handle_exception_with_mailer_class
<add>
<add> def perform(mailer, mail_method, delivery_method, args:, params: nil) #:nodoc:
<add> mailer_class = params ? mailer.constantize.with(params) : mailer.constantize
<add> mailer_class.public_send(mail_method, *args).send(delivery_method)
<add> end
<add>
<add> private
<add> # "Deserialize" the mailer class name by hand in case another argument
<add> # (like a Global ID reference) raised DeserializationError.
<add> def mailer_class
<add> if mailer = Array(@serialized_arguments).first || Array(arguments).first
<add> mailer.constantize
<add> end
<add> end
<add>
<add> def handle_exception_with_mailer_class(exception)
<add> if klass = mailer_class
<add> klass.handle_exception exception
<add> else
<add> raise exception
<add> end
<add> end
<add> end
<add>end
<ide><path>actionmailer/lib/action_mailer/message_delivery.rb
<ide> def enqueue_delivery(delivery_method, options = {})
<ide> "#deliver_later, 2. only touch the message *within your mailer " \
<ide> "method*, or 3. use a custom Active Job instead of #deliver_later."
<ide> else
<del> args = @mailer_class.name, @action.to_s, delivery_method.to_s, nil, *@args
<ide> job = @mailer_class.delivery_job
<add> args = arguments_for(job, delivery_method)
<ide> job.set(options).perform_later(*args)
<ide> end
<ide> end
<add>
<add> def arguments_for(delivery_job, delivery_method)
<add> if delivery_job <= MailDeliveryJob
<add> [@mailer_class.name, @action.to_s, delivery_method.to_s, args: @args]
<add> else
<add> [@mailer_class.name, @action.to_s, delivery_method.to_s, *@args]
<add> end
<add> end
<ide> end
<ide> end
<ide><path>actionmailer/lib/action_mailer/parameterized.rb
<ide> def respond_to_missing?(method, include_all = false)
<ide> end
<ide> end
<ide>
<add> class DeliveryJob < ActionMailer::DeliveryJob # :nodoc:
<add> def perform(mailer, mail_method, delivery_method, params, *args)
<add> mailer.constantize.with(params).public_send(mail_method, *args).send(delivery_method)
<add> end
<add> end
<add>
<ide> class MessageDelivery < ActionMailer::MessageDelivery # :nodoc:
<ide> def initialize(mailer_class, action, params, *args)
<ide> super(mailer_class, action, *args)
<ide> def enqueue_delivery(delivery_method, options = {})
<ide> if processed?
<ide> super
<ide> else
<del> args = @mailer_class.name, @action.to_s, delivery_method.to_s, @params, *@args
<del> job = @mailer_class.delivery_job
<add> job = @mailer_class.delivery_job
<add> args = arguments_for(job, delivery_method)
<ide> job.set(options).perform_later(*args)
<ide> end
<ide> end
<add>
<add> def arguments_for(delivery_job, delivery_method)
<add> if delivery_job <= MailDeliveryJob
<add> [@mailer_class.name, @action.to_s, delivery_method.to_s, params: @params, args: @args]
<add> else
<add> [@mailer_class.name, @action.to_s, delivery_method.to_s, @params, *@args]
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>actionmailer/lib/action_mailer/test_helper.rb
<ide> def assert_enqueued_emails(number, &block)
<ide> # end
<ide> def assert_enqueued_email_with(mailer, method, args: nil, queue: "mailers", &block)
<ide> args = if args.is_a?(Hash)
<del> [mailer.to_s, method.to_s, "deliver_now", args]
<add> [mailer.to_s, method.to_s, "deliver_now", params: args, args: []]
<ide> else
<del> [mailer.to_s, method.to_s, "deliver_now", nil, *args]
<add> [mailer.to_s, method.to_s, "deliver_now", args: Array(args)]
<ide> end
<ide> assert_enqueued_with(job: mailer.delivery_job, args: args, queue: queue, &block)
<ide> end
<ide><path>actionmailer/test/legacy_delivery_job_test.rb
<add># frozen_string_literal: true
<add>
<add>require "abstract_unit"
<add>require "active_job"
<add>require "mailers/params_mailer"
<add>require "mailers/delayed_mailer"
<add>
<add>class LegacyDeliveryJobTest < ActiveSupport::TestCase
<add> include ActiveJob::TestHelper
<add>
<add> class LegacyDeliveryJob < ActionMailer::DeliveryJob
<add> end
<add>
<add> class LegacyParmeterizedDeliveryJob < ActionMailer::Parameterized::DeliveryJob
<add> end
<add>
<add> setup do
<add> @previous_logger = ActiveJob::Base.logger
<add> ActiveJob::Base.logger = Logger.new(nil)
<add>
<add> @previous_delivery_method = ActionMailer::Base.delivery_method
<add> ActionMailer::Base.delivery_method = :test
<add>
<add> @previous_deliver_later_queue_name = ActionMailer::Base.deliver_later_queue_name
<add> ActionMailer::Base.deliver_later_queue_name = :test_queue
<add> end
<add>
<add> teardown do
<add> ActiveJob::Base.logger = @previous_logger
<add> ParamsMailer.deliveries.clear
<add>
<add> ActionMailer::Base.delivery_method = @previous_delivery_method
<add> ActionMailer::Base.deliver_later_queue_name = @previous_deliver_later_queue_name
<add> end
<add>
<add> test "should send parameterized mail correctly" do
<add> mail = ParamsMailer.with(inviter: "david@basecamp.com", invitee: "jason@basecamp.com").invitation
<add> args = [
<add> "ParamsMailer",
<add> "invitation",
<add> "deliver_now",
<add> { inviter: "david@basecamp.com", invitee: "jason@basecamp.com" },
<add> ]
<add>
<add> with_delivery_job(LegacyParmeterizedDeliveryJob) do
<add> assert_deprecated do
<add> assert_performed_with(job: LegacyParmeterizedDeliveryJob, args: args) do
<add> mail.deliver_later
<add> end
<add> end
<add> end
<add> end
<add>
<add> test "should send mail correctly" do
<add> mail = DelayedMailer.test_message(1, 2, 3)
<add> args = [
<add> "DelayedMailer",
<add> "test_message",
<add> "deliver_now",
<add> 1,
<add> 2,
<add> 3,
<add> ]
<add>
<add> with_delivery_job(LegacyDeliveryJob) do
<add> assert_deprecated do
<add> assert_performed_with(job: LegacyDeliveryJob, args: args) do
<add> mail.deliver_later
<add> end
<add> end
<add> end
<add> end
<add>
<add> private
<add>
<add> def with_delivery_job(job)
<add> old_params_delivery_job = ParamsMailer.delivery_job
<add> old_regular_delivery_job = DelayedMailer.delivery_job
<add> ParamsMailer.delivery_job = job
<add> DelayedMailer.delivery_job = job
<add> yield
<add> ensure
<add> ParamsMailer.delivery_job = old_params_delivery_job
<add> DelayedMailer.delivery_job = old_regular_delivery_job
<add> end
<add>end
<ide><path>actionmailer/test/message_delivery_test.rb
<ide> def test_should_enqueue_and_run_correctly_in_activejob
<ide> end
<ide>
<ide> test "should enqueue the email with :deliver_now delivery method" do
<del> assert_performed_with(job: ActionMailer::DeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", nil, 1, 2, 3]) do
<add> assert_performed_with(job: ActionMailer::MailDeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", args: [1, 2, 3]]) do
<ide> @mail.deliver_later
<ide> end
<ide> end
<ide>
<ide> test "should enqueue the email with :deliver_now! delivery method" do
<del> assert_performed_with(job: ActionMailer::DeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now!", nil, 1, 2, 3]) do
<add> assert_performed_with(job: ActionMailer::MailDeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now!", args: [1, 2, 3]]) do
<ide> @mail.deliver_later!
<ide> end
<ide> end
<ide>
<ide> test "should enqueue a delivery with a delay" do
<ide> travel_to Time.new(2004, 11, 24, 01, 04, 44) do
<del> assert_performed_with(job: ActionMailer::DeliveryJob, at: Time.current + 10.minutes, args: ["DelayedMailer", "test_message", "deliver_now", nil, 1, 2, 3]) do
<add> assert_performed_with(job: ActionMailer::MailDeliveryJob, at: Time.current + 10.minutes, args: ["DelayedMailer", "test_message", "deliver_now", args: [1, 2, 3]]) do
<ide> @mail.deliver_later wait: 10.minutes
<ide> end
<ide> end
<ide> end
<ide>
<ide> test "should enqueue a delivery at a specific time" do
<ide> later_time = Time.current + 1.hour
<del> assert_performed_with(job: ActionMailer::DeliveryJob, at: later_time, args: ["DelayedMailer", "test_message", "deliver_now", nil, 1, 2, 3]) do
<add> assert_performed_with(job: ActionMailer::MailDeliveryJob, at: later_time, args: ["DelayedMailer", "test_message", "deliver_now", args: [1, 2, 3]]) do
<ide> @mail.deliver_later wait_until: later_time
<ide> end
<ide> end
<ide>
<ide> test "should enqueue the job on the correct queue" do
<del> assert_performed_with(job: ActionMailer::DeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", nil, 1, 2, 3], queue: "test_queue") do
<add> assert_performed_with(job: ActionMailer::MailDeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", args: [1, 2, 3]], queue: "test_queue") do
<ide> @mail.deliver_later
<ide> end
<ide> end
<ide> def test_should_enqueue_and_run_correctly_in_activejob
<ide> old_delivery_job = DelayedMailer.delivery_job
<ide> DelayedMailer.delivery_job = DummyJob
<ide>
<del> assert_performed_with(job: DummyJob, args: ["DelayedMailer", "test_message", "deliver_now", nil, 1, 2, 3]) do
<add> assert_performed_with(job: DummyJob, args: ["DelayedMailer", "test_message", "deliver_now", args: [1, 2, 3]]) do
<ide> @mail.deliver_later
<ide> end
<ide>
<ide> DelayedMailer.delivery_job = old_delivery_job
<ide> end
<ide>
<del> class DummyJob < ActionMailer::DeliveryJob; end
<add> class DummyJob < ActionMailer::MailDeliveryJob; end
<ide>
<ide> test "can override the queue when enqueuing mail" do
<del> assert_performed_with(job: ActionMailer::DeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", nil, 1, 2, 3], queue: "another_queue") do
<add> assert_performed_with(job: ActionMailer::MailDeliveryJob, args: ["DelayedMailer", "test_message", "deliver_now", args: [1, 2, 3]], queue: "another_queue") do
<ide> @mail.deliver_later(queue: :another_queue)
<ide> end
<ide> end
<ide><path>actionmailer/test/parameterized_test.rb
<ide> class ParameterizedTest < ActiveSupport::TestCase
<ide> include ActiveJob::TestHelper
<ide>
<del> class DummyDeliveryJob < ActionMailer::DeliveryJob
<add> class DummyDeliveryJob < ActionMailer::MailDeliveryJob
<ide> end
<ide>
<ide> setup do
<ide> class DummyDeliveryJob < ActionMailer::DeliveryJob
<ide> "ParamsMailer",
<ide> "invitation",
<ide> "deliver_now",
<del> { inviter: "david@basecamp.com", invitee: "jason@basecamp.com" },
<add> params: { inviter: "david@basecamp.com", invitee: "jason@basecamp.com" },
<add> args: [],
<ide> ]
<del> assert_performed_with(job: ActionMailer::DeliveryJob, args: args) do
<add> assert_performed_with(job: ActionMailer::MailDeliveryJob, args: args) do
<ide> @mail.deliver_later
<ide> end
<ide> end
<ide> class DummyDeliveryJob < ActionMailer::DeliveryJob
<ide> "ParamsMailer",
<ide> "invitation",
<ide> "deliver_now",
<del> { inviter: "david@basecamp.com", invitee: "jason@basecamp.com" },
<add> params: { inviter: "david@basecamp.com", invitee: "jason@basecamp.com" },
<add> args: [],
<ide> ]
<ide>
<ide> with_delivery_job DummyDeliveryJob do
<ide><path>actionmailer/test/test_helper_test.rb
<ide> def test_parameter_args
<ide> end
<ide> end
<ide>
<del>class CustomDeliveryJob < ActionMailer::DeliveryJob
<add>class CustomDeliveryJob < ActionMailer::MailDeliveryJob
<ide> end
<ide>
<ide> class CustomDeliveryMailer < TestHelperMailer
| 12
|
Javascript
|
Javascript
|
handle quotes around email addresses
|
a9d227120dc2d433372da415a450e56b783b57a0
|
<ide><path>src/ngSanitize/filter/linky.js
<ide> */
<ide> angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
<ide> var LINKY_URL_REGEXP =
<del> /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>]/,
<add> /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"]/,
<ide> MAILTO_REGEXP = /^mailto:/;
<ide>
<ide> return function(text, target) {
<ide><path>test/ngSanitize/filter/linkySpec.js
<ide> describe('linky', function() {
<ide> toEqual('<a href="mailto:me@example.com">me@example.com</a>');
<ide> expect(linky("send email to me@example.com, but")).
<ide> toEqual('send email to <a href="mailto:me@example.com">me@example.com</a>, but');
<add> expect(linky("my email is \"me@example.com\"")).
<add> toEqual('my email is "<a href="mailto:me@example.com">me@example.com</a>"');
<ide> });
<ide>
<ide> it('should handle target:', function() {
| 2
|
Javascript
|
Javascript
|
fix auxiliary files for compilation.renameasset
|
b6bfe8b891a9f5f0bf0b56ab3cd77734a115fc3e
|
<ide><path>lib/Compilation.js
<ide> Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
<ide> delete this.assets[file];
<ide> this.assets[newFile] = source;
<ide> for (const chunk of this.chunks) {
<del> const size = chunk.files.size;
<del> chunk.files.delete(file);
<del> if (size !== chunk.files.size) {
<del> chunk.files.add(newFile);
<add> {
<add> const size = chunk.files.size;
<add> chunk.files.delete(file);
<add> if (size !== chunk.files.size) {
<add> chunk.files.add(newFile);
<add> }
<add> }
<add> {
<add> const size = chunk.auxiliaryFiles.size;
<add> chunk.auxiliaryFiles.delete(file);
<add> if (size !== chunk.auxiliaryFiles.size) {
<add> chunk.auxiliaryFiles.add(newFile);
<add> }
<ide> }
<ide> }
<ide> }
| 1
|
Text
|
Text
|
add asp.net mvc information
|
f423f0449598ba314fad2440c192f1ba1c7a1061
|
<ide><path>guide/english/aspnet/index.md
<ide> Server-side programming languages like C# and VB .NET may be used to code the ba
<ide>
<ide> ASP.NET offers different frameworks for creating web applications: For e.g Web Forms and ASP.NET MVC.
<ide>
<del>
<ide> #### More Information:
<ide> - [ASP .NET Tutorials](https://www.tutorialspoint.com/asp.net/)
<ide> - [ASP .NET Site](https://www.asp.net/)
<ide> - [ASP .NET Microsoft Documentation](https://docs.microsoft.com/en-us/aspnet/#pivot=aspnet/)
<add>- [ASP .NET MVC Site](https://www.asp.net/mvc/)
<add>- [ASP .NET MVC Tutorials](https://www.tutorialspoint.com/asp.net_mvc/)
<add>- [ASP .NET MVC Interview Questions](https://medium.com/dot-net-tutorial/top-50-asp-net-mvc-interview-questions-with-answers-1fd9b1638c61)
<ide>
<ide> ASP.Net development is now available on Mac and Linux, Checkout more here:
<ide> - [ASP .NET Core](https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app-xplat/start-mvc?view=aspnetcore-2.1)
<del>
| 1
|
PHP
|
PHP
|
add bus facade
|
ed2c0546d1c93b78cfcb4148b754066a1e4df045
|
<ide><path>config/app.php
<ide> 'Artisan' => 'Illuminate\Support\Facades\Artisan',
<ide> 'Auth' => 'Illuminate\Support\Facades\Auth',
<ide> 'Blade' => 'Illuminate\Support\Facades\Blade',
<add> 'Bus' => 'Illuminate\Support\Facades\Bus',
<ide> 'Cache' => 'Illuminate\Support\Facades\Cache',
<ide> 'Config' => 'Illuminate\Support\Facades\Config',
<ide> 'Cookie' => 'Illuminate\Support\Facades\Cookie',
| 1
|
Text
|
Text
|
add a comment about live reload
|
559c302094f578153906ab2a1a12ed737ee04741
|
<ide><path>docs/Debugging.md
<ide> To debug the javascript code of your react app do the following:
<ide> 5. You should now be able to debug as you normally would.
<ide>
<ide> ### Optional
<del>Install the [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) extension for Google Chrome. This will allow you to navigate the view hierarchy if you select the ```React``` tab when the developer tools are open.
<ide>\ No newline at end of file
<add>Install the [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) extension for Google Chrome. This will allow you to navigate the view hierarchy if you select the ```React``` tab when the developer tools are open.
<add>
<add>## Live Reload.
<add>To activate Live Reload do the following:
<add>
<add>1. Run your application in the iOS simulator.
<add>2. Press ```Control + Command + Z```.
<add>3. You will now see the `Enable/Disable Live Reload`, `Reload` and `Enable/Disable Debugging` options.
<ide>\ No newline at end of file
| 1
|
PHP
|
PHP
|
remove the array_fetch helper
|
6f7a98ea4a62fae6eace3c410d189fa5fd8c4ace
|
<ide><path>src/Illuminate/Support/helpers.php
<ide> function array_except($array, $keys)
<ide> }
<ide> }
<ide>
<del>if (! function_exists('array_fetch')) {
<del> /**
<del> * Fetch a flattened array of a nested array element.
<del> *
<del> * @param array $array
<del> * @param string $key
<del> * @return array
<del> *
<del> * @deprecated since version 5.1. Use array_pluck instead.
<del> */
<del> function array_fetch($array, $key)
<del> {
<del> return Arr::fetch($array, $key);
<del> }
<del>}
<del>
<ide> if (! function_exists('array_first')) {
<ide> /**
<ide> * Return the first element in an array passing a given truth test.
| 1
|
PHP
|
PHP
|
view() helper
|
1d6ad39f84b5fa677b049e68b86ddbd12cf674eb
|
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function redirect($uri, $destination, $status = 301)
<ide> ->defaults('status', $status);
<ide> }
<ide>
<add> /**
<add> * Register a new route that returns a view.
<add> *
<add> * @param string $uri
<add> * @param string $view
<add> * @return \Illuminate\Routing\Route
<add> */
<add> public function view($uri, $view)
<add> {
<add> return $this->get($uri, '\Illuminate\Routing\ViewController')
<add> ->defaults('view', $view);
<add> }
<add>
<ide> /**
<ide> * Register a new route with the given verbs.
<ide> *
<ide><path>src/Illuminate/Routing/ViewController.php
<add><?php
<add>
<add>namespace Illuminate\Routing;
<add>
<add>use Illuminate\Contracts\View\Factory as ViewFactory;
<add>
<add>class ViewController extends Controller
<add>{
<add> /**
<add> * The view factory instance.
<add> *
<add> * @var \Illuminate\Contracts\View\Factory
<add> */
<add> protected $view;
<add>
<add> /**
<add> * Create a new view controller instance.
<add> *
<add> * @param \Illuminate\Contracts\View\Factory $view
<add> */
<add> public function __construct(ViewFactory $view)
<add> {
<add> $this->view = $view;
<add> }
<add>
<add> /**
<add> * Invoke the controller method.
<add> *
<add> * @param string $view
<add> * @return \Illuminate\Contracts\View\View
<add> */
<add> public function __invoke($view)
<add> {
<add> return $this->view->make($view);
<add> }
<add>}
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> namespace Illuminate\Tests\Routing;
<ide>
<ide> use stdClass;
<add>use Mockery as m;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Routing\Route;
<ide> use Illuminate\Contracts\Routing\Registrar;
<ide> use Illuminate\Auth\Middleware\Authenticate;
<ide> use Symfony\Component\HttpFoundation\Response;
<add>use Illuminate\Contracts\View\Factory as ViewFactory;
<ide> use Illuminate\Routing\Middleware\SubstituteBindings;
<ide>
<ide> class RoutingRouteTest extends TestCase
<ide> public function testRouteRedirect()
<ide> $this->assertEquals(302, $response->getStatusCode());
<ide> }
<ide>
<add> public function testRouteView()
<add> {
<add> $container = new Container;
<add> $factory = m::mock('Illuminate\View\Factory');
<add> $factory->shouldReceive('make')->once()->with('pages.contact')->andReturn('Contact us');
<add> $router = new Router(new Dispatcher, $container);
<add> $container->bind(ViewFactory::class, function () use ($factory) {
<add> return $factory;
<add> });
<add> $container->singleton(Registrar::class, function () use ($router) {
<add> return $router;
<add> });
<add>
<add> $router->view('contact', 'pages.contact');
<add>
<add> $this->assertEquals('Contact us', $router->dispatch(Request::create('contact', 'GET'))->getContent());
<add> }
<add>
<ide> protected function getRouter()
<ide> {
<ide> $container = new Container;
| 3
|
Text
|
Text
|
add notes for v1.5.2
|
b0f2ee7cc4b05c495098f1619a20dd7b652c70cd
|
<ide><path>CHANGELOG.md
<add><a name="1.5.2"></a>
<add># 1.5.2 differential-recovery (2016-03-18)
<add>
<add>This release reverts a breaking change that accidentally made it into the 1.5.1 release. See [fee7bac3](https://github.com/angular/angular.js/commit/fee7bac392db24b6006d6a57ba71526f3afa102c) for more info.
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **ngAnimate.$animate:** remove animation callbacks when the element is removed
<add> ([ce7f4000](https://github.com/angular/angular.js/commit/ce7f400011e1e2e1b9316f18ce87b87b79d878b4))
<add>
<add>
<add>## Breaking Changes
<add>
<add>
<add>
<ide> <a name="1.4.10"></a>
<ide> # 1.4.10 benignant-oscillation (2016-03-16)
<ide>
<ide>
<ide> ## Breaking Changes
<ide>
<add>### Upgrade to 1.5.1
<add>This version of AngularJS is problematic due to a issue during its release. Please upgrade to version 1.5.1.
<add>
<ide> - **ngAria:** due to [d06431e5](https://github.com/angular/angular.js/commit/d06431e5309bb0125588877451dc79b935808134),
<ide> Where appropriate, ngAria now applies ARIA to custom controls only, not native inputs. Because of this, support for `aria-multiline` on textareas has been removed.
<ide>
| 1
|
Text
|
Text
|
add information on jsx element keys
|
5d64199bb6d5a875206cdcc552cdcb4bf32c7e97
|
<ide><path>docs/docs/02.3-jsx-gotchas.md
<ide> A safer alternative is to find the [unicode number corresponding to the entity](
<ide> <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
<ide> ```
<ide>
<del>You can use mixed arrays with strings and JSX elements.
<add>You can use mixed arrays with strings and JSX elements. Each JSX element in the array needs a unique key.
<ide>
<ide> ```javascript
<del><div>{['First ', <span>·</span>, ' Second']}</div>
<add><div>{['First ', <span key="middot">·</span>, ' Second']}</div>
<ide> ```
<ide>
<ide> As a last resort, you always have the ability to [insert raw HTML](/react/tips/dangerously-set-inner-html.html).
| 1
|
Python
|
Python
|
save layers for access in encoderscaffold
|
9f9b430710273163769033660ad07715b243d269
|
<ide><path>official/nlp/modeling/networks/encoder_scaffold.py
<ide> def __init__(self,
<ide> inputs = embedding_network.inputs
<ide> embeddings, attention_mask = embedding_network(inputs)
<ide> embedding_layer = None
<add> position_embedding_layer = None
<add> type_embedding_layer = None
<add> embedding_norm_layer = None
<ide> else:
<ide> embedding_network = None
<ide> seq_length = embedding_cfg.get('seq_length', None)
<ide> def __init__(self,
<ide>
<ide> self._embedding_layer = embedding_layer
<ide> self._embedding_network = embedding_network
<add> self._position_embedding_layer = position_embedding_layer
<add> self._type_embedding_layer = type_embedding_layer
<add> self._embedding_norm_layer = embedding_norm_layer
<add> self._embedding_network = embedding_network
<ide> self._hidden_layers = hidden_layers
<ide> self._pooler_layer = pooler_layer
<ide>
| 1
|
Text
|
Text
|
add note about hmr websocket to upgrade guide
|
900ec48c0344e230dbf696fdcb8f17be14c6b72d
|
<ide><path>docs/upgrading.md
<ide> The `className` prop is unchanged and will still be passed to the underlying `<i
<ide>
<ide> See the [documentation](https://nextjs.org/docs/basic-features/image-optimization#styling) for more info.
<ide>
<add>### Next.js' HMR connection now uses a WebSocket
<add>
<add>Previously, Next.js used a [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) connection to receive HMR events. Next.js 12 now uses a WebSocket connection.
<add>
<add>In some cases when proxying requests to the Next.js dev server, you will need to ensure the upgrade request is handled correctly. For example, in `nginx` you would need to add the following configuration:
<add>
<add>```nginx
<add>location /_next/webpack-hmr {
<add> proxy_pass http://localhost:3000/_next/webpack-hmr;
<add> proxy_http_version 1.1;
<add> proxy_set_header Upgrade $http_upgrade;
<add> proxy_set_header Connection "upgrade";
<add>}
<add>```
<add>
<ide> ### Webpack 4 support has been removed
<ide>
<ide> If you are already using webpack 5 you can skip this section.
| 1
|
Ruby
|
Ruby
|
fix md5 compat layer
|
f01a38772aa7e865a38c71e73661fb14825da9b9
|
<ide><path>Library/Homebrew/compat/md5.rb
<ide> class Formula
<ide> def self.md5(val)
<del> @stable ||= create_spec(SoftwareSpec)
<del> @stable.md5(val)
<add> stable.md5(val)
<ide> end
<ide> end
<ide>
| 1
|
Python
|
Python
|
add k.tile test
|
15d0b0ea08833b8f2db19e2da1ac428bad69d4cc
|
<ide><path>keras/backend/tensorflow_backend.py
<ide> def repeat(x, n):
<ide>
<ide>
<ide> def tile(x, n):
<add> if not hasattr(n, 'shape') and not hasattr(n, '__len__'):
<add> n = [n]
<ide> return tf.tile(x, n)
<ide>
<ide>
<ide><path>tests/keras/backend/test_backends.py
<ide> def test_repeat_elements(self):
<ide> assert_allclose(np_rep, th_rep, atol=1e-05)
<ide> assert_allclose(np_rep, tf_rep, atol=1e-05)
<ide>
<add> def test_tile(self):
<add> shape = (3, 4)
<add> arr = np.arange(np.prod(shape)).reshape(shape)
<add> arr_th = KTH.variable(arr)
<add> arr_tf = KTF.variable(arr)
<add>
<add> n = (2, 1)
<add> th_rep = KTH.eval(KTH.tile(arr_th, n))
<add> tf_rep = KTF.eval(KTF.tile(arr_tf, n))
<add> assert_allclose(tf_rep, th_rep, atol=1e-05)
<add>
<ide> def test_value_manipulation(self):
<ide> val = np.random.random((4, 2))
<ide> xth = KTH.variable(val)
| 2
|
PHP
|
PHP
|
allow higher order partition
|
724950a42c225c7b53c56283c01576b050fea37a
|
<ide><path>src/Illuminate/Support/Collection.php
<ide> protected function getArrayableItems($items)
<ide> public function __get($key)
<ide> {
<ide> $proxies = [
<del> 'each', 'map', 'first', 'sortBy',
<add> 'each', 'map', 'first', 'partition', 'sortBy',
<ide> 'sortByDesc', 'sum', 'reject', 'filter',
<ide> ];
<ide>
| 1
|
Text
|
Text
|
apply edits and suggestions
|
ab2a95db8088b7607017671b82e396bcd9e80332
|
<ide><path>guides/source/active_storage_overview.md
<ide> config.active_storage.service = :s3
<ide> Continue reading for more information on the built-in service adapters (e.g.
<ide> `Disk` and `S3`) and the configuration they require.
<ide>
<del>Mirrored services can be used to facilitate a migration between services in
<del>production. You can start mirroring to the new service, copy existing files from
<del>the old service to the new, then go all-in on the new service.
<del>
<del>If you wish to transform your images, add `mini_magick` to your Gemfile:
<del>
<del>``` ruby
<del>gem 'mini_magick'
<del>```
<del>
<ide> ### Disk Service
<ide> Declare a Disk service in `config/storage.yml`:
<ide>
<ide> gem "google-cloud-storage", "~> 1.3", require: false
<ide>
<ide> ### Mirror Service
<ide>
<del>You can keep multiple services in sync by defining a mirror service. When
<del>a file is uploaded or deleted, it's done across all the mirrored services.
<del>Define each of the services you'd like to use as described above and reference
<del>them from a mirrored service.
<add>You can keep multiple services in sync by defining a mirror service. When a file
<add>is uploaded or deleted, it's done across all the mirrored services. Mirrored
<add>services can be used to facilitate a migration between services in production.
<add>You can start mirroring to the new service, copy existing files from the old
<add>service to the new, then go all-in on the new service. Define each of the
<add>services you'd like to use as described above and reference them from a mirrored
<add>service.
<ide>
<ide> ``` yaml
<ide> s3_west_coast:
<ide> Call `images.attach` to add new images to an existing message:
<ide> @message.images.attach(params[:images])
<ide> ```
<ide>
<del>Call `images.attached?`` to determine whether a particular message has any images:
<add>Call `images.attached?` to determine whether a particular message has any images:
<ide>
<ide> ```ruby
<ide> @message.images.attached?
<ide> Create Variations of Attached Image
<ide> Sometimes your application requires images in a different format than
<ide> what was uploaded. To create variation of the image, call `variant` on the Blob.
<ide> You can pass any [MiniMagick](https://github.com/minimagick/minimagick)
<del>supported transformation.
<add>supported transformation to the method.
<add>
<add>To enable variants, add `mini_magick` to your Gemfile:
<add>
<add>``` ruby
<add>gem 'mini_magick'
<add>```
<ide>
<ide> When the browser hits the variant URL, ActiveStorage will lazy transform the
<ide> original blob into the format you specified and redirect to its new service
<ide> class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
<ide> end
<ide> ```
<ide>
<del>If your system tests verify the deletion of a model with attachments and your
<add>If your system tests verify the deletion of a model with attachments and you're
<ide> using Active Job, set your test environment to use the inline queue adapter so
<ide> the purge job is executed immediately rather at an unknown time in the future.
<ide>
<ide> config.active_job.queue_adapter = :inline
<ide> config.active_storage.service = :local_test
<ide> ```
<ide>
<del>Add Support Additional Cloud Service
<add>Add Support for Additional Cloud Services
<ide> ------------------------------------
<ide>
<del>If you need to support a cloud service other these, you will need to implement
<del>the Service. Each service extends
<add>If you need to support a cloud service other than these, you will need to
<add>implement the Service. Each service extends
<ide> [`ActiveStorage::Service`](https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/service.rb)
<ide> by implementing the methods necessary to upload and download files to the cloud.
| 1
|
PHP
|
PHP
|
fix fqcn for exceptions via sniffer run
|
a70b8895e421baf45d5aca93a3abf52d9d917577
|
<ide><path>src/Cache/Engine/FileEngine.php
<ide> use Cake\Cache\InvalidArgumentException;
<ide> use CallbackFilterIterator;
<ide> use Exception;
<add>use FilesystemIterator;
<ide> use LogicException;
<ide> use RecursiveDirectoryIterator;
<ide> use RecursiveIteratorIterator;
<ide> public function clear()
<ide>
<ide> $directory = new RecursiveDirectoryIterator(
<ide> $this->_config['path'],
<del> \FilesystemIterator::SKIP_DOTS
<add> FilesystemIterator::SKIP_DOTS
<ide> );
<ide> $contents = new RecursiveIteratorIterator(
<ide> $directory,
<ide><path>src/Collection/CollectionTrait.php
<ide> use Cake\Collection\Iterator\UnfoldIterator;
<ide> use Cake\Collection\Iterator\ZipIterator;
<ide> use Countable;
<add>use InvalidArgumentException;
<ide> use LimitIterator;
<ide> use LogicException;
<ide> use OuterIterator;
<ide> public function last()
<ide> public function takeLast(int $howMany): CollectionInterface
<ide> {
<ide> if ($howMany < 1) {
<del> throw new \InvalidArgumentException("The takeLast method requires a number greater than 0.");
<add> throw new InvalidArgumentException("The takeLast method requires a number greater than 0.");
<ide> }
<ide>
<ide> $iterator = $this->optimizeUnwrap();
<ide><path>src/Database/QueryCompiler.php
<ide>
<ide> use Cake\Database\Expression\QueryExpression;
<ide> use Closure;
<add>use Countable;
<ide>
<ide> /**
<ide> * Responsible for compiling a Query object into its SQL representation
<ide> protected function _sqlCompiler(string &$sql, Query $query, ValueBinder $generat
<ide> {
<ide> return function ($parts, $name) use (&$sql, $query, $generator) {
<ide> if (!isset($parts) ||
<del> ((is_array($parts) || $parts instanceof \Countable) && !count($parts))
<add> ((is_array($parts) || $parts instanceof Countable) && !count($parts))
<ide> ) {
<ide> return;
<ide> }
<ide><path>src/Database/SqlDialectTrait.php
<ide> namespace Cake\Database;
<ide>
<ide> use Cake\Database\Expression\Comparison;
<add>use RuntimeException;
<ide>
<ide> /**
<ide> * Sql dialect trait
<ide> protected function _updateQueryTranslator(Query $query): Query
<ide> protected function _removeAliasesFromConditions(Query $query): Query
<ide> {
<ide> if ($query->clause('join')) {
<del> throw new \RuntimeException(
<add> throw new RuntimeException(
<ide> 'Aliases are being removed from conditions for UPDATE/DELETE queries, ' .
<ide> 'this can break references to joined tables.'
<ide> );
<ide><path>src/ORM/Behavior/Translate/ShadowTableStrategy.php
<ide> protected function rowMapper($results, $locale)
<ide> $allowEmpty = $this->_config['allowEmptyTranslations'];
<ide>
<ide> return $results->map(function ($row) use ($allowEmpty) {
<add> /** @var \Cake\Datasource\EntityInterface|array|null $row */
<ide> if ($row === null) {
<ide> return $row;
<ide> }
<ide><path>src/ORM/Marshaller.php
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\InvalidPropertyInterface;
<ide> use Cake\ORM\Association\BelongsToMany;
<add>use InvalidArgumentException;
<ide> use RuntimeException;
<ide>
<ide> /**
<ide> protected function _buildPropertyMap(array $data, array $options): array
<ide> // it is a missing association that we should error on.
<ide> if (!$this->_table->hasAssociation($key)) {
<ide> if (substr($key, 0, 1) !== '_') {
<del> throw new \InvalidArgumentException(sprintf(
<add> throw new InvalidArgumentException(sprintf(
<ide> 'Cannot marshal data for "%s" association. It is not associated with "%s".',
<ide> $key,
<ide> $this->_table->getAlias()
<ide><path>src/ORM/Query.php
<ide> namespace Cake\ORM;
<ide>
<ide> use ArrayObject;
<add>use BadMethodCallException;
<ide> use Cake\Database\Connection;
<ide> use Cake\Database\ExpressionInterface;
<ide> use Cake\Database\Query as DatabaseQuery;
<ide> use Cake\Datasource\QueryInterface;
<ide> use Cake\Datasource\QueryTrait;
<ide> use Cake\Datasource\ResultSetInterface;
<add>use InvalidArgumentException;
<ide> use JsonSerializable;
<ide> use RuntimeException;
<ide> use Traversable;
<ide> public function selectAllExcept($table, array $excludedFields, $overwrite = fals
<ide> }
<ide>
<ide> if (!($table instanceof Table)) {
<del> throw new \InvalidArgumentException('You must provide either an Association or a Table object');
<add> throw new InvalidArgumentException('You must provide either an Association or a Table object');
<ide> }
<ide>
<ide> $fields = array_diff($table->getSchema()->columns(), $excludedFields);
<ide> public function __call($method, $arguments)
<ide> return $this->_call($method, $arguments);
<ide> }
<ide>
<del> throw new \BadMethodCallException(
<add> throw new BadMethodCallException(
<ide> sprintf('Cannot call method "%s" on a "%s" query', $method, $this->type())
<ide> );
<ide> }
<ide><path>src/ORM/Table.php
<ide> use Cake\Utility\Inflector;
<ide> use Cake\Validation\ValidatorAwareInterface;
<ide> use Cake\Validation\ValidatorAwareTrait;
<add>use Exception;
<ide> use InvalidArgumentException;
<ide> use RuntimeException;
<ide>
<ide> public function saveMany(iterable $entities, $options = [])
<ide> }
<ide> }
<ide> });
<del> } catch (\Exception $e) {
<add> } catch (Exception $e) {
<ide> $cleanup($entities);
<ide>
<ide> throw $e;
<ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> use Cake\Datasource\FixtureInterface;
<ide> use Cake\TestSuite\TestCase;
<ide> use PDOException;
<add>use RuntimeException;
<ide> use UnexpectedValueException;
<ide>
<ide> /**
<ide> public function load(TestCase $test): void
<ide> get_class($test),
<ide> $e->getMessage()
<ide> );
<del> throw new \RuntimeException($msg, 0, $e);
<add> throw new RuntimeException($msg, 0, $e);
<ide> }
<ide> }
<ide>
<ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> use Cake\Utility\Security;
<ide> use Cake\Utility\Text;
<ide> use Cake\View\Helper\SecureFieldTokenTrait;
<add>use Exception;
<ide> use LogicException;
<ide> use PHPUnit\Exception as PhpUnitException;
<ide> use Throwable;
<ide> public function assertFileResponse(string $expected, string $message = ''): void
<ide> */
<ide> protected function extractVerboseMessage(string $message): string
<ide> {
<del> if ($this->_exception instanceof \Exception) {
<add> if ($this->_exception instanceof Exception) {
<ide> $message .= $this->extractExceptionMessage($this->_exception);
<ide> }
<ide> if ($this->_controller === null) {
<ide> return $message;
<ide> }
<ide> $error = $this->_controller->viewBuilder()->getVar('error');
<del> if ($error instanceof \Exception) {
<add> if ($error instanceof Exception) {
<ide> $message .= $this->extractExceptionMessage($this->viewVariable('error'));
<ide> }
<ide>
<ide> protected function extractVerboseMessage(string $message): string
<ide> * @param \Exception $exception Exception to extract
<ide> * @return string
<ide> */
<del> protected function extractExceptionMessage(\Exception $exception)
<add> protected function extractExceptionMessage(Exception $exception)
<ide> {
<ide> return PHP_EOL .
<ide> sprintf('Possibly related to %s: "%s" ', get_class($exception), $exception->getMessage()) .
<ide><path>src/TestSuite/TestListenerTrait.php
<ide> use PHPUnit\Framework\Test;
<ide> use PHPUnit\Framework\TestSuite;
<ide> use PHPUnit\Framework\Warning;
<add>use Throwable;
<ide>
<ide> trait TestListenerTrait
<ide> {
<ide> public function endTest(Test $test, float $time): void
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function addSkippedTest(Test $test, \Throwable $t, float $time): void
<add> public function addSkippedTest(Test $test, Throwable $t, float $time): void
<ide> {
<ide> }
<ide>
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function addError(Test $test, \Throwable $t, float $time): void
<add> public function addError(Test $test, Throwable $t, float $time): void
<ide> {
<ide> }
<ide>
<ide> public function addFailure(Test $test, AssertionFailedError $e, float $time): vo
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function addRiskyTest(Test $test, \Throwable $e, float $time): void
<add> public function addRiskyTest(Test $test, Throwable $e, float $time): void
<ide> {
<ide> }
<ide>
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function addIncompleteTest(Test $test, \Throwable $e, float $time): void
<add> public function addIncompleteTest(Test $test, Throwable $e, float $time): void
<ide> {
<ide> }
<ide> }
<ide><path>src/Validation/Validation.php
<ide>
<ide> use Cake\I18n\Time;
<ide> use Cake\Utility\Text;
<add>use Countable;
<ide> use DateTimeInterface;
<ide> use InvalidArgumentException;
<ide> use LogicException;
<ide> public static function creditCard($check, $type = 'fast', bool $deep = false, ?s
<ide> */
<ide> public static function numElements($check, string $operator, int $expectedCount): bool
<ide> {
<del> if (!is_array($check) && !$check instanceof \Countable) {
<add> if (!is_array($check) && !$check instanceof Countable) {
<ide> return false;
<ide> }
<ide>
<ide><path>src/View/HelperRegistry.php
<ide> public function __isset($helper)
<ide>
<ide> try {
<ide> $this->load($helper);
<del> } catch (Exception\MissingHelperException $exception) {
<add> } catch (MissingHelperException $exception) {
<ide> if ($this->_View->getPlugin()) {
<ide> $this->load($this->_View->getPlugin() . '.' . $helper);
<ide>
| 13
|
Python
|
Python
|
remove unused variables noticed by pyflakes
|
1dc081cb6b5c9ea0ae96875a31e73f9caed34b6e
|
<ide><path>libcloud/drivers/elastichosts.py
<ide> import base64
<ide>
<ide> from libcloud.types import Provider, NodeState, InvalidCredsException
<del>from libcloud.base import ConnectionUserAndKey, Response, NodeAuthPassword
<del>from libcloud.base import NodeDriver, NodeSize, Node, NodeLocation
<add>from libcloud.base import ConnectionUserAndKey, Response
<add>from libcloud.base import NodeDriver, NodeSize, Node
<ide> from libcloud.base import NodeImage
<ide>
<ide> # JSON is included in the standard library starting with Python 2.6. For 2.5
<ide> def parse_body(self):
<ide>
<ide> def parse_error(self):
<ide> error_header = self.headers.get('x-elastic-error', '')
<del> message = self.body
<del>
<ide> return 'X-Elastic-Error: %s (%s)' % (error_header, self.body.strip())
<ide>
<ide> class ElasticHostsNodeSize(NodeSize):
| 1
|
PHP
|
PHP
|
add check to sqlserver query compiler
|
8fbf6d51b4bc75859e39645527044be888f1edc4
|
<ide><path>src/Database/SqlserverCompiler.php
<ide> */
<ide> namespace Cake\Database;
<ide>
<add>use Cake\Database\Exception as DatabaseException;
<ide> use Cake\Database\Expression\FunctionExpression;
<ide>
<ide> /**
<ide> protected function _buildWithPart(array $parts, Query $query, ValueBinder $gener
<ide> */
<ide> protected function _buildInsertPart(array $parts, Query $query, ValueBinder $generator): string
<ide> {
<add> if (!isset($parts[0])) {
<add> throw new DatabaseException(
<add> 'Could not compile insert query. No table was specified. ' .
<add> 'Use `into()` to define a table.'
<add> );
<add> }
<ide> $table = $parts[0];
<ide> $columns = $this->_stringifyExpressions($parts[1], $generator);
<ide> $modifiers = $this->_buildModifierPart($query->clause('modifier'), $query, $generator);
| 1
|
Text
|
Text
|
add link to the glamorous example
|
6ca1feaf98b2df0a700327b85609bdcb0fc6c51d
|
<ide><path>readme.md
<ide> export default () => (
<ide> <summary>
<ide> <b>Examples</b>
<ide> </summary>
<del> <ul><li><a href="./examples/with-styled-components">Styled components</a></li><li><a href="./examples/with-styletron">Styletron</a></li><li><a href="./examples/with-glamor">Glamor</a></li><li><a href="./examples/with-cxs">Cxs</a></li><li><a href="./examples/with-aphrodite">Aphrodite</a></li><li><a href="./examples/with-fela">Fela</a></li></ul>
<add> <ul><li><a href="./examples/with-styled-components">Styled components</a></li><li><a href="./examples/with-styletron">Styletron</a></li><li><a href="./examples/with-glamor">Glamor</a></li><li><a href="./examples/with-glamorous">Glamorous</a></li><li><a href="./examples/with-cxs">Cxs</a></li><li><a href="./examples/with-aphrodite">Aphrodite</a></li><li><a href="./examples/with-fela">Fela</a></li></ul>
<ide> </details></p>
<ide>
<ide> It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles:
| 1
|
Ruby
|
Ruby
|
remove unused require
|
d985c5d23eda396bbc349f01db02d1efccf7af52
|
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> require "active_record/relation/where_clause"
<ide> require "active_record/relation/where_clause_factory"
<ide> require 'active_model/forbidden_attributes_protection'
<del>require 'active_support/core_ext/string/filters'
<ide>
<ide> module ActiveRecord
<ide> module QueryMethods
| 1
|
Java
|
Java
|
fix error when writing empty string to databuffer
|
2b65d0e51ff106270871455880e2b1cf427eea1b
|
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DataBuffer.java
<ide> default DataBuffer ensureCapacity(int capacity) {
<ide> default DataBuffer write(CharSequence charSequence, Charset charset) {
<ide> Assert.notNull(charSequence, "CharSequence must not be null");
<ide> Assert.notNull(charset, "Charset must not be null");
<del> CharsetEncoder charsetEncoder = charset.newEncoder()
<del> .onMalformedInput(CodingErrorAction.REPLACE)
<del> .onUnmappableCharacter(CodingErrorAction.REPLACE);
<del> CharBuffer inBuffer = CharBuffer.wrap(charSequence);
<del> int estimatedSize = (int) (inBuffer.remaining() * charsetEncoder.averageBytesPerChar());
<del> ByteBuffer outBuffer = ensureCapacity(estimatedSize)
<del> .asByteBuffer(writePosition(), writableByteCount());
<del> while (true) {
<del> CoderResult cr = (inBuffer.hasRemaining() ?
<del> charsetEncoder.encode(inBuffer, outBuffer, true) : CoderResult.UNDERFLOW);
<del> if (cr.isUnderflow()) {
<del> cr = charsetEncoder.flush(outBuffer);
<del> }
<del> if (cr.isUnderflow()) {
<del> break;
<del> }
<del> if (cr.isOverflow()) {
<del> writePosition(outBuffer.position());
<del> int maximumSize = (int) (inBuffer.remaining() * charsetEncoder.maxBytesPerChar());
<del> ensureCapacity(maximumSize);
<del> outBuffer = asByteBuffer(writePosition(), writableByteCount());
<add> if (charSequence.length() != 0) {
<add> CharsetEncoder charsetEncoder = charset.newEncoder()
<add> .onMalformedInput(CodingErrorAction.REPLACE)
<add> .onUnmappableCharacter(CodingErrorAction.REPLACE);
<add> CharBuffer inBuffer = CharBuffer.wrap(charSequence);
<add> int estimatedSize = (int) (inBuffer.remaining() * charsetEncoder.averageBytesPerChar());
<add> ByteBuffer outBuffer = ensureCapacity(estimatedSize)
<add> .asByteBuffer(writePosition(), writableByteCount());
<add> while (true) {
<add> CoderResult cr = (inBuffer.hasRemaining() ?
<add> charsetEncoder.encode(inBuffer, outBuffer, true) : CoderResult.UNDERFLOW);
<add> if (cr.isUnderflow()) {
<add> cr = charsetEncoder.flush(outBuffer);
<add> }
<add> if (cr.isUnderflow()) {
<add> break;
<add> }
<add> if (cr.isOverflow()) {
<add> writePosition(outBuffer.position());
<add> int maximumSize = (int) (inBuffer.remaining() * charsetEncoder.maxBytesPerChar());
<add> ensureCapacity(maximumSize);
<add> outBuffer = asByteBuffer(writePosition(), writableByteCount());
<add> }
<ide> }
<add> writePosition(outBuffer.position());
<ide> }
<del> writePosition(outBuffer.position());
<ide> return this;
<ide> }
<ide>
<ide><path>spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void writeNullCharset() {
<ide> }
<ide> }
<ide>
<add> @Test
<add> public void writeEmptyString() {
<add> DataBuffer buffer = createDataBuffer(1);
<add> buffer.write("", StandardCharsets.UTF_8);
<add>
<add> assertEquals(0, buffer.readableByteCount());
<add>
<add> release(buffer);
<add> }
<add>
<ide> @Test
<ide> public void writeUtf8String() {
<ide> DataBuffer buffer = createDataBuffer(6);
| 2
|
PHP
|
PHP
|
remove unused variable from the signature
|
e658e071d10daf7af8b70243bd796e643acfabb7
|
<ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> public function queryAssociation(Model $Model, &$LinkModel, $type, $association,
<ide> $this->_filterResults($fetch, $Model);
<ide> }
<ide>
<del> return $this->_mergeHasMany($resultSet, $fetch, $association, $Model, $LinkModel);
<add> return $this->_mergeHasMany($resultSet, $fetch, $association, $Model);
<ide>
<ide> } elseif ($type === 'hasAndBelongsToMany') {
<ide> $ins = $fetch = array();
<ide> public function fetchAssociated(Model $Model, $query, $ids) {
<ide> * @param array $merge Data to merge
<ide> * @param string $association Name of Model being Merged
<ide> * @param Model $Model Model being merged onto
<del> * @param Model $LinkModel Model being merged
<ide> * @return void
<ide> */
<del> protected function _mergeHasMany(&$resultSet, $merge, $association, $Model, $LinkModel) {
<add> protected function _mergeHasMany(&$resultSet, $merge, $association, $Model) {
<ide> $modelAlias = $Model->alias;
<ide> $primaryKey = $Model->primaryKey;
<ide> $foreignKey = $Model->hasMany[$association]['foreignKey'];
| 1
|
Ruby
|
Ruby
|
apply suggestions from code review
|
b2cccfcf68b131d2eab734b1e105a5b0407a06ba
|
<ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_license
<ide> if @spdx_ids.key?(formula.license)
<ide> return unless @online
<ide>
<del> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}, false)
<add> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*})
<ide> return if user.nil?
<ide>
<ide> github_license = GitHub.get_repo_license(user, repo)
<ide> def audit_license
<ide> end
<ide> end
<ide>
<del> # def get_github_repo_license_data(user, repo)
<del> # return unless @online
<del> #
<del> # begin
<del> # res = GitHub.open_api("#{GitHub::API_URL}/repos/#{user}/#{repo}/license")
<del> # return unless res.key?("license")
<del> #
<del> # res["license"]["spdx_id"] || nil
<del> # rescue GitHub::HTTPNotFoundError
<del> # nil
<del> # end
<del> # end
<del>
<ide> def audit_deps
<ide> @specs.each do |spec|
<ide> # Check for things we don't like to depend on.
<ide> def get_repo_data(regex, new_formula_only = true)
<ide> return unless @core_tap
<ide> return unless @online
<ide>
<del> return unless @new_formula || !new_formula_only
<del>
<ide> _, user, repo = *regex.match(formula.stable.url) if formula.stable
<ide> _, user, repo = *regex.match(formula.homepage) unless user
<ide> return if !user || !repo
| 1
|
Mixed
|
Javascript
|
expose keyobject class
|
f1056542f0cf2520e122d93afbaada6b6599e49b
|
<ide><path>doc/api/crypto.md
<ide> This can be called many times with new data as it is streamed.
<ide> ## Class: KeyObject
<ide> <!-- YAML
<ide> added: v11.6.0
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/26438
<add> description: This class is now exported.
<ide> -->
<ide>
<del>Node.js uses an internal `KeyObject` class which should not be accessed
<del>directly. Instead, factory functions exist to create instances of this class
<del>in a secure manner, see [`crypto.createSecretKey()`][],
<del>[`crypto.createPublicKey()`][] and [`crypto.createPrivateKey()`][]. A
<del>`KeyObject` can represent a symmetric or asymmetric key, and each kind of key
<del>exposes different functions.
<add>Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
<add>and each kind of key exposes different functions. The
<add>[`crypto.createSecretKey()`][], [`crypto.createPublicKey()`][] and
<add>[`crypto.createPrivateKey()`][] methods are used to create `KeyObject`
<add>instances. `KeyObject` objects are not to be created directly using the `new`
<add>keyword.
<ide>
<ide> Most applications should consider using the new `KeyObject` API instead of
<ide> passing keys as strings or `Buffer`s due to improved security features.
<ide><path>lib/crypto.js
<ide> const {
<ide> const {
<ide> createSecretKey,
<ide> createPublicKey,
<del> createPrivateKey
<add> createPrivateKey,
<add> KeyObject,
<ide> } = require('internal/crypto/keys');
<ide> const {
<ide> DiffieHellman,
<ide> module.exports = exports = {
<ide> ECDH,
<ide> Hash,
<ide> Hmac,
<add> KeyObject,
<ide> Sign,
<ide> Verify
<ide> };
<ide><path>lib/internal/crypto/keys.js
<ide> module.exports = {
<ide> createSecretKey,
<ide> createPublicKey,
<ide> createPrivateKey,
<add> KeyObject,
<ide>
<ide> // These are designed for internal use only and should not be exposed.
<ide> parsePublicKeyEncoding,
| 3
|
Java
|
Java
|
increase fudge factor in stopwatchtests
|
3ccbf1edeb34259751fd3e5ce80d4cd4d3e029e2
|
<ide><path>spring-core/src/test/java/org/springframework/util/StopWatchTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> class StopWatchTests {
<ide>
<ide> private static final long duration1 = 200;
<ide> private static final long duration2 = 100;
<del> private static final long fudgeFactor = 50;
<add> private static final long fudgeFactor = 100;
<ide>
<ide> private final StopWatch stopWatch = new StopWatch(ID);
<ide>
<ide> void validUsage() throws Exception {
<ide> .isLessThanOrEqualTo(duration1 + duration2 + fudgeFactor);
<ide> assertThat(stopWatch.getTotalTimeSeconds())
<ide> .as("total time in seconds for task #2")
<del> .isGreaterThanOrEqualTo((duration1 + duration2 - fudgeFactor) / 1000.0)
<add> .isGreaterThanOrEqualTo((duration1 + duration2 - fudgeFactor) / 1000.0)
<ide> .isLessThanOrEqualTo((duration1 + duration2 + fudgeFactor) / 1000.0);
<ide>
<ide> assertThat(stopWatch.getTaskCount()).isEqualTo(2);
| 1
|
Javascript
|
Javascript
|
replace suspenseconfig object with an integer
|
92fcd46cc79bbf45df4ce86b0678dcef3b91078d
|
<ide><path>packages/react-debug-tools/src/ReactDebugHooks.js
<ide> import type {
<ide> } from 'react-reconciler/src/ReactInternalTypes';
<ide> import type {OpaqueIDType} from 'react-reconciler/src/ReactFiberHostConfig';
<ide>
<del>import type {SuspenseConfig} from 'react-reconciler/src/ReactFiberSuspenseConfig';
<add>import type {SuspenseConfig} from 'react-reconciler/src/ReactFiberTransition';
<ide> import {NoMode} from 'react-reconciler/src/ReactTypeOfMode';
<ide>
<ide> import ErrorStackParser from 'error-stack-parser';
<ide><path>packages/react-dom/src/server/ReactPartialRendererHooks.js
<ide> import type {
<ide> MutableSourceSubscribeFn,
<ide> ReactContext,
<ide> } from 'shared/ReactTypes';
<del>import type {SuspenseConfig} from 'react-reconciler/src/ReactFiberSuspenseConfig';
<add>import type {SuspenseConfig} from 'react-reconciler/src/ReactFiberTransition';
<ide> import type PartialRenderer from './ReactPartialRenderer';
<ide>
<ide> import {validateContextBounds} from './ReactPartialRendererContext';
<ide><path>packages/react-reconciler/src/ReactFiberClassComponent.new.js
<ide> import {
<ide> requestUpdateLane,
<ide> scheduleUpdateOnFiber,
<ide> } from './ReactFiberWorkLoop.new';
<del>import {requestCurrentSuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import {logForceUpdateScheduled, logStateUpdateScheduled} from './DebugTracing';
<ide>
<ide> import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev';
<ide> const classComponentUpdater = {
<ide> enqueueSetState(inst, payload, callback) {
<ide> const fiber = getInstance(inst);
<ide> const eventTime = requestEventTime();
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> const update = createUpdate(eventTime, lane);
<ide> update.payload = payload;
<ide> const classComponentUpdater = {
<ide> enqueueReplaceState(inst, payload, callback) {
<ide> const fiber = getInstance(inst);
<ide> const eventTime = requestEventTime();
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> const update = createUpdate(eventTime, lane);
<ide> update.tag = ReplaceState;
<ide> const classComponentUpdater = {
<ide> enqueueForceUpdate(inst, callback) {
<ide> const fiber = getInstance(inst);
<ide> const eventTime = requestEventTime();
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> const update = createUpdate(eventTime, lane);
<ide> update.tag = ForceUpdate;
<ide><path>packages/react-reconciler/src/ReactFiberClassComponent.old.js
<ide> import {
<ide> requestUpdateLane,
<ide> scheduleUpdateOnFiber,
<ide> } from './ReactFiberWorkLoop.old';
<del>import {requestCurrentSuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import {logForceUpdateScheduled, logStateUpdateScheduled} from './DebugTracing';
<ide>
<ide> import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev';
<ide> const classComponentUpdater = {
<ide> enqueueSetState(inst, payload, callback) {
<ide> const fiber = getInstance(inst);
<ide> const eventTime = requestEventTime();
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> const update = createUpdate(eventTime, lane);
<ide> update.payload = payload;
<ide> const classComponentUpdater = {
<ide> enqueueReplaceState(inst, payload, callback) {
<ide> const fiber = getInstance(inst);
<ide> const eventTime = requestEventTime();
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> const update = createUpdate(eventTime, lane);
<ide> update.tag = ReplaceState;
<ide> const classComponentUpdater = {
<ide> enqueueForceUpdate(inst, callback) {
<ide> const fiber = getInstance(inst);
<ide> const eventTime = requestEventTime();
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> const update = createUpdate(eventTime, lane);
<ide> update.tag = ForceUpdate;
<ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js
<ide> import type {
<ide> import type {Fiber, Dispatcher} from './ReactInternalTypes';
<ide> import type {Lanes, Lane} from './ReactFiberLane';
<ide> import type {HookEffectTag} from './ReactHookEffectTags';
<del>import type {SuspenseConfig} from './ReactFiberSuspenseConfig';
<add>import type {SuspenseConfig} from './ReactFiberTransition';
<ide> import type {ReactPriorityLevel} from './ReactInternalTypes';
<ide> import type {FiberRoot} from './ReactInternalTypes';
<ide> import type {OpaqueIDType} from './ReactFiberHostConfig';
<ide> import invariant from 'shared/invariant';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import is from 'shared/objectIs';
<ide> import {markWorkInProgressReceivedUpdate} from './ReactFiberBeginWork.new';
<del>import {requestCurrentSuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import {
<ide> UserBlockingPriority,
<ide> NormalPriority,
<ide> function useMutableSource<Source, Snapshot>(
<ide> if (!is(snapshot, maybeNewSnapshot)) {
<ide> setSnapshot(maybeNewSnapshot);
<ide>
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide> markRootMutableRead(root, lane);
<ide> }
<ide> // If the source mutated between render and now,
<ide> function useMutableSource<Source, Snapshot>(
<ide> latestSetSnapshot(latestGetSnapshot(source._source));
<ide>
<ide> // Record a pending mutable source update with the same expiration time.
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> markRootMutableRead(root, lane);
<ide> } catch (error) {
<ide> function mountDeferredValue<T>(
<ide> ): T {
<ide> const [prevValue, setValue] = mountState(value);
<ide> mountEffect(() => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setValue(value);
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> }, [value, config]);
<ide> return prevValue;
<ide> function updateDeferredValue<T>(
<ide> ): T {
<ide> const [prevValue, setValue] = updateState(value);
<ide> updateEffect(() => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setValue(value);
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> }, [value, config]);
<ide> return prevValue;
<ide> function rerenderDeferredValue<T>(
<ide> ): T {
<ide> const [prevValue, setValue] = rerenderState(value);
<ide> updateEffect(() => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setValue(value);
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> }, [value, config]);
<ide> return prevValue;
<ide> function startTransition(setPending, config, callback) {
<ide> runWithPriority(
<ide> priorityLevel > NormalPriority ? NormalPriority : priorityLevel,
<ide> () => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setPending(false);
<ide> callback();
<ide> } finally {
<ide> if (decoupleUpdatePriorityFromScheduler) {
<ide> setCurrentUpdateLanePriority(previousLanePriority);
<ide> }
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> },
<ide> );
<ide> function startTransition(setPending, config, callback) {
<ide> runWithPriority(
<ide> priorityLevel > NormalPriority ? NormalPriority : priorityLevel,
<ide> () => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setPending(false);
<ide> callback();
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> },
<ide> );
<ide> function dispatchAction<S, A>(
<ide> }
<ide>
<ide> const eventTime = requestEventTime();
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> const update: Update<S, A> = {
<ide> lane,
<ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js
<ide> import type {
<ide> import type {Fiber, Dispatcher} from './ReactInternalTypes';
<ide> import type {Lanes, Lane} from './ReactFiberLane';
<ide> import type {HookEffectTag} from './ReactHookEffectTags';
<del>import type {SuspenseConfig} from './ReactFiberSuspenseConfig';
<add>import type {SuspenseConfig} from './ReactFiberTransition';
<ide> import type {ReactPriorityLevel} from './ReactInternalTypes';
<ide> import type {FiberRoot} from './ReactInternalTypes';
<ide> import type {OpaqueIDType} from './ReactFiberHostConfig';
<ide> import invariant from 'shared/invariant';
<ide> import getComponentName from 'shared/getComponentName';
<ide> import is from 'shared/objectIs';
<ide> import {markWorkInProgressReceivedUpdate} from './ReactFiberBeginWork.old';
<del>import {requestCurrentSuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import {
<ide> UserBlockingPriority,
<ide> NormalPriority,
<ide> function useMutableSource<Source, Snapshot>(
<ide> if (!is(snapshot, maybeNewSnapshot)) {
<ide> setSnapshot(maybeNewSnapshot);
<ide>
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide> markRootMutableRead(root, lane);
<ide> }
<ide> // If the source mutated between render and now,
<ide> function useMutableSource<Source, Snapshot>(
<ide> latestSetSnapshot(latestGetSnapshot(source._source));
<ide>
<ide> // Record a pending mutable source update with the same expiration time.
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> markRootMutableRead(root, lane);
<ide> } catch (error) {
<ide> function mountDeferredValue<T>(
<ide> ): T {
<ide> const [prevValue, setValue] = mountState(value);
<ide> mountEffect(() => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setValue(value);
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> }, [value, config]);
<ide> return prevValue;
<ide> function updateDeferredValue<T>(
<ide> ): T {
<ide> const [prevValue, setValue] = updateState(value);
<ide> updateEffect(() => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setValue(value);
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> }, [value, config]);
<ide> return prevValue;
<ide> function rerenderDeferredValue<T>(
<ide> ): T {
<ide> const [prevValue, setValue] = rerenderState(value);
<ide> updateEffect(() => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setValue(value);
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> }, [value, config]);
<ide> return prevValue;
<ide> function startTransition(setPending, config, callback) {
<ide> runWithPriority(
<ide> priorityLevel > NormalPriority ? NormalPriority : priorityLevel,
<ide> () => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setPending(false);
<ide> callback();
<ide> } finally {
<ide> if (decoupleUpdatePriorityFromScheduler) {
<ide> setCurrentUpdateLanePriority(previousLanePriority);
<ide> }
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> },
<ide> );
<ide> function startTransition(setPending, config, callback) {
<ide> runWithPriority(
<ide> priorityLevel > NormalPriority ? NormalPriority : priorityLevel,
<ide> () => {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> setPending(false);
<ide> callback();
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> },
<ide> );
<ide> function dispatchAction<S, A>(
<ide> }
<ide>
<ide> const eventTime = requestEventTime();
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(fiber, suspenseConfig);
<add> const lane = requestUpdateLane(fiber);
<ide>
<ide> const update: Update<S, A> = {
<ide> lane,
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.new.js
<ide> import {
<ide> getCurrentUpdateLanePriority,
<ide> setCurrentUpdateLanePriority,
<ide> } from './ReactFiberLane';
<del>import {requestCurrentSuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import {
<ide> scheduleRefresh,
<ide> scheduleRoot,
<ide> export function updateContainer(
<ide> warnIfNotScopedWithMatchingAct(current);
<ide> }
<ide> }
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(current, suspenseConfig);
<add> const lane = requestUpdateLane(current);
<ide>
<ide> if (enableSchedulingProfiler) {
<ide> markRenderScheduled(lane);
<ide> export function attemptHydrationAtCurrentPriority(fiber: Fiber): void {
<ide> return;
<ide> }
<ide> const eventTime = requestEventTime();
<del> const lane = requestUpdateLane(fiber, null);
<add> const lane = requestUpdateLane(fiber);
<ide> scheduleUpdateOnFiber(fiber, lane, eventTime);
<ide> markRetryLaneIfNotHydrated(fiber, lane);
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.old.js
<ide> import {
<ide> getCurrentUpdateLanePriority,
<ide> setCurrentUpdateLanePriority,
<ide> } from './ReactFiberLane';
<del>import {requestCurrentSuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import {
<ide> scheduleRefresh,
<ide> scheduleRoot,
<ide> export function updateContainer(
<ide> warnIfNotScopedWithMatchingAct(current);
<ide> }
<ide> }
<del> const suspenseConfig = requestCurrentSuspenseConfig();
<del> const lane = requestUpdateLane(current, suspenseConfig);
<add> const lane = requestUpdateLane(current);
<ide>
<ide> if (enableSchedulingProfiler) {
<ide> markRenderScheduled(lane);
<ide> export function attemptHydrationAtCurrentPriority(fiber: Fiber): void {
<ide> return;
<ide> }
<ide> const eventTime = requestEventTime();
<del> const lane = requestUpdateLane(fiber, null);
<add> const lane = requestUpdateLane(fiber);
<ide> scheduleUpdateOnFiber(fiber, lane, eventTime);
<ide> markRetryLaneIfNotHydrated(fiber, lane);
<ide> }
<add><path>packages/react-reconciler/src/ReactFiberTransition.js
<del><path>packages/react-reconciler/src/ReactFiberSuspenseConfig.js
<ide>
<ide> import ReactSharedInternals from 'shared/ReactSharedInternals';
<ide>
<del>const {ReactCurrentBatchConfig} = ReactSharedInternals;
<del>
<add>// Deprecated
<ide> export type SuspenseConfig = {|
<ide> timeoutMs: number,
<ide> busyDelayMs?: number,
<ide> busyMinDurationMs?: number,
<ide> |};
<ide>
<add>// Deprecated
<ide> export type TimeoutConfig = {|
<ide> timeoutMs: number,
<ide> |};
<ide>
<del>export function requestCurrentSuspenseConfig(): null | SuspenseConfig {
<del> return ReactCurrentBatchConfig.suspense;
<add>const {ReactCurrentBatchConfig} = ReactSharedInternals;
<add>
<add>export const NoTransition = 0;
<add>
<add>export function requestCurrentTransition(): number {
<add> return ReactCurrentBatchConfig.transition;
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import type {Fiber, FiberRoot} from './ReactInternalTypes';
<ide> import type {Lanes, Lane} from './ReactFiberLane';
<ide> import type {ReactPriorityLevel} from './ReactInternalTypes';
<ide> import type {Interaction} from 'scheduler/src/Tracing';
<del>import type {SuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.new';
<ide> import type {StackCursor} from './ReactFiberStack.new';
<ide> import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new';
<ide> import {
<ide> schedulerPriorityToLanePriority,
<ide> lanePriorityToSchedulerPriority,
<ide> } from './ReactFiberLane';
<add>import {requestCurrentTransition, NoTransition} from './ReactFiberTransition';
<ide> import {beginWork as originalBeginWork} from './ReactFiberBeginWork.new';
<ide> import {completeWork} from './ReactFiberCompleteWork.new';
<ide> import {unwindWork, unwindInterruptedWork} from './ReactFiberUnwindWork.new';
<ide> export function getCurrentTime() {
<ide> return now();
<ide> }
<ide>
<del>export function requestUpdateLane(
<del> fiber: Fiber,
<del> suspenseConfig: SuspenseConfig | null,
<del>): Lane {
<add>export function requestUpdateLane(fiber: Fiber): Lane {
<ide> // Special cases
<ide> const mode = fiber.mode;
<ide> if ((mode & BlockingMode) === NoMode) {
<ide> export function requestUpdateLane(
<ide> currentEventWipLanes = workInProgressRootIncludedLanes;
<ide> }
<ide>
<del> if (suspenseConfig !== null) {
<del> // Use the size of the timeout as a heuristic to prioritize shorter
<del> // transitions over longer ones.
<del> // TODO: This will coerce numbers larger than 31 bits to 0.
<add> const isTransition = requestCurrentTransition() !== NoTransition;
<add> if (isTransition) {
<ide> if (currentEventPendingLanes !== NoLanes) {
<ide> currentEventPendingLanes =
<ide> mostRecentlyUpdatedRoot !== null
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import type {Fiber, FiberRoot} from './ReactInternalTypes';
<ide> import type {Lanes, Lane} from './ReactFiberLane';
<ide> import type {ReactPriorityLevel} from './ReactInternalTypes';
<ide> import type {Interaction} from 'scheduler/src/Tracing';
<del>import type {SuspenseConfig} from './ReactFiberSuspenseConfig';
<ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.old';
<ide> import type {Effect as HookEffect} from './ReactFiberHooks.old';
<ide> import type {StackCursor} from './ReactFiberStack.old';
<ide> import {
<ide> schedulerPriorityToLanePriority,
<ide> lanePriorityToSchedulerPriority,
<ide> } from './ReactFiberLane';
<add>import {requestCurrentTransition, NoTransition} from './ReactFiberTransition';
<ide> import {beginWork as originalBeginWork} from './ReactFiberBeginWork.old';
<ide> import {completeWork} from './ReactFiberCompleteWork.old';
<ide> import {unwindWork, unwindInterruptedWork} from './ReactFiberUnwindWork.old';
<ide> export function getCurrentTime() {
<ide> return now();
<ide> }
<ide>
<del>export function requestUpdateLane(
<del> fiber: Fiber,
<del> suspenseConfig: SuspenseConfig | null,
<del>): Lane {
<add>export function requestUpdateLane(fiber: Fiber): Lane {
<ide> // Special cases
<ide> const mode = fiber.mode;
<ide> if ((mode & BlockingMode) === NoMode) {
<ide> export function requestUpdateLane(
<ide> currentEventWipLanes = workInProgressRootIncludedLanes;
<ide> }
<ide>
<del> if (suspenseConfig !== null) {
<del> // Use the size of the timeout as a heuristic to prioritize shorter
<del> // transitions over longer ones.
<del> // TODO: This will coerce numbers larger than 31 bits to 0.
<add> const isTransition = requestCurrentTransition() !== NoTransition;
<add> if (isTransition) {
<ide> if (currentEventPendingLanes !== NoLanes) {
<ide> currentEventPendingLanes =
<ide> mostRecentlyUpdatedRoot !== null
<ide><path>packages/react-reconciler/src/ReactInternalTypes.js
<ide> import type {RootTag} from './ReactRootTags';
<ide> import type {TimeoutHandle, NoTimeout} from './ReactFiberHostConfig';
<ide> import type {Wakeable} from 'shared/ReactTypes';
<ide> import type {Interaction} from 'scheduler/src/Tracing';
<del>import type {SuspenseConfig, TimeoutConfig} from './ReactFiberSuspenseConfig';
<add>import type {SuspenseConfig, TimeoutConfig} from './ReactFiberTransition';
<ide>
<ide> export type ReactPriorityLevel = 99 | 98 | 97 | 96 | 95 | 90;
<ide>
<ide><path>packages/react/src/ReactBatchConfig.js
<ide> * @flow
<ide> */
<ide>
<del>import type {SuspenseConfig} from 'react-reconciler/src/ReactFiberSuspenseConfig';
<add>import type {SuspenseConfig} from 'react-reconciler/src/ReactFiberTransition';
<ide>
<ide> import ReactCurrentBatchConfig from './ReactCurrentBatchConfig';
<ide>
<del>// Within the scope of the callback, mark all updates as being allowed to suspend.
<add>// This is a copy of startTransition, except if null or undefined is passed,
<add>// then updates inside the scope are opted-out of the outer transition scope.
<add>// TODO: Deprecated. Remove in favor of startTransition. Figure out how scopes
<add>// should nest, and whether we need an API to opt-out nested scopes.
<ide> export function withSuspenseConfig(scope: () => void, config?: SuspenseConfig) {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = config === undefined ? null : config;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition =
<add> config === undefined || config === null ? 0 : 1;
<ide> try {
<ide> scope();
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> }
<ide><path>packages/react/src/ReactCurrentBatchConfig.js
<ide> * @flow
<ide> */
<ide>
<del>import type {SuspenseConfig} from 'react-reconciler/src/ReactFiberSuspenseConfig';
<del>
<ide> /**
<ide> * Keeps track of the current batch's configuration such as how long an update
<ide> * should suspend for if it needs to.
<ide> */
<ide> const ReactCurrentBatchConfig = {
<del> suspense: (null: null | SuspenseConfig),
<add> transition: (0: number),
<ide> };
<ide>
<ide> export default ReactCurrentBatchConfig;
<ide><path>packages/react/src/ReactStartTransition.js
<ide>
<ide> import ReactCurrentBatchConfig from './ReactCurrentBatchConfig';
<ide>
<del>// Default to an arbitrarily large timeout. Effectively, this is infinite. The
<del>// eventual goal is to never timeout when refreshing already visible content.
<del>const IndefiniteTimeoutConfig = {timeoutMs: 100000};
<del>
<ide> export function startTransition(scope: () => void) {
<del> const previousConfig = ReactCurrentBatchConfig.suspense;
<del> ReactCurrentBatchConfig.suspense = IndefiniteTimeoutConfig;
<add> const prevTransition = ReactCurrentBatchConfig.transition;
<add> ReactCurrentBatchConfig.transition = 1;
<ide> try {
<ide> scope();
<ide> } finally {
<del> ReactCurrentBatchConfig.suspense = previousConfig;
<add> ReactCurrentBatchConfig.transition = prevTransition;
<ide> }
<ide> }
| 15
|
PHP
|
PHP
|
allow redirectpath for consistency
|
63a534a31129be4cec4f5a694342d7020e2d7f07
|
<ide><path>src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php
<ide> public function getLogout()
<ide> */
<ide> public function redirectPath()
<ide> {
<add> if (property_exists($this, 'redirectPath'))
<add> {
<add> return $this->redirectPath;
<add> }
<add>
<ide> return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
<ide> }
<ide>
| 1
|
PHP
|
PHP
|
use array_fill_keys instead of a manual loop
|
902f3ebd5ba9fc3690c8d5744c03708677a4bf2c
|
<ide><path>Cake/Model/Behavior/TimestampBehavior.php
<ide> public function handleEvent(Event $event, Entity $entity) {
<ide> * @return array
<ide> */
<ide> public function implementedEvents() {
<del> $events = array_flip(array_keys($this->_settings['events']));
<del> foreach ($events as &$method) {
<del> $method = 'handleEvent';
<del> }
<del> return $events;
<add> return array_fill_keys(array_keys($this->_settings['events']), 'handleEvent');
<ide> }
<ide>
<ide> /**
| 1
|
Text
|
Text
|
add mozilla code of conduct file
|
800de61422791dd6c263b2c2f56ea7c4506fe6da
|
<ide><path>CODE_OF_CONDUCT.md
<add># Community Participation Guidelines
<add>
<add>This repository is governed by Mozilla's code of conduct and etiquette guidelines.
<add>For more details, please read the
<add>[Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/).
<add>
<add>## How to Report
<add>For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page.
<add>
<add><!--
<add>## Project Specific Etiquette
<add>
<add>In some cases, there will be additional project etiquette i.e.: (https://bugzilla.mozilla.org/page.cgi?id=etiquette.html).
<add>Please update for your project.
<add>-->
| 1
|
Javascript
|
Javascript
|
remove usage of legacy context api in modal
|
29f0cedc0ad2a52b73f580cfb31dcb1efefefa85
|
<ide><path>Libraries/Modal/Modal.js
<ide> 'use strict';
<ide>
<ide> const AppContainer = require('../ReactNative/AppContainer');
<add>const {RootTagContext} = require('../ReactNative/RootTag');
<ide> const I18nManager = require('../ReactNative/I18nManager');
<del>const PropTypes = require('prop-types');
<ide> const React = require('react');
<ide> const ScrollView = require('../Components/ScrollView/ScrollView');
<ide> const StyleSheet = require('../StyleSheet/StyleSheet');
<ide> const View = require('../Components/View/View');
<ide>
<add>import type {RootTag} from '../ReactNative/RootTag';
<ide> import type {ViewProps} from '../Components/View/ViewPropTypes';
<ide> import type {DirectEventHandler} from '../Types/CodegenTypes';
<ide> import type EmitterSubscription from '../vendor/emitter/EmitterSubscription';
<ide> class Modal extends React.Component<Props> {
<ide> hardwareAccelerated: false,
<ide> };
<ide>
<del> static contextTypes: any | {|rootTag: React$PropType$Primitive<number>|} = {
<del> rootTag: PropTypes.number,
<del> };
<add> static contextType: React.Context<RootTag> = RootTagContext;
<ide>
<ide> _identifier: number;
<ide> _eventSubscription: ?EmitterSubscription;
<ide> class Modal extends React.Component<Props> {
<ide> }
<ide>
<ide> const innerChildren = __DEV__ ? (
<del> <AppContainer rootTag={this.context.rootTag}>
<del> {this.props.children}
<del> </AppContainer>
<add> <AppContainer rootTag={this.context}>{this.props.children}</AppContainer>
<ide> ) : (
<ide> this.props.children
<ide> );
| 1
|
Ruby
|
Ruby
|
use consistent keys between cache get / set
|
81fb5317dcdec7a9279c1004f3da3204b6c59c76
|
<ide><path>activerecord/lib/active_record/associations.rb
<ide> def association(name) #:nodoc:
<ide> private
<ide> # Returns the specified association instance if it responds to :loaded?, nil otherwise.
<ide> def association_instance_get(name)
<del> @association_cache[name.to_sym]
<add> @association_cache[name]
<ide> end
<ide>
<ide> # Set the specified association instance.
| 1
|
Go
|
Go
|
fix various problems with iptables.exists
|
3559b4177e611920d87c4dae607c641efb645783
|
<ide><path>daemon/networkdriver/bridge/driver.go
<ide> func setupIPTables(addr net.Addr, icc, ipmasq bool) error {
<ide> // Enable NAT
<ide>
<ide> if ipmasq {
<del> natArgs := []string{"POSTROUTING", "-t", "nat", "-s", addr.String(), "!", "-o", bridgeIface, "-j", "MASQUERADE"}
<add> natArgs := []string{"-s", addr.String(), "!", "-o", bridgeIface, "-j", "MASQUERADE"}
<ide>
<del> if !iptables.Exists(natArgs...) {
<del> if output, err := iptables.Raw(append([]string{"-I"}, natArgs...)...); err != nil {
<add> if !iptables.Exists(iptables.Nat, "POSTROUTING", natArgs...) {
<add> if output, err := iptables.Raw(append([]string{
<add> "-t", string(iptables.Nat), "-I", "POSTROUTING"}, natArgs...)...); err != nil {
<ide> return fmt.Errorf("Unable to enable network bridge NAT: %s", err)
<ide> } else if len(output) != 0 {
<ide> return &iptables.ChainError{Chain: "POSTROUTING", Output: output}
<ide> func setupIPTables(addr net.Addr, icc, ipmasq bool) error {
<ide> }
<ide>
<ide> var (
<del> args = []string{"FORWARD", "-i", bridgeIface, "-o", bridgeIface, "-j"}
<add> args = []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
<ide> acceptArgs = append(args, "ACCEPT")
<ide> dropArgs = append(args, "DROP")
<ide> )
<ide>
<ide> if !icc {
<del> iptables.Raw(append([]string{"-D"}, acceptArgs...)...)
<add> iptables.Raw(append([]string{"-D", "FORWARD"}, acceptArgs...)...)
<ide>
<del> if !iptables.Exists(dropArgs...) {
<add> if !iptables.Exists(iptables.Filter, "FORWARD", dropArgs...) {
<ide> log.Debugf("Disable inter-container communication")
<del> if output, err := iptables.Raw(append([]string{"-I"}, dropArgs...)...); err != nil {
<add> if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, dropArgs...)...); err != nil {
<ide> return fmt.Errorf("Unable to prevent intercontainer communication: %s", err)
<ide> } else if len(output) != 0 {
<ide> return fmt.Errorf("Error disabling intercontainer communication: %s", output)
<ide> }
<ide> }
<ide> } else {
<del> iptables.Raw(append([]string{"-D"}, dropArgs...)...)
<add> iptables.Raw(append([]string{"-D", "FORWARD"}, dropArgs...)...)
<ide>
<del> if !iptables.Exists(acceptArgs...) {
<add> if !iptables.Exists(iptables.Filter, "FORWARD", acceptArgs...) {
<ide> log.Debugf("Enable inter-container communication")
<del> if output, err := iptables.Raw(append([]string{"-I"}, acceptArgs...)...); err != nil {
<add> if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, acceptArgs...)...); err != nil {
<ide> return fmt.Errorf("Unable to allow intercontainer communication: %s", err)
<ide> } else if len(output) != 0 {
<ide> return fmt.Errorf("Error enabling intercontainer communication: %s", output)
<ide> func setupIPTables(addr net.Addr, icc, ipmasq bool) error {
<ide> }
<ide>
<ide> // Accept all non-intercontainer outgoing packets
<del> outgoingArgs := []string{"FORWARD", "-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}
<del> if !iptables.Exists(outgoingArgs...) {
<del> if output, err := iptables.Raw(append([]string{"-I"}, outgoingArgs...)...); err != nil {
<add> outgoingArgs := []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}
<add> if !iptables.Exists(iptables.Filter, "FORWARD", outgoingArgs...) {
<add> if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, outgoingArgs...)...); err != nil {
<ide> return fmt.Errorf("Unable to allow outgoing packets: %s", err)
<ide> } else if len(output) != 0 {
<ide> return &iptables.ChainError{Chain: "FORWARD outgoing", Output: output}
<ide> }
<ide> }
<ide>
<ide> // Accept incoming packets for existing connections
<del> existingArgs := []string{"FORWARD", "-o", bridgeIface, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}
<add> existingArgs := []string{"-o", bridgeIface, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}
<ide>
<del> if !iptables.Exists(existingArgs...) {
<del> if output, err := iptables.Raw(append([]string{"-I"}, existingArgs...)...); err != nil {
<add> if !iptables.Exists(iptables.Filter, "FORWARD", existingArgs...) {
<add> if output, err := iptables.Raw(append([]string{"-I", "FORWARD"}, existingArgs...)...); err != nil {
<ide> return fmt.Errorf("Unable to allow incoming packets: %s", err)
<ide> } else if len(output) != 0 {
<ide> return &iptables.ChainError{Chain: "FORWARD incoming", Output: output}
<ide><path>integration-cli/docker_cli_links_test.go
<ide> func TestLinksIpTablesRulesWhenLinkAndUnlink(t *testing.T) {
<ide> childIP := findContainerIP(t, "child")
<ide> parentIP := findContainerIP(t, "parent")
<ide>
<del> sourceRule := []string{"DOCKER", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"}
<del> destinationRule := []string{"DOCKER", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"}
<del> if !iptables.Exists(sourceRule...) || !iptables.Exists(destinationRule...) {
<add> sourceRule := []string{"-i", "docker0", "-o", "docker0", "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"}
<add> destinationRule := []string{"-i", "docker0", "-o", "docker0", "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"}
<add> if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) {
<ide> t.Fatal("Iptables rules not found")
<ide> }
<ide>
<ide> dockerCmd(t, "rm", "--link", "parent/http")
<del> if iptables.Exists(sourceRule...) || iptables.Exists(destinationRule...) {
<add> if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) {
<ide> t.Fatal("Iptables rules should be removed when unlink")
<ide> }
<ide>
<ide><path>pkg/iptables/iptables.go
<ide> const (
<ide> Insert Action = "-I"
<ide> Nat Table = "nat"
<ide> Filter Table = "filter"
<add> Mangle Table = "mangle"
<ide> )
<ide>
<ide> var (
<ide> func NewChain(name, bridge string, table Table) (*Chain, error) {
<ide> preroute := []string{
<ide> "-m", "addrtype",
<ide> "--dst-type", "LOCAL"}
<del> if !Exists(preroute...) {
<add> if !Exists(Nat, "PREROUTING", preroute...) {
<ide> if err := c.Prerouting(Append, preroute...); err != nil {
<ide> return nil, fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err)
<ide> }
<ide> func NewChain(name, bridge string, table Table) (*Chain, error) {
<ide> "-m", "addrtype",
<ide> "--dst-type", "LOCAL",
<ide> "!", "--dst", "127.0.0.0/8"}
<del> if !Exists(output...) {
<add> if !Exists(Nat, "OUTPUT", output...) {
<ide> if err := c.Output(Append, output...); err != nil {
<ide> return nil, fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
<ide> }
<ide> }
<ide> case Filter:
<del> link := []string{"FORWARD",
<add> link := []string{
<ide> "-o", c.Bridge,
<ide> "-j", c.Name}
<del> if !Exists(link...) {
<del> insert := append([]string{string(Insert)}, link...)
<add> if !Exists(Filter, "FORWARD", link...) {
<add> insert := append([]string{string(Insert), "FORWARD"}, link...)
<ide> if output, err := Raw(insert...); err != nil {
<ide> return nil, err
<ide> } else if len(output) != 0 {
<ide> func (c *Chain) Remove() error {
<ide> }
<ide>
<ide> // Check if a rule exists
<del>func Exists(args ...string) bool {
<add>func Exists(table Table, chain string, rule ...string) bool {
<add> if string(table) == "" {
<add> table = Filter
<add> }
<add>
<ide> // iptables -C, --check option was added in v.1.4.11
<ide> // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
<ide>
<ide> // try -C
<ide> // if exit status is 0 then return true, the rule exists
<del> if _, err := Raw(append([]string{"-C"}, args...)...); err == nil {
<add> if _, err := Raw(append([]string{
<add> "-t", string(table), "-C", chain}, rule...)...); err == nil {
<ide> return true
<ide> }
<ide>
<del> // parse iptables-save for the rule
<del> rule := strings.Replace(strings.Join(args, " "), "-t nat ", "", -1)
<del> existingRules, _ := exec.Command("iptables-save").Output()
<add> // parse "iptables -S" for the rule (this checks rules in a specific chain
<add> // in a specific table)
<add> rule_string := strings.Join(rule, " ")
<add> existingRules, _ := exec.Command("iptables", "-t", string(table), "-S", chain).Output()
<ide>
<ide> // regex to replace ips in rule
<ide> // because MASQUERADE rule will not be exactly what was passed
<ide> re := regexp.MustCompile(`[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}`)
<ide>
<ide> return strings.Contains(
<ide> re.ReplaceAllString(string(existingRules), "?"),
<del> re.ReplaceAllString(rule, "?"),
<add> re.ReplaceAllString(rule_string, "?"),
<ide> )
<ide> }
<ide>
<ide><path>pkg/iptables/iptables_test.go
<ide> func TestForward(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> dnatRule := []string{natChain.Name,
<del> "-t", string(natChain.Table),
<add> dnatRule := []string{
<ide> "!", "-i", filterChain.Bridge,
<ide> "-d", ip.String(),
<ide> "-p", proto,
<ide> func TestForward(t *testing.T) {
<ide> "--to-destination", dstAddr + ":" + strconv.Itoa(dstPort),
<ide> }
<ide>
<del> if !Exists(dnatRule...) {
<add> if !Exists(natChain.Table, natChain.Name, dnatRule...) {
<ide> t.Fatalf("DNAT rule does not exist")
<ide> }
<ide>
<del> filterRule := []string{filterChain.Name,
<del> "-t", string(filterChain.Table),
<add> filterRule := []string{
<ide> "!", "-i", filterChain.Bridge,
<ide> "-o", filterChain.Bridge,
<ide> "-d", dstAddr,
<ide> func TestForward(t *testing.T) {
<ide> "-j", "ACCEPT",
<ide> }
<ide>
<del> if !Exists(filterRule...) {
<add> if !Exists(filterChain.Table, filterChain.Name, filterRule...) {
<ide> t.Fatalf("filter rule does not exist")
<ide> }
<ide>
<del> masqRule := []string{"POSTROUTING",
<del> "-t", string(natChain.Table),
<add> masqRule := []string{
<ide> "-d", dstAddr,
<ide> "-s", dstAddr,
<ide> "-p", proto,
<ide> "--dport", strconv.Itoa(dstPort),
<ide> "-j", "MASQUERADE",
<ide> }
<ide>
<del> if !Exists(masqRule...) {
<add> if !Exists(natChain.Table, "POSTROUTING", masqRule...) {
<ide> t.Fatalf("MASQUERADE rule does not exist")
<ide> }
<ide> }
<ide> func TestLink(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> rule1 := []string{filterChain.Name,
<del> "-t", string(filterChain.Table),
<add> rule1 := []string{
<ide> "-i", filterChain.Bridge,
<ide> "-o", filterChain.Bridge,
<ide> "-p", proto,
<ide> func TestLink(t *testing.T) {
<ide> "--dport", strconv.Itoa(port),
<ide> "-j", "ACCEPT"}
<ide>
<del> if !Exists(rule1...) {
<add> if !Exists(filterChain.Table, filterChain.Name, rule1...) {
<ide> t.Fatalf("rule1 does not exist")
<ide> }
<ide>
<del> rule2 := []string{filterChain.Name,
<del> "-t", string(filterChain.Table),
<add> rule2 := []string{
<ide> "-i", filterChain.Bridge,
<ide> "-o", filterChain.Bridge,
<ide> "-p", proto,
<ide> func TestLink(t *testing.T) {
<ide> "--sport", strconv.Itoa(port),
<ide> "-j", "ACCEPT"}
<ide>
<del> if !Exists(rule2...) {
<add> if !Exists(filterChain.Table, filterChain.Name, rule2...) {
<ide> t.Fatalf("rule2 does not exist")
<ide> }
<ide> }
<ide> func TestPrerouting(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> rule := []string{"PREROUTING",
<del> "-t", string(Nat),
<add> rule := []string{
<ide> "-j", natChain.Name}
<ide>
<ide> rule = append(rule, args...)
<ide>
<del> if !Exists(rule...) {
<add> if !Exists(natChain.Table, "PREROUTING", rule...) {
<ide> t.Fatalf("rule does not exist")
<ide> }
<ide>
<del> delRule := append([]string{"-D"}, rule...)
<add> delRule := append([]string{"-D", "PREROUTING", "-t", string(Nat)}, rule...)
<ide> if _, err = Raw(delRule...); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestOutput(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> rule := []string{"OUTPUT",
<del> "-t", string(natChain.Table),
<add> rule := []string{
<ide> "-j", natChain.Name}
<ide>
<ide> rule = append(rule, args...)
<ide>
<del> if !Exists(rule...) {
<add> if !Exists(natChain.Table, "OUTPUT", rule...) {
<ide> t.Fatalf("rule does not exist")
<ide> }
<ide>
<del> delRule := append([]string{"-D"}, rule...)
<add> delRule := append([]string{"-D", "OUTPUT", "-t",
<add> string(natChain.Table)}, rule...)
<ide> if _, err = Raw(delRule...); err != nil {
<ide> t.Fatal(err)
<ide> }
| 4
|
Go
|
Go
|
use getresourcepath instead
|
63708dca8a633d68f9342eebd4f7a616e8c48234
|
<ide><path>daemon/volumes.go
<ide> func (container *Container) parseVolumeMountConfig() (map[string]*Mount, error)
<ide> if _, exists := container.Volumes[path]; exists {
<ide> continue
<ide> }
<del> realpath, err := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, path), container.basefs)
<add> realPath, err := container.getResourcePath(path)
<ide> if err != nil {
<ide> return nil, fmt.Errorf("failed to evaluate the absolute path of symlink")
<ide> }
<del> if stat, err := os.Stat(realpath); err == nil {
<add> if stat, err := os.Stat(realPath); err == nil {
<ide> if !stat.IsDir() {
<del> return nil, fmt.Errorf("file exists at %s, can't create volume there", realpath)
<add> return nil, fmt.Errorf("file exists at %s, can't create volume there", realPath)
<ide> }
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestRunWithVolumesFromExited(t *testing.T) {
<ide> logDone("run - regression test for #4979 - volumes-from on exited container")
<ide> }
<ide>
<del>// Test create volume in a dirctory which is a symbolic link
<add>// Volume path is a symlink which also exists on the host, and the host side is a file not a dir
<add>// But the volume call is just a normal volume, not a bind mount
<ide> func TestRunCreateVolumesInSymlinkDir(t *testing.T) {
<add> testRequires(t, SameHostDaemon)
<add> testRequires(t, NativeExecDriver)
<ide> defer deleteAllContainers()
<del> // This test has to create a file on host
<del> hostFile := "/tmp/abcd"
<del> cmd := exec.Command("touch", hostFile)
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> t.Fatalf("failed to create file %s on host: %v, output: %q", hostFile, err, out)
<del> }
<del> defer func() {
<del> cmd := exec.Command("rm", "-f", hostFile)
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> t.Fatalf("failed to remove file %s on host: %v, output: %q", hostFile, err, out)
<del> }
<del> }()
<del> // create symlink directory /home/test link to /tmp
<del> cmd = exec.Command(dockerBinary, "run", "--name=test", "busybox", "ln", "-s", "/tmp", "/home/test")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> t.Fatalf("failed to run container: %v, output: %q", err, out)
<add> name := "test-volume-symlink"
<add>
<add> dir, err := ioutil.TempDir("", name)
<add> if err != nil {
<add> t.Fatal(err)
<ide> }
<del> cmd = exec.Command(dockerBinary, "commit", "test", "busybox:test")
<del> out, _, err := runCommandWithOutput(cmd)
<add> defer os.RemoveAll(dir)
<add>
<add> f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
<ide> if err != nil {
<del> t.Fatalf("failed to commit container: %v, output: %q", err, out)
<add> t.Fatal(err)
<ide> }
<del> cleanedImageID := stripTrailingCharacters(out)
<del> defer deleteImages(cleanedImageID)
<del> // directory /home/test is link to /tmp, /home/test/abcd==/tmp/abcd
<del> cmd = exec.Command(dockerBinary, "run", "-v", "/home/test/abcd", "busybox", "touch", "/home/test/abcd/Hello")
<del> if out, _, err = runCommandWithOutput(cmd); err != nil {
<del> t.Fatalf("failed to create volume in symlink directory: %v, output %q", err, out)
<add> f.Close()
<add>
<add> dockerFile := fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
<add> if _, err := buildImage(name, dockerFile, false); err != nil {
<add> t.Fatal(err)
<add> }
<add> defer deleteImages(name)
<add>
<add> if out, _, err := dockerCmd(t, "run", "-v", "/test/test", name); err != nil {
<add> t.Fatal(err, out)
<ide> }
<ide>
<ide> logDone("run - create volume in symlink directory")
| 2
|
Go
|
Go
|
add context to various methods
|
def549c8f6716507ee9175fe9d798a42df89e27d
|
<ide><path>api/server/router/container/backend.go
<ide> type copyBackend interface {
<ide>
<ide> // stateBackend includes functions to implement to provide container state lifecycle functionality.
<ide> type stateBackend interface {
<del> ContainerCreate(config types.ContainerCreateConfig) (container.CreateResponse, error)
<add> ContainerCreate(ctx context.Context, config types.ContainerCreateConfig) (container.CreateResponse, error)
<ide> ContainerKill(name string, signal string) error
<ide> ContainerPause(name string) error
<ide> ContainerRename(oldName, newName string) error
<ide> ContainerResize(name string, height, width int) error
<ide> ContainerRestart(ctx context.Context, name string, options container.StopOptions) error
<ide> ContainerRm(name string, config *types.ContainerRmConfig) error
<del> ContainerStart(name string, hostConfig *container.HostConfig, checkpoint string, checkpointDir string) error
<add> ContainerStart(ctx context.Context, name string, hostConfig *container.HostConfig, checkpoint string, checkpointDir string) error
<ide> ContainerStop(ctx context.Context, name string, options container.StopOptions) error
<ide> ContainerUnpause(name string) error
<ide> ContainerUpdate(name string, hostConfig *container.HostConfig) (container.ContainerUpdateOKBody, error)
<ide> type monitorBackend interface {
<ide> ContainerStats(ctx context.Context, name string, config *backend.ContainerStatsConfig) error
<ide> ContainerTop(name string, psArgs string) (*container.ContainerTopOKBody, error)
<ide>
<del> Containers(config *types.ContainerListOptions) ([]*types.Container, error)
<add> Containers(ctx context.Context, config *types.ContainerListOptions) ([]*types.Container, error)
<ide> }
<ide>
<ide> // attachBackend includes function to implement to provide container attaching functionality.
<ide> type systemBackend interface {
<ide> }
<ide>
<ide> type commitBackend interface {
<del> CreateImageFromContainer(name string, config *backend.CreateImageConfig) (imageID string, err error)
<add> CreateImageFromContainer(ctx context.Context, name string, config *backend.CreateImageConfig) (imageID string, err error)
<ide> }
<ide>
<ide> // Backend is all the methods that need to be implemented to provide container specific functionality.
<ide><path>api/server/router/container/container_routes.go
<ide> func (s *containerRouter) postCommit(ctx context.Context, w http.ResponseWriter,
<ide> Changes: r.Form["changes"],
<ide> }
<ide>
<del> imgID, err := s.backend.CreateImageFromContainer(r.Form.Get("container"), commitCfg)
<add> imgID, err := s.backend.CreateImageFromContainer(ctx, r.Form.Get("container"), commitCfg)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (s *containerRouter) getContainersJSON(ctx context.Context, w http.Response
<ide> config.Limit = limit
<ide> }
<ide>
<del> containers, err := s.backend.Containers(config)
<add> containers, err := s.backend.Containers(ctx, config)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (s *containerRouter) postContainersStart(ctx context.Context, w http.Respon
<ide>
<ide> checkpoint := r.Form.Get("checkpoint")
<ide> checkpointDir := r.Form.Get("checkpoint-dir")
<del> if err := s.backend.ContainerStart(vars["name"], hostConfig, checkpoint, checkpointDir); err != nil {
<add> if err := s.backend.ContainerStart(ctx, vars["name"], hostConfig, checkpoint, checkpointDir); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (s *containerRouter) postContainersCreate(ctx context.Context, w http.Respo
<ide> hostConfig.PidsLimit = nil
<ide> }
<ide>
<del> ccr, err := s.backend.ContainerCreate(types.ContainerCreateConfig{
<add> ccr, err := s.backend.ContainerCreate(ctx, types.ContainerCreateConfig{
<ide> Name: name,
<ide> Config: config,
<ide> HostConfig: hostConfig,
<ide><path>api/server/router/image/backend.go
<ide> type imageBackend interface {
<ide>
<ide> type importExportBackend interface {
<ide> LoadImage(ctx context.Context, inTar io.ReadCloser, outStream io.Writer, quiet bool) error
<del> ImportImage(src string, repository string, platform *specs.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error
<add> ImportImage(ctx context.Context, src string, repository string, platform *specs.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error
<ide> ExportImage(ctx context.Context, names []string, outStream io.Writer) error
<ide> }
<ide>
<ide><path>api/server/router/image/image_routes.go
<ide> func (ir *imageRouter) postImagesCreate(ctx context.Context, w http.ResponseWrit
<ide> progressErr = ir.backend.PullImage(ctx, img, tag, platform, metaHeaders, authConfig, output)
<ide> } else { // import
<ide> src := r.Form.Get("fromSrc")
<del> progressErr = ir.backend.ImportImage(src, repo, platform, tag, message, r.Body, output, r.Form["changes"])
<add> progressErr = ir.backend.ImportImage(ctx, src, repo, platform, tag, message, r.Body, output, r.Form["changes"])
<ide> }
<ide> if progressErr != nil {
<ide> if !output.Flushed() {
<ide><path>api/server/router/swarm/backend.go
<ide> import (
<ide> type Backend interface {
<ide> Init(req types.InitRequest) (string, error)
<ide> Join(req types.JoinRequest) error
<del> Leave(force bool) error
<add> Leave(ctx context.Context, force bool) error
<ide> Inspect() (types.Swarm, error)
<ide> Update(uint64, types.Spec, types.UpdateFlags) error
<ide> GetUnlockKey() (string, error)
<ide><path>api/server/router/swarm/cluster_routes.go
<ide> func (sr *swarmRouter) leaveCluster(ctx context.Context, w http.ResponseWriter,
<ide> }
<ide>
<ide> force := httputils.BoolValue(r, "force")
<del> return sr.backend.Leave(force)
<add> return sr.backend.Leave(ctx, force)
<ide> }
<ide>
<ide> func (sr *swarmRouter) inspectCluster(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>builder/builder.go
<ide> type ExecBackend interface {
<ide> // ContainerAttachRaw attaches to container.
<ide> ContainerAttachRaw(cID string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool, attached chan struct{}) error
<ide> // ContainerCreateIgnoreImagesArgsEscaped creates a new Docker container and returns potential warnings
<del> ContainerCreateIgnoreImagesArgsEscaped(config types.ContainerCreateConfig) (container.CreateResponse, error)
<add> ContainerCreateIgnoreImagesArgsEscaped(ctx context.Context, config types.ContainerCreateConfig) (container.CreateResponse, error)
<ide> // ContainerRm removes a container specified by `id`.
<ide> ContainerRm(name string, config *types.ContainerRmConfig) error
<ide> // ContainerKill stops the container execution abruptly.
<ide> ContainerKill(containerID string, sig string) error
<ide> // ContainerStart starts a new container
<del> ContainerStart(containerID string, hostConfig *container.HostConfig, checkpoint string, checkpointDir string) error
<add> ContainerStart(ctx context.Context, containerID string, hostConfig *container.HostConfig, checkpoint string, checkpointDir string) error
<ide> // ContainerWait stops processing until the given container is stopped.
<ide> ContainerWait(ctx context.Context, name string, condition containerpkg.WaitCondition) (<-chan containerpkg.StateStatus, error)
<ide> }
<ide> type Result struct {
<ide> // ImageCacheBuilder represents a generator for stateful image cache.
<ide> type ImageCacheBuilder interface {
<ide> // MakeImageCache creates a stateful image cache.
<del> MakeImageCache(cacheFrom []string) ImageCache
<add> MakeImageCache(ctx context.Context, cacheFrom []string) (ImageCache, error)
<ide> }
<ide>
<ide> // ImageCache abstracts an image cache.
<ide><path>builder/dockerfile/builder.go
<ide> func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> return b.build(source, dockerfile)
<add> return b.build(ctx, source, dockerfile)
<ide> }
<ide>
<ide> // builderOptions are the dependencies required by the builder
<ide> func newBuilder(clientCtx context.Context, options builderOptions) (*Builder, er
<ide> config = new(types.ImageBuildOptions)
<ide> }
<ide>
<add> imageProber, err := newImageProber(clientCtx, options.Backend, config.CacheFrom, config.NoCache)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<ide> b := &Builder{
<ide> clientCtx: clientCtx,
<ide> options: config,
<ide> func newBuilder(clientCtx context.Context, options builderOptions) (*Builder, er
<ide> idMapping: options.IDMapping,
<ide> imageSources: newImageSources(clientCtx, options),
<ide> pathCache: options.PathCache,
<del> imageProber: newImageProber(options.Backend, config.CacheFrom, config.NoCache),
<add> imageProber: imageProber,
<ide> containerManager: newContainerManager(options.Backend),
<ide> }
<ide>
<ide> func buildLabelOptions(labels map[string]string, stages []instructions.Stage) {
<ide>
<ide> // Build runs the Dockerfile builder by parsing the Dockerfile and executing
<ide> // the instructions from the file.
<del>func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
<add>func (b *Builder) build(ctx context.Context, source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
<ide> defer b.imageSources.Unmount()
<ide>
<ide> stages, metaArgs, err := instructions.Parse(dockerfile.AST)
<ide> func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*buil
<ide> buildLabelOptions(b.options.Labels, stages)
<ide>
<ide> dockerfile.PrintWarnings(b.Stderr)
<del> dispatchState, err := b.dispatchDockerfileWithCancellation(stages, metaArgs, dockerfile.EscapeToken, source)
<add> dispatchState, err := b.dispatchDockerfileWithCancellation(ctx, stages, metaArgs, dockerfile.EscapeToken, source)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func printCommand(out io.Writer, currentCommandIndex int, totalCommands int, cmd
<ide> return currentCommandIndex + 1
<ide> }
<ide>
<del>func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.Stage, metaArgs []instructions.ArgCommand, escapeToken rune, source builder.Source) (*dispatchState, error) {
<add>func (b *Builder) dispatchDockerfileWithCancellation(ctx context.Context, parseResult []instructions.Stage, metaArgs []instructions.ArgCommand, escapeToken rune, source builder.Source) (*dispatchState, error) {
<ide> dispatchRequest := dispatchRequest{}
<ide> buildArgs := NewBuildArgs(b.options.BuildArgs)
<ide> totalCommands := len(metaArgs) + len(parseResult)
<ide> func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.
<ide> dispatchRequest = newDispatchRequest(b, escapeToken, source, buildArgs, stagesResults)
<ide>
<ide> currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, stage.SourceCode)
<del> if err := initializeStage(dispatchRequest, &stage); err != nil {
<add> if err := initializeStage(ctx, dispatchRequest, &stage); err != nil {
<ide> return nil, err
<ide> }
<ide> dispatchRequest.state.updateRunConfig()
<ide> func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.
<ide>
<ide> currentCommandIndex = printCommand(b.Stdout, currentCommandIndex, totalCommands, cmd)
<ide>
<del> if err := dispatch(dispatchRequest, cmd); err != nil {
<add> if err := dispatch(ctx, dispatchRequest, cmd); err != nil {
<ide> return nil, err
<ide> }
<ide> dispatchRequest.state.updateRunConfig()
<ide> func (b *Builder) dispatchDockerfileWithCancellation(parseResult []instructions.
<ide> // coming from the query parameter of the same name.
<ide> //
<ide> // TODO: Remove?
<del>func BuildFromConfig(config *container.Config, changes []string, os string) (*container.Config, error) {
<add>func BuildFromConfig(ctx context.Context, config *container.Config, changes []string, os string) (*container.Config, error) {
<ide> if len(changes) == 0 {
<ide> return config, nil
<ide> }
<ide> func BuildFromConfig(config *container.Config, changes []string, os string) (*co
<ide> return nil, errdefs.InvalidParameter(err)
<ide> }
<ide>
<del> b, err := newBuilder(context.Background(), builderOptions{
<add> b, err := newBuilder(ctx, builderOptions{
<ide> Options: &types.ImageBuildOptions{NoCache: true},
<ide> })
<ide> if err != nil {
<ide> func BuildFromConfig(config *container.Config, changes []string, os string) (*co
<ide> dispatchRequest.state.imageID = config.Image
<ide> dispatchRequest.state.operatingSystem = os
<ide> for _, cmd := range commands {
<del> err := dispatch(dispatchRequest, cmd)
<add> err := dispatch(ctx, dispatchRequest, cmd)
<ide> if err != nil {
<ide> return nil, errdefs.InvalidParameter(err)
<ide> }
<ide><path>builder/dockerfile/containerbackend.go
<ide> func newContainerManager(docker builder.ExecBackend) *containerManager {
<ide> }
<ide>
<ide> // Create a container
<del>func (c *containerManager) Create(runConfig *container.Config, hostConfig *container.HostConfig) (container.CreateResponse, error) {
<del> container, err := c.backend.ContainerCreateIgnoreImagesArgsEscaped(types.ContainerCreateConfig{
<add>func (c *containerManager) Create(ctx context.Context, runConfig *container.Config, hostConfig *container.HostConfig) (container.CreateResponse, error) {
<add> container, err := c.backend.ContainerCreateIgnoreImagesArgsEscaped(ctx, types.ContainerCreateConfig{
<ide> Config: runConfig,
<ide> HostConfig: hostConfig,
<ide> })
<ide> func (c *containerManager) Run(ctx context.Context, cID string, stdout, stderr i
<ide> }
<ide> }()
<ide>
<del> if err := c.backend.ContainerStart(cID, nil, "", ""); err != nil {
<add> if err := c.backend.ContainerStart(ctx, cID, nil, "", ""); err != nil {
<ide> close(finished)
<ide> logCancellationError(cancelErrCh, "error from ContainerStart: "+err.Error())
<ide> return err
<ide><path>builder/dockerfile/dispatchers.go
<ide> package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<ide>
<ide> import (
<ide> "bytes"
<add> "context"
<ide> "fmt"
<ide> "runtime"
<ide> "sort"
<ide> import (
<ide> //
<ide> // Sets the environment variable foo to bar, also makes interpolation
<ide> // in the dockerfile available from the next statement on via ${foo}.
<del>func dispatchEnv(d dispatchRequest, c *instructions.EnvCommand) error {
<add>func dispatchEnv(ctx context.Context, d dispatchRequest, c *instructions.EnvCommand) error {
<ide> runConfig := d.state.runConfig
<ide> commitMessage := bytes.NewBufferString("ENV")
<ide> for _, e := range c.Env {
<ide> func dispatchEnv(d dispatchRequest, c *instructions.EnvCommand) error {
<ide> runConfig.Env = append(runConfig.Env, newVar)
<ide> }
<ide> }
<del> return d.builder.commit(d.state, commitMessage.String())
<add> return d.builder.commit(ctx, d.state, commitMessage.String())
<ide> }
<ide>
<ide> // MAINTAINER some text <maybe@an.email.address>
<ide> //
<ide> // Sets the maintainer metadata.
<del>func dispatchMaintainer(d dispatchRequest, c *instructions.MaintainerCommand) error {
<add>func dispatchMaintainer(ctx context.Context, d dispatchRequest, c *instructions.MaintainerCommand) error {
<ide> d.state.maintainer = c.Maintainer
<del> return d.builder.commit(d.state, "MAINTAINER "+c.Maintainer)
<add> return d.builder.commit(ctx, d.state, "MAINTAINER "+c.Maintainer)
<ide> }
<ide>
<ide> // LABEL some json data describing the image
<ide> //
<ide> // Sets the Label variable foo to bar,
<del>func dispatchLabel(d dispatchRequest, c *instructions.LabelCommand) error {
<add>func dispatchLabel(ctx context.Context, d dispatchRequest, c *instructions.LabelCommand) error {
<ide> if d.state.runConfig.Labels == nil {
<ide> d.state.runConfig.Labels = make(map[string]string)
<ide> }
<ide> func dispatchLabel(d dispatchRequest, c *instructions.LabelCommand) error {
<ide> d.state.runConfig.Labels[v.Key] = v.Value
<ide> commitStr += " " + v.String()
<ide> }
<del> return d.builder.commit(d.state, commitStr)
<add> return d.builder.commit(ctx, d.state, commitStr)
<ide> }
<ide>
<ide> // ADD foo /path
<ide> //
<ide> // Add the file 'foo' to '/path'. Tarball and Remote URL (http, https) handling
<ide> // exist here. If you do not wish to have this automatic handling, use COPY.
<del>func dispatchAdd(d dispatchRequest, c *instructions.AddCommand) error {
<add>func dispatchAdd(ctx context.Context, d dispatchRequest, c *instructions.AddCommand) error {
<ide> if c.Chmod != "" {
<ide> return errors.New("the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled")
<ide> }
<ide> func dispatchAdd(d dispatchRequest, c *instructions.AddCommand) error {
<ide> copyInstruction.chownStr = c.Chown
<ide> copyInstruction.allowLocalDecompression = true
<ide>
<del> return d.builder.performCopy(d, copyInstruction)
<add> return d.builder.performCopy(ctx, d, copyInstruction)
<ide> }
<ide>
<ide> // COPY foo /path
<ide> //
<ide> // Same as 'ADD' but without the tar and remote url handling.
<del>func dispatchCopy(d dispatchRequest, c *instructions.CopyCommand) error {
<add>func dispatchCopy(ctx context.Context, d dispatchRequest, c *instructions.CopyCommand) error {
<ide> if c.Chmod != "" {
<ide> return errors.New("the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled")
<ide> }
<ide> func dispatchCopy(d dispatchRequest, c *instructions.CopyCommand) error {
<ide> if c.From != "" && copyInstruction.chownStr == "" {
<ide> copyInstruction.preserveOwnership = true
<ide> }
<del> return d.builder.performCopy(d, copyInstruction)
<add> return d.builder.performCopy(ctx, d, copyInstruction)
<ide> }
<ide>
<ide> func (d *dispatchRequest) getImageMount(imageRefOrID string) (*imageMount, error) {
<ide> func (d *dispatchRequest) getImageMount(imageRefOrID string) (*imageMount, error
<ide> }
<ide>
<ide> // FROM [--platform=platform] imagename[:tag | @digest] [AS build-stage-name]
<del>func initializeStage(d dispatchRequest, cmd *instructions.Stage) error {
<del> d.builder.imageProber.Reset()
<add>func initializeStage(ctx context.Context, d dispatchRequest, cmd *instructions.Stage) error {
<add> err := d.builder.imageProber.Reset(ctx)
<add> if err != nil {
<add> return err
<add> }
<ide>
<ide> var platform *specs.Platform
<ide> if v := cmd.Platform; v != "" {
<ide> func initializeStage(d dispatchRequest, cmd *instructions.Stage) error {
<ide> if len(state.runConfig.OnBuild) > 0 {
<ide> triggers := state.runConfig.OnBuild
<ide> state.runConfig.OnBuild = nil
<del> return dispatchTriggeredOnBuild(d, triggers)
<add> return dispatchTriggeredOnBuild(ctx, d, triggers)
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func dispatchTriggeredOnBuild(d dispatchRequest, triggers []string) error {
<add>func dispatchTriggeredOnBuild(ctx context.Context, d dispatchRequest, triggers []string) error {
<ide> fmt.Fprintf(d.builder.Stdout, "# Executing %d build trigger", len(triggers))
<ide> if len(triggers) > 1 {
<ide> fmt.Fprint(d.builder.Stdout, "s")
<ide> func dispatchTriggeredOnBuild(d dispatchRequest, triggers []string) error {
<ide> }
<ide> return err
<ide> }
<del> err = dispatch(d, cmd)
<add> err = dispatch(ctx, d, cmd)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (d *dispatchRequest) getFromImage(shlex *shell.Lex, basename string, platfo
<ide> return d.getImageOrStage(name, platform)
<ide> }
<ide>
<del>func dispatchOnbuild(d dispatchRequest, c *instructions.OnbuildCommand) error {
<add>func dispatchOnbuild(ctx context.Context, d dispatchRequest, c *instructions.OnbuildCommand) error {
<ide> d.state.runConfig.OnBuild = append(d.state.runConfig.OnBuild, c.Expression)
<del> return d.builder.commit(d.state, "ONBUILD "+c.Expression)
<add> return d.builder.commit(ctx, d.state, "ONBUILD "+c.Expression)
<ide> }
<ide>
<ide> // WORKDIR /tmp
<ide> //
<ide> // Set the working directory for future RUN/CMD/etc statements.
<del>func dispatchWorkdir(d dispatchRequest, c *instructions.WorkdirCommand) error {
<add>func dispatchWorkdir(ctx context.Context, d dispatchRequest, c *instructions.WorkdirCommand) error {
<ide> runConfig := d.state.runConfig
<ide> var err error
<ide> runConfig.WorkingDir, err = normalizeWorkdir(d.state.operatingSystem, runConfig.WorkingDir, c.Path)
<ide> func dispatchWorkdir(d dispatchRequest, c *instructions.WorkdirCommand) error {
<ide> comment := "WORKDIR " + runConfig.WorkingDir
<ide> runConfigWithCommentCmd := copyRunConfig(runConfig, withCmdCommentString(comment, d.state.operatingSystem))
<ide>
<del> containerID, err := d.builder.probeAndCreate(d.state, runConfigWithCommentCmd)
<add> containerID, err := d.builder.probeAndCreate(ctx, d.state, runConfigWithCommentCmd)
<ide> if err != nil || containerID == "" {
<ide> return err
<ide> }
<ide> func dispatchWorkdir(d dispatchRequest, c *instructions.WorkdirCommand) error {
<ide> // RUN echo hi # sh -c echo hi (Linux and LCOW)
<ide> // RUN echo hi # cmd /S /C echo hi (Windows)
<ide> // RUN [ "echo", "hi" ] # echo hi
<del>func dispatchRun(d dispatchRequest, c *instructions.RunCommand) error {
<add>func dispatchRun(ctx context.Context, d dispatchRequest, c *instructions.RunCommand) error {
<ide> if !system.IsOSSupported(d.state.operatingSystem) {
<ide> return system.ErrNotSupportedOperatingSystem
<ide> }
<ide> func dispatchRun(d dispatchRequest, c *instructions.RunCommand) error {
<ide> withEntrypointOverride(saveCmd, strslice.StrSlice{""}),
<ide> withoutHealthcheck())
<ide>
<del> cID, err := d.builder.create(runConfig)
<add> cID, err := d.builder.create(ctx, runConfig)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func prependEnvOnCmd(buildArgs *BuildArgs, buildArgVars []string, cmd strslice.S
<ide> //
<ide> // Set the default command to run in the container (which may be empty).
<ide> // Argument handling is the same as RUN.
<del>func dispatchCmd(d dispatchRequest, c *instructions.CmdCommand) error {
<add>func dispatchCmd(ctx context.Context, d dispatchRequest, c *instructions.CmdCommand) error {
<ide> runConfig := d.state.runConfig
<ide> cmd, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem, c.Name(), c.String())
<ide>
<ide> func dispatchCmd(d dispatchRequest, c *instructions.CmdCommand) error {
<ide> runConfig.Cmd = cmd
<ide> runConfig.ArgsEscaped = argsEscaped
<ide>
<del> if err := d.builder.commit(d.state, fmt.Sprintf("CMD %q", cmd)); err != nil {
<add> if err := d.builder.commit(ctx, d.state, fmt.Sprintf("CMD %q", cmd)); err != nil {
<ide> return err
<ide> }
<ide> if len(c.ShellDependantCmdLine.CmdLine) != 0 {
<ide> func dispatchCmd(d dispatchRequest, c *instructions.CmdCommand) error {
<ide> //
<ide> // Set the default healthcheck command to run in the container (which may be empty).
<ide> // Argument handling is the same as RUN.
<del>func dispatchHealthcheck(d dispatchRequest, c *instructions.HealthCheckCommand) error {
<add>func dispatchHealthcheck(ctx context.Context, d dispatchRequest, c *instructions.HealthCheckCommand) error {
<ide> runConfig := d.state.runConfig
<ide> if runConfig.Healthcheck != nil {
<ide> oldCmd := runConfig.Healthcheck.Test
<ide> func dispatchHealthcheck(d dispatchRequest, c *instructions.HealthCheckCommand)
<ide> }
<ide> }
<ide> runConfig.Healthcheck = c.Health
<del> return d.builder.commit(d.state, fmt.Sprintf("HEALTHCHECK %q", runConfig.Healthcheck))
<add> return d.builder.commit(ctx, d.state, fmt.Sprintf("HEALTHCHECK %q", runConfig.Healthcheck))
<ide> }
<ide>
<ide> // ENTRYPOINT /usr/sbin/nginx
<ide> func dispatchHealthcheck(d dispatchRequest, c *instructions.HealthCheckCommand)
<ide> //
<ide> // Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
<ide> // is initialized at newBuilder time instead of through argument parsing.
<del>func dispatchEntrypoint(d dispatchRequest, c *instructions.EntrypointCommand) error {
<add>func dispatchEntrypoint(ctx context.Context, d dispatchRequest, c *instructions.EntrypointCommand) error {
<ide> runConfig := d.state.runConfig
<ide> cmd, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem, c.Name(), c.String())
<ide>
<ide> func dispatchEntrypoint(d dispatchRequest, c *instructions.EntrypointCommand) er
<ide> runConfig.Cmd = nil
<ide> }
<ide>
<del> return d.builder.commit(d.state, fmt.Sprintf("ENTRYPOINT %q", runConfig.Entrypoint))
<add> return d.builder.commit(ctx, d.state, fmt.Sprintf("ENTRYPOINT %q", runConfig.Entrypoint))
<ide> }
<ide>
<ide> // EXPOSE 6667/tcp 7000/tcp
<ide> //
<ide> // Expose ports for links and port mappings. This all ends up in
<ide> // req.runConfig.ExposedPorts for runconfig.
<del>func dispatchExpose(d dispatchRequest, c *instructions.ExposeCommand, envs []string) error {
<add>func dispatchExpose(ctx context.Context, d dispatchRequest, c *instructions.ExposeCommand, envs []string) error {
<ide> // custom multi word expansion
<ide> // expose $FOO with FOO="80 443" is expanded as EXPOSE [80,443]. This is the only command supporting word to words expansion
<ide> // so the word processing has been de-generalized
<ide> func dispatchExpose(d dispatchRequest, c *instructions.ExposeCommand, envs []str
<ide> d.state.runConfig.ExposedPorts[p] = struct{}{}
<ide> }
<ide>
<del> return d.builder.commit(d.state, "EXPOSE "+strings.Join(c.Ports, " "))
<add> return d.builder.commit(ctx, d.state, "EXPOSE "+strings.Join(c.Ports, " "))
<ide> }
<ide>
<ide> // USER foo
<ide> //
<ide> // Set the user to 'foo' for future commands and when running the
<ide> // ENTRYPOINT/CMD at container run time.
<del>func dispatchUser(d dispatchRequest, c *instructions.UserCommand) error {
<add>func dispatchUser(ctx context.Context, d dispatchRequest, c *instructions.UserCommand) error {
<ide> d.state.runConfig.User = c.User
<del> return d.builder.commit(d.state, fmt.Sprintf("USER %v", c.User))
<add> return d.builder.commit(ctx, d.state, fmt.Sprintf("USER %v", c.User))
<ide> }
<ide>
<ide> // VOLUME /foo
<ide> //
<ide> // Expose the volume /foo for use. Will also accept the JSON array form.
<del>func dispatchVolume(d dispatchRequest, c *instructions.VolumeCommand) error {
<add>func dispatchVolume(ctx context.Context, d dispatchRequest, c *instructions.VolumeCommand) error {
<ide> if d.state.runConfig.Volumes == nil {
<ide> d.state.runConfig.Volumes = map[string]struct{}{}
<ide> }
<ide> func dispatchVolume(d dispatchRequest, c *instructions.VolumeCommand) error {
<ide> }
<ide> d.state.runConfig.Volumes[v] = struct{}{}
<ide> }
<del> return d.builder.commit(d.state, fmt.Sprintf("VOLUME %v", c.Volumes))
<add> return d.builder.commit(ctx, d.state, fmt.Sprintf("VOLUME %v", c.Volumes))
<ide> }
<ide>
<ide> // STOPSIGNAL signal
<ide> //
<ide> // Set the signal that will be used to kill the container.
<del>func dispatchStopSignal(d dispatchRequest, c *instructions.StopSignalCommand) error {
<add>func dispatchStopSignal(ctx context.Context, d dispatchRequest, c *instructions.StopSignalCommand) error {
<ide> _, err := signal.ParseSignal(c.Signal)
<ide> if err != nil {
<ide> return errdefs.InvalidParameter(err)
<ide> }
<ide> d.state.runConfig.StopSignal = c.Signal
<del> return d.builder.commit(d.state, fmt.Sprintf("STOPSIGNAL %v", c.Signal))
<add> return d.builder.commit(ctx, d.state, fmt.Sprintf("STOPSIGNAL %v", c.Signal))
<ide> }
<ide>
<ide> // ARG name[=value]
<ide> //
<ide> // Adds the variable foo to the trusted list of variables that can be passed
<ide> // to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
<ide> // Dockerfile author may optionally set a default value of this variable.
<del>func dispatchArg(d dispatchRequest, c *instructions.ArgCommand) error {
<add>func dispatchArg(ctx context.Context, d dispatchRequest, c *instructions.ArgCommand) error {
<ide> var commitStr strings.Builder
<ide> commitStr.WriteString("ARG ")
<ide> for i, arg := range c.Args {
<ide> func dispatchArg(d dispatchRequest, c *instructions.ArgCommand) error {
<ide> d.state.buildArgs.AddArg(arg.Key, arg.Value)
<ide> }
<ide>
<del> return d.builder.commit(d.state, commitStr.String())
<add> return d.builder.commit(ctx, d.state, commitStr.String())
<ide> }
<ide>
<ide> // SHELL powershell -command
<ide> //
<ide> // Set the non-default shell to use.
<del>func dispatchShell(d dispatchRequest, c *instructions.ShellCommand) error {
<add>func dispatchShell(ctx context.Context, d dispatchRequest, c *instructions.ShellCommand) error {
<ide> d.state.runConfig.Shell = c.Shell
<del> return d.builder.commit(d.state, fmt.Sprintf("SHELL %v", d.state.runConfig.Shell))
<add> return d.builder.commit(ctx, d.state, fmt.Sprintf("SHELL %v", d.state.runConfig.Shell))
<ide> }
<ide><path>builder/dockerfile/dispatchers_test.go
<ide> import (
<ide> is "gotest.tools/v3/assert/cmp"
<ide> )
<ide>
<del>func newBuilderWithMockBackend() *Builder {
<add>func newBuilderWithMockBackend(t *testing.T) *Builder {
<add> t.Helper()
<ide> mockBackend := &MockBackend{}
<ide> opts := &types.ImageBuildOptions{}
<ide> ctx := context.Background()
<add>
<add> imageProber, err := newImageProber(ctx, mockBackend, nil, false)
<add> assert.NilError(t, err, "Could not create image prober")
<add>
<ide> b := &Builder{
<ide> options: opts,
<ide> docker: mockBackend,
<ide> func newBuilderWithMockBackend() *Builder {
<ide> Options: opts,
<ide> Backend: mockBackend,
<ide> }),
<del> imageProber: newImageProber(mockBackend, nil, false),
<add> imageProber: imageProber,
<ide> containerManager: newContainerManager(mockBackend),
<ide> }
<ide> return b
<ide> }
<ide>
<ide> func TestEnv2Variables(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> envCommand := &instructions.EnvCommand{
<ide> Env: instructions.KeyValuePairs{
<ide> instructions.KeyValuePair{Key: "var1", Value: "val1"},
<ide> instructions.KeyValuePair{Key: "var2", Value: "val2"},
<ide> },
<ide> }
<del> err := dispatch(sb, envCommand)
<add> err := dispatch(context.TODO(), sb, envCommand)
<ide> assert.NilError(t, err)
<ide>
<ide> expected := []string{
<ide> func TestEnv2Variables(t *testing.T) {
<ide> }
<ide>
<ide> func TestEnvValueWithExistingRunConfigEnv(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> sb.state.runConfig.Env = []string{"var1=old", "var2=fromenv"}
<ide> envCommand := &instructions.EnvCommand{
<ide> Env: instructions.KeyValuePairs{
<ide> instructions.KeyValuePair{Key: "var1", Value: "val1"},
<ide> },
<ide> }
<del> err := dispatch(sb, envCommand)
<add> err := dispatch(context.TODO(), sb, envCommand)
<ide> assert.NilError(t, err)
<ide> expected := []string{
<ide> "var1=val1",
<ide> func TestEnvValueWithExistingRunConfigEnv(t *testing.T) {
<ide>
<ide> func TestMaintainer(t *testing.T) {
<ide> maintainerEntry := "Some Maintainer <maintainer@example.com>"
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> cmd := &instructions.MaintainerCommand{Maintainer: maintainerEntry}
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(maintainerEntry, sb.state.maintainer))
<ide> }
<ide> func TestLabel(t *testing.T) {
<ide> labelName := "label"
<ide> labelValue := "value"
<ide>
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> cmd := &instructions.LabelCommand{
<ide> Labels: instructions.KeyValuePairs{
<ide> instructions.KeyValuePair{Key: labelName, Value: labelValue},
<ide> },
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide>
<ide> assert.Assert(t, is.Contains(sb.state.runConfig.Labels, labelName))
<ide> assert.Check(t, is.Equal(sb.state.runConfig.Labels[labelName], labelValue))
<ide> }
<ide>
<ide> func TestFromScratch(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> cmd := &instructions.Stage{
<ide> BaseName: "scratch",
<ide> }
<del> err := initializeStage(sb, cmd)
<add> err := initializeStage(context.TODO(), sb, cmd)
<ide>
<ide> if runtime.GOOS == "windows" {
<ide> assert.Check(t, is.Error(err, "Windows does not support FROM scratch"))
<ide> func TestFromWithArg(t *testing.T) {
<ide> assert.Check(t, is.Equal("alpine"+tag, name))
<ide> return &mockImage{id: "expectedthisid"}, nil, nil
<ide> }
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> b.docker.(*MockBackend).getImageFunc = getImage
<ide> args := NewBuildArgs(make(map[string]*string))
<ide>
<ide> func TestFromWithArg(t *testing.T) {
<ide>
<ide> sb := newDispatchRequest(b, '\\', nil, args, newStagesBuildResults())
<ide> assert.NilError(t, err)
<del> err = initializeStage(sb, cmd)
<add> err = initializeStage(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide>
<ide> assert.Check(t, is.Equal(expected, sb.state.imageID))
<ide> func TestFromWithArg(t *testing.T) {
<ide> }
<ide>
<ide> func TestFromWithArgButBuildArgsNotGiven(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> args := NewBuildArgs(make(map[string]*string))
<ide>
<ide> metaArg := instructions.ArgCommand{}
<ide> func TestFromWithArgButBuildArgsNotGiven(t *testing.T) {
<ide>
<ide> sb := newDispatchRequest(b, '\\', nil, args, newStagesBuildResults())
<ide> assert.NilError(t, err)
<del> err = initializeStage(sb, cmd)
<add> err = initializeStage(context.TODO(), sb, cmd)
<ide> assert.Error(t, err, "base name (${THETAG}) should not be blank")
<ide> }
<ide>
<ide> func TestFromWithUndefinedArg(t *testing.T) {
<ide> assert.Check(t, is.Equal("alpine", name))
<ide> return &mockImage{id: "expectedthisid"}, nil, nil
<ide> }
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> b.docker.(*MockBackend).getImageFunc = getImage
<ide> sb := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide>
<ide> func TestFromWithUndefinedArg(t *testing.T) {
<ide> cmd := &instructions.Stage{
<ide> BaseName: "alpine${THETAG}",
<ide> }
<del> err := initializeStage(sb, cmd)
<add> err := initializeStage(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(expected, sb.state.imageID))
<ide> }
<ide>
<ide> func TestFromMultiStageWithNamedStage(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> firstFrom := &instructions.Stage{BaseName: "someimg", Name: "base"}
<ide> secondFrom := &instructions.Stage{BaseName: "base"}
<ide> previousResults := newStagesBuildResults()
<ide> firstSB := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), previousResults)
<ide> secondSB := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), previousResults)
<del> err := initializeStage(firstSB, firstFrom)
<add> err := initializeStage(context.TODO(), firstSB, firstFrom)
<ide> assert.NilError(t, err)
<ide> assert.Check(t, firstSB.state.hasFromImage())
<ide> previousResults.indexed["base"] = firstSB.state.runConfig
<ide> previousResults.flat = append(previousResults.flat, firstSB.state.runConfig)
<del> err = initializeStage(secondSB, secondFrom)
<add> err = initializeStage(context.TODO(), secondSB, secondFrom)
<ide> assert.NilError(t, err)
<ide> assert.Check(t, secondSB.state.hasFromImage())
<ide> }
<ide>
<ide> func TestOnbuild(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '\\', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> cmd := &instructions.OnbuildCommand{
<ide> Expression: "ADD . /app/src",
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal("ADD . /app/src", sb.state.runConfig.OnBuild[0]))
<ide> }
<ide>
<ide> func TestWorkdir(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> sb.state.baseImage = &mockImage{}
<ide> workingDir := "/app"
<ide> func TestWorkdir(t *testing.T) {
<ide> Path: workingDir,
<ide> }
<ide>
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(workingDir, sb.state.runConfig.WorkingDir))
<ide> }
<ide>
<ide> func TestCmd(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> sb.state.baseImage = &mockImage{}
<ide> command := "./executable"
<ide> func TestCmd(t *testing.T) {
<ide> PrependShell: true,
<ide> },
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide>
<ide> var expectedCommand strslice.StrSlice
<ide> func TestCmd(t *testing.T) {
<ide> }
<ide>
<ide> func TestHealthcheckNone(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> cmd := &instructions.HealthCheckCommand{
<ide> Health: &container.HealthConfig{
<ide> Test: []string{"NONE"},
<ide> },
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide>
<ide> assert.Assert(t, sb.state.runConfig.Healthcheck != nil)
<ide> assert.Check(t, is.DeepEqual([]string{"NONE"}, sb.state.runConfig.Healthcheck.Test))
<ide> }
<ide>
<ide> func TestHealthcheckCmd(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> expectedTest := []string{"CMD-SHELL", "curl -f http://localhost/ || exit 1"}
<ide> cmd := &instructions.HealthCheckCommand{
<ide> Health: &container.HealthConfig{
<ide> Test: expectedTest,
<ide> },
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide>
<ide> assert.Assert(t, sb.state.runConfig.Healthcheck != nil)
<ide> assert.Check(t, is.DeepEqual(expectedTest, sb.state.runConfig.Healthcheck.Test))
<ide> }
<ide>
<ide> func TestEntrypoint(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> sb.state.baseImage = &mockImage{}
<ide> entrypointCmd := "/usr/sbin/nginx"
<ide> func TestEntrypoint(t *testing.T) {
<ide> PrependShell: true,
<ide> },
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide> assert.Assert(t, sb.state.runConfig.Entrypoint != nil)
<ide>
<ide> func TestEntrypoint(t *testing.T) {
<ide> }
<ide>
<ide> func TestExpose(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide>
<ide> exposedPort := "80"
<ide> cmd := &instructions.ExposeCommand{
<ide> Ports: []string{exposedPort},
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide>
<ide> assert.Assert(t, sb.state.runConfig.ExposedPorts != nil)
<ide> func TestExpose(t *testing.T) {
<ide> }
<ide>
<ide> func TestUser(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide>
<ide> cmd := &instructions.UserCommand{
<ide> User: "test",
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal("test", sb.state.runConfig.User))
<ide> }
<ide>
<ide> func TestVolume(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide>
<ide> exposedVolume := "/foo"
<ide>
<ide> cmd := &instructions.VolumeCommand{
<ide> Volumes: []string{exposedVolume},
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide> assert.Assert(t, sb.state.runConfig.Volumes != nil)
<ide> assert.Check(t, is.Len(sb.state.runConfig.Volumes, 1))
<ide> func TestStopSignal(t *testing.T) {
<ide> t.Skip("Windows does not support stopsignal")
<ide> return
<ide> }
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> sb.state.baseImage = &mockImage{}
<ide> signal := "SIGKILL"
<ide>
<ide> cmd := &instructions.StopSignalCommand{
<ide> Signal: signal,
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide> assert.Check(t, is.Equal(signal, sb.state.runConfig.StopSignal))
<ide> }
<ide>
<ide> func TestArg(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide>
<ide> argName := "foo"
<ide> argVal := "bar"
<ide> cmd := &instructions.ArgCommand{Args: []instructions.KeyValuePairOptional{{Key: argName, Value: &argVal}}}
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide>
<ide> expected := map[string]string{argName: argVal}
<ide> assert.Check(t, is.DeepEqual(expected, sb.state.buildArgs.GetAllAllowed()))
<ide> }
<ide>
<ide> func TestShell(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide>
<ide> shellCmd := "powershell"
<ide> cmd := &instructions.ShellCommand{Shell: strslice.StrSlice{shellCmd}}
<ide>
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.NilError(t, err)
<ide>
<ide> expectedShell := strslice.StrSlice([]string{shellCmd})
<ide> func TestPrependEnvOnCmd(t *testing.T) {
<ide> }
<ide>
<ide> func TestRunWithBuildArgs(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> args := NewBuildArgs(make(map[string]*string))
<ide> args.argsFromOptions["HTTP_PROXY"] = strPtr("FOO")
<ide> b.disableCommit = false
<ide> func TestRunWithBuildArgs(t *testing.T) {
<ide> mockBackend.makeImageCacheFunc = func(_ []string) builder.ImageCache {
<ide> return imageCache
<ide> }
<del> b.imageProber = newImageProber(mockBackend, nil, false)
<add>
<add> imageProber, err := newImageProber(context.TODO(), mockBackend, nil, false)
<add> assert.NilError(t, err, "Could not create image prober")
<add> b.imageProber = imageProber
<add>
<ide> mockBackend.getImageFunc = func(_ string) (builder.Image, builder.ROLayer, error) {
<ide> return &mockImage{
<ide> id: "abcdef",
<ide> func TestRunWithBuildArgs(t *testing.T) {
<ide> return "", nil
<ide> }
<ide> from := &instructions.Stage{BaseName: "abcdef"}
<del> err := initializeStage(sb, from)
<add> err = initializeStage(context.TODO(), sb, from)
<ide> assert.NilError(t, err)
<ide> sb.state.buildArgs.AddArg("one", strPtr("two"))
<ide>
<ide> func TestRunWithBuildArgs(t *testing.T) {
<ide> runinst.CmdLine = strslice.StrSlice{"echo foo"}
<ide> runinst.PrependShell = true
<ide>
<del> assert.NilError(t, dispatch(sb, runinst))
<add> assert.NilError(t, dispatch(context.TODO(), sb, runinst))
<ide>
<ide> // Check that runConfig.Cmd has not been modified by run
<ide> assert.Check(t, is.DeepEqual(origCmd, sb.state.runConfig.Cmd))
<ide> }
<ide>
<ide> func TestRunIgnoresHealthcheck(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> args := NewBuildArgs(make(map[string]*string))
<ide> sb := newDispatchRequest(b, '`', nil, args, newStagesBuildResults())
<ide> b.disableCommit = false
<ide> func TestRunIgnoresHealthcheck(t *testing.T) {
<ide> mockBackend.makeImageCacheFunc = func(_ []string) builder.ImageCache {
<ide> return imageCache
<ide> }
<del> b.imageProber = newImageProber(mockBackend, nil, false)
<add> imageProber, err := newImageProber(context.TODO(), mockBackend, nil, false)
<add> assert.NilError(t, err, "Could not create image prober")
<add>
<add> b.imageProber = imageProber
<ide> mockBackend.getImageFunc = func(_ string) (builder.Image, builder.ROLayer, error) {
<ide> return &mockImage{
<ide> id: "abcdef",
<ide> func TestRunIgnoresHealthcheck(t *testing.T) {
<ide> return "", nil
<ide> }
<ide> from := &instructions.Stage{BaseName: "abcdef"}
<del> err := initializeStage(sb, from)
<add> err = initializeStage(context.TODO(), sb, from)
<ide> assert.NilError(t, err)
<ide>
<ide> expectedTest := []string{"CMD-SHELL", "curl -f http://localhost/ || exit 1"}
<ide> func TestRunIgnoresHealthcheck(t *testing.T) {
<ide> assert.NilError(t, err)
<ide> cmd := healthint.(*instructions.HealthCheckCommand)
<ide>
<del> assert.NilError(t, dispatch(sb, cmd))
<add> assert.NilError(t, dispatch(context.TODO(), sb, cmd))
<ide> assert.Assert(t, sb.state.runConfig.Healthcheck != nil)
<ide>
<ide> mockBackend.containerCreateFunc = func(config types.ContainerCreateConfig) (container.CreateResponse, error) {
<ide> func TestRunIgnoresHealthcheck(t *testing.T) {
<ide> run := runint.(*instructions.RunCommand)
<ide> run.PrependShell = true
<ide>
<del> assert.NilError(t, dispatch(sb, run))
<add> assert.NilError(t, dispatch(context.TODO(), sb, run))
<ide> assert.Check(t, is.DeepEqual(expectedTest, sb.state.runConfig.Healthcheck.Test))
<ide> }
<ide>
<ide> func TestDispatchUnsupportedOptions(t *testing.T) {
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', nil, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<ide> sb.state.baseImage = &mockImage{}
<ide> sb.state.operatingSystem = runtime.GOOS
<ide> func TestDispatchUnsupportedOptions(t *testing.T) {
<ide> },
<ide> Chmod: "0655",
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.Error(t, err, "the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled")
<ide> })
<ide>
<ide> func TestDispatchUnsupportedOptions(t *testing.T) {
<ide> },
<ide> Chmod: "0655",
<ide> }
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.Error(t, err, "the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled")
<ide> })
<ide>
<ide> func TestDispatchUnsupportedOptions(t *testing.T) {
<ide> // one or more of these flags will be supported in future
<ide> for _, f := range []string{"mount", "network", "security", "any-flag"} {
<ide> cmd.FlagsUsed = []string{f}
<del> err := dispatch(sb, cmd)
<add> err := dispatch(context.TODO(), sb, cmd)
<ide> assert.Error(t, err, fmt.Sprintf("the --%s option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled", f))
<ide> }
<ide> })
<ide><path>builder/dockerfile/evaluator.go
<ide> package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<ide>
<ide> import (
<add> "context"
<ide> "reflect"
<ide> "strconv"
<ide> "strings"
<ide> import (
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<del>func dispatch(d dispatchRequest, cmd instructions.Command) (err error) {
<add>func dispatch(ctx context.Context, d dispatchRequest, cmd instructions.Command) (err error) {
<ide> if c, ok := cmd.(instructions.PlatformSpecific); ok {
<ide> err := c.CheckPlatform(d.state.operatingSystem)
<ide> if err != nil {
<ide> func dispatch(d dispatchRequest, cmd instructions.Command) (err error) {
<ide> }()
<ide> switch c := cmd.(type) {
<ide> case *instructions.EnvCommand:
<del> return dispatchEnv(d, c)
<add> return dispatchEnv(ctx, d, c)
<ide> case *instructions.MaintainerCommand:
<del> return dispatchMaintainer(d, c)
<add> return dispatchMaintainer(ctx, d, c)
<ide> case *instructions.LabelCommand:
<del> return dispatchLabel(d, c)
<add> return dispatchLabel(ctx, d, c)
<ide> case *instructions.AddCommand:
<del> return dispatchAdd(d, c)
<add> return dispatchAdd(ctx, d, c)
<ide> case *instructions.CopyCommand:
<del> return dispatchCopy(d, c)
<add> return dispatchCopy(ctx, d, c)
<ide> case *instructions.OnbuildCommand:
<del> return dispatchOnbuild(d, c)
<add> return dispatchOnbuild(ctx, d, c)
<ide> case *instructions.WorkdirCommand:
<del> return dispatchWorkdir(d, c)
<add> return dispatchWorkdir(ctx, d, c)
<ide> case *instructions.RunCommand:
<del> return dispatchRun(d, c)
<add> return dispatchRun(ctx, d, c)
<ide> case *instructions.CmdCommand:
<del> return dispatchCmd(d, c)
<add> return dispatchCmd(ctx, d, c)
<ide> case *instructions.HealthCheckCommand:
<del> return dispatchHealthcheck(d, c)
<add> return dispatchHealthcheck(ctx, d, c)
<ide> case *instructions.EntrypointCommand:
<del> return dispatchEntrypoint(d, c)
<add> return dispatchEntrypoint(ctx, d, c)
<ide> case *instructions.ExposeCommand:
<del> return dispatchExpose(d, c, envs)
<add> return dispatchExpose(ctx, d, c, envs)
<ide> case *instructions.UserCommand:
<del> return dispatchUser(d, c)
<add> return dispatchUser(ctx, d, c)
<ide> case *instructions.VolumeCommand:
<del> return dispatchVolume(d, c)
<add> return dispatchVolume(ctx, d, c)
<ide> case *instructions.StopSignalCommand:
<del> return dispatchStopSignal(d, c)
<add> return dispatchStopSignal(ctx, d, c)
<ide> case *instructions.ArgCommand:
<del> return dispatchArg(d, c)
<add> return dispatchArg(ctx, d, c)
<ide> case *instructions.ShellCommand:
<del> return dispatchShell(d, c)
<add> return dispatchShell(ctx, d, c)
<ide> }
<ide> return errors.Errorf("unsupported command type: %v", reflect.TypeOf(cmd))
<ide> }
<ide><path>builder/dockerfile/evaluator_test.go
<ide> package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<ide>
<ide> import (
<add> "context"
<ide> "os"
<ide> "runtime"
<ide> "testing"
<ide> func TestDispatch(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> b := newBuilderWithMockBackend()
<add> b := newBuilderWithMockBackend(t)
<ide> sb := newDispatchRequest(b, '`', buildContext, NewBuildArgs(make(map[string]*string)), newStagesBuildResults())
<del> err = dispatch(sb, tc.cmd)
<add> err = dispatch(context.TODO(), sb, tc.cmd)
<ide> assert.Check(t, is.ErrorContains(err, tc.expectedError))
<ide> })
<ide> }
<ide><path>builder/dockerfile/imageprobe.go
<ide> package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<ide>
<ide> import (
<add> "context"
<add>
<ide> "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/sirupsen/logrus"
<ide> import (
<ide> // ImageProber exposes an Image cache to the Builder. It supports resetting a
<ide> // cache.
<ide> type ImageProber interface {
<del> Reset()
<add> Reset(ctx context.Context) error
<ide> Probe(parentID string, runConfig *container.Config) (string, error)
<ide> }
<ide>
<add>type resetFunc func(context.Context) (builder.ImageCache, error)
<add>
<ide> type imageProber struct {
<ide> cache builder.ImageCache
<del> reset func() builder.ImageCache
<add> reset resetFunc
<ide> cacheBusted bool
<ide> }
<ide>
<del>func newImageProber(cacheBuilder builder.ImageCacheBuilder, cacheFrom []string, noCache bool) ImageProber {
<add>func newImageProber(ctx context.Context, cacheBuilder builder.ImageCacheBuilder, cacheFrom []string, noCache bool) (ImageProber, error) {
<ide> if noCache {
<del> return &nopProber{}
<add> return &nopProber{}, nil
<add> }
<add>
<add> reset := func(ctx context.Context) (builder.ImageCache, error) {
<add> return cacheBuilder.MakeImageCache(ctx, cacheFrom)
<ide> }
<ide>
<del> reset := func() builder.ImageCache {
<del> return cacheBuilder.MakeImageCache(cacheFrom)
<add> cache, err := reset(ctx)
<add> if err != nil {
<add> return nil, err
<ide> }
<del> return &imageProber{cache: reset(), reset: reset}
<add> return &imageProber{cache: cache, reset: reset}, nil
<ide> }
<ide>
<del>func (c *imageProber) Reset() {
<del> c.cache = c.reset()
<add>func (c *imageProber) Reset(ctx context.Context) error {
<add> newCache, err := c.reset(ctx)
<add> if err != nil {
<add> return err
<add> }
<add> c.cache = newCache
<ide> c.cacheBusted = false
<add> return nil
<ide> }
<ide>
<ide> // Probe checks if cache match can be found for current build instruction.
<ide> func (c *imageProber) Probe(parentID string, runConfig *container.Config) (strin
<ide>
<ide> type nopProber struct{}
<ide>
<del>func (c *nopProber) Reset() {}
<add>func (c *nopProber) Reset(ctx context.Context) error {
<add> return nil
<add>}
<ide>
<ide> func (c *nopProber) Probe(_ string, _ *container.Config) (string, error) {
<ide> return "", nil
<ide><path>builder/dockerfile/internals.go
<ide> package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<ide> // non-contiguous functionality. Please read the comments.
<ide>
<ide> import (
<add> "context"
<ide> "crypto/sha256"
<ide> "encoding/hex"
<ide> "fmt"
<ide> func (b *Builder) getArchiver() *archive.Archiver {
<ide> return chrootarchive.NewArchiver(b.idMapping)
<ide> }
<ide>
<del>func (b *Builder) commit(dispatchState *dispatchState, comment string) error {
<add>func (b *Builder) commit(ctx context.Context, dispatchState *dispatchState, comment string) error {
<ide> if b.disableCommit {
<ide> return nil
<ide> }
<ide> func (b *Builder) commit(dispatchState *dispatchState, comment string) error {
<ide> }
<ide>
<ide> runConfigWithCommentCmd := copyRunConfig(dispatchState.runConfig, withCmdComment(comment, dispatchState.operatingSystem))
<del> id, err := b.probeAndCreate(dispatchState, runConfigWithCommentCmd)
<add> id, err := b.probeAndCreate(ctx, dispatchState, runConfigWithCommentCmd)
<ide> if err != nil || id == "" {
<ide> return err
<ide> }
<ide> func (b *Builder) exportImage(state *dispatchState, layer builder.RWLayer, paren
<ide> return nil
<ide> }
<ide>
<del>func (b *Builder) performCopy(req dispatchRequest, inst copyInstruction) error {
<add>func (b *Builder) performCopy(ctx context.Context, req dispatchRequest, inst copyInstruction) error {
<ide> state := req.state
<ide> srcHash := getSourceHashFromInfos(inst.infos)
<ide>
<ide> func (b *Builder) performCopy(req dispatchRequest, inst copyInstruction) error {
<ide> // translated (if necessary because of user namespaces), and replace
<ide> // the root pair with the chown pair for copy operations
<ide> if inst.chownStr != "" {
<del> identity, err = parseChownFlag(b, state, inst.chownStr, destInfo.root, b.idMapping)
<add> identity, err = parseChownFlag(ctx, b, state, inst.chownStr, destInfo.root, b.idMapping)
<ide> if err != nil {
<ide> if b.options.Platform != "windows" {
<ide> return errors.Wrapf(err, "unable to convert uid/gid chown string to host mapping")
<ide> func (b *Builder) probeCache(dispatchState *dispatchState, runConfig *container.
<ide>
<ide> var defaultLogConfig = container.LogConfig{Type: "none"}
<ide>
<del>func (b *Builder) probeAndCreate(dispatchState *dispatchState, runConfig *container.Config) (string, error) {
<add>func (b *Builder) probeAndCreate(ctx context.Context, dispatchState *dispatchState, runConfig *container.Config) (string, error) {
<ide> if hit, err := b.probeCache(dispatchState, runConfig); err != nil || hit {
<ide> return "", err
<ide> }
<del> return b.create(runConfig)
<add> return b.create(ctx, runConfig)
<ide> }
<ide>
<del>func (b *Builder) create(runConfig *container.Config) (string, error) {
<add>func (b *Builder) create(ctx context.Context, runConfig *container.Config) (string, error) {
<ide> logrus.Debugf("[BUILDER] Command to be executed: %v", runConfig.Cmd)
<ide>
<ide> hostConfig := hostConfigFromOptions(b.options)
<del> container, err := b.containerManager.Create(runConfig, hostConfig)
<add> container, err := b.containerManager.Create(ctx, runConfig, hostConfig)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide><path>builder/dockerfile/internals_linux.go
<ide> package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<ide>
<ide> import (
<add> "context"
<ide> "path/filepath"
<ide> "strconv"
<ide> "strings"
<ide> import (
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<del>func parseChownFlag(builder *Builder, state *dispatchState, chown, ctrRootPath string, identityMapping idtools.IdentityMapping) (idtools.Identity, error) {
<add>func parseChownFlag(ctx context.Context, builder *Builder, state *dispatchState, chown, ctrRootPath string, identityMapping idtools.IdentityMapping) (idtools.Identity, error) {
<ide> var userStr, grpStr string
<ide> parts := strings.Split(chown, ":")
<ide> if len(parts) > 2 {
<ide><path>builder/dockerfile/internals_linux_test.go
<ide> package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<ide>
<ide> import (
<add> "context"
<ide> "os"
<ide> "path/filepath"
<ide> "testing"
<ide> othergrp:x:6666:
<ide> },
<ide> } {
<ide> t.Run(testcase.name, func(t *testing.T) {
<del> idPair, err := parseChownFlag(testcase.builder, testcase.state, testcase.chownStr, contextDir, testcase.idMapping)
<add> idPair, err := parseChownFlag(context.TODO(), testcase.builder, testcase.state, testcase.chownStr, contextDir, testcase.idMapping)
<ide> assert.NilError(t, err, "Failed to parse chown flag: %q", testcase.chownStr)
<ide> assert.Check(t, is.DeepEqual(testcase.expected, idPair), "chown flag mapping failure")
<ide> })
<ide> othergrp:x:6666:
<ide> },
<ide> } {
<ide> t.Run(testcase.name, func(t *testing.T) {
<del> _, err := parseChownFlag(testcase.builder, testcase.state, testcase.chownStr, contextDir, testcase.idMapping)
<add> _, err := parseChownFlag(context.TODO(), testcase.builder, testcase.state, testcase.chownStr, contextDir, testcase.idMapping)
<ide> assert.Check(t, is.Error(err, testcase.descr), "Expected error string doesn't match")
<ide> })
<ide> }
<ide><path>builder/dockerfile/internals_windows.go
<ide> package dockerfile // import "github.com/docker/docker/builder/dockerfile"
<ide>
<ide> import (
<ide> "bytes"
<add> "context"
<ide> "os"
<ide> "path/filepath"
<ide> "strings"
<ide> import (
<ide> "golang.org/x/sys/windows"
<ide> )
<ide>
<del>func parseChownFlag(builder *Builder, state *dispatchState, chown, ctrRootPath string, identityMapping idtools.IdentityMapping) (idtools.Identity, error) {
<add>func parseChownFlag(ctx context.Context, builder *Builder, state *dispatchState, chown, ctrRootPath string, identityMapping idtools.IdentityMapping) (idtools.Identity, error) {
<ide> if builder.options.Platform == "windows" {
<del> return getAccountIdentity(builder, chown, ctrRootPath, state)
<add> return getAccountIdentity(ctx, builder, chown, ctrRootPath, state)
<ide> }
<ide>
<ide> return identityMapping.RootPair(), nil
<ide> }
<ide>
<del>func getAccountIdentity(builder *Builder, accountName string, ctrRootPath string, state *dispatchState) (idtools.Identity, error) {
<add>func getAccountIdentity(ctx context.Context, builder *Builder, accountName string, ctrRootPath string, state *dispatchState) (idtools.Identity, error) {
<ide> // If this is potentially a string SID then attempt to convert it to verify
<ide> // this, otherwise continue looking for the account.
<ide> if strings.HasPrefix(accountName, "S-") || strings.HasPrefix(accountName, "s-") {
<ide> func getAccountIdentity(builder *Builder, accountName string, ctrRootPath string
<ide>
<ide> // All other lookups failed, so therefore determine if the account in
<ide> // question exists in the container and if so, obtain its SID.
<del> return lookupNTAccount(builder, accountName, state)
<add> return lookupNTAccount(ctx, builder, accountName, state)
<ide> }
<ide>
<del>func lookupNTAccount(builder *Builder, accountName string, state *dispatchState) (idtools.Identity, error) {
<add>func lookupNTAccount(ctx context.Context, builder *Builder, accountName string, state *dispatchState) (idtools.Identity, error) {
<ide>
<ide> source, _ := filepath.Split(os.Args[0])
<ide>
<ide> func lookupNTAccount(builder *Builder, accountName string, state *dispatchState)
<ide> },
<ide> }
<ide>
<del> container, err := builder.containerManager.Create(runConfig, hostConfig)
<add> container, err := builder.containerManager.Create(ctx, runConfig, hostConfig)
<ide> if err != nil {
<ide> return idtools.Identity{}, err
<ide> }
<ide><path>builder/dockerfile/mockbackend_test.go
<ide> func (m *MockBackend) ContainerAttachRaw(cID string, stdin io.ReadCloser, stdout
<ide> return nil
<ide> }
<ide>
<del>func (m *MockBackend) ContainerCreateIgnoreImagesArgsEscaped(config types.ContainerCreateConfig) (container.CreateResponse, error) {
<add>func (m *MockBackend) ContainerCreateIgnoreImagesArgsEscaped(ctx context.Context, config types.ContainerCreateConfig) (container.CreateResponse, error) {
<ide> if m.containerCreateFunc != nil {
<ide> return m.containerCreateFunc(config)
<ide> }
<ide> func (m *MockBackend) ContainerKill(containerID string, sig string) error {
<ide> return nil
<ide> }
<ide>
<del>func (m *MockBackend) ContainerStart(containerID string, hostConfig *container.HostConfig, checkpoint string, checkpointDir string) error {
<add>func (m *MockBackend) ContainerStart(ctx context.Context, containerID string, hostConfig *container.HostConfig, checkpoint string, checkpointDir string) error {
<ide> return nil
<ide> }
<ide>
<ide> func (m *MockBackend) GetImageAndReleasableLayer(ctx context.Context, refOrID st
<ide> return &mockImage{id: "theid"}, &mockLayer{}, nil
<ide> }
<ide>
<del>func (m *MockBackend) MakeImageCache(cacheFrom []string) builder.ImageCache {
<add>func (m *MockBackend) MakeImageCache(ctx context.Context, cacheFrom []string) (builder.ImageCache, error) {
<ide> if m.makeImageCacheFunc != nil {
<del> return m.makeImageCacheFunc(cacheFrom)
<add> return m.makeImageCacheFunc(cacheFrom), nil
<ide> }
<del> return nil
<add> return nil, nil
<ide> }
<ide>
<ide> func (m *MockBackend) CreateImage(config []byte, parent string) (builder.Image, error) {
<ide><path>cmd/dockerd/daemon.go
<ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
<ide>
<ide> // notify systemd that we're shutting down
<ide> notifyStopping()
<del> shutdownDaemon(d)
<add> shutdownDaemon(ctx, d)
<ide>
<ide> // Stop notification processing and any background processes
<ide> cancel()
<ide> func (cli *DaemonCli) stop() {
<ide> // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
<ide> // d.Shutdown() is waiting too long to kill container or worst it's
<ide> // blocked there
<del>func shutdownDaemon(d *daemon.Daemon) {
<add>func shutdownDaemon(ctx context.Context, d *daemon.Daemon) {
<ide> shutdownTimeout := d.ShutdownTimeout()
<ide> ch := make(chan struct{})
<ide> go func() {
<del> d.Shutdown()
<add> d.Shutdown(ctx)
<ide> close(ch)
<ide> }()
<ide> if shutdownTimeout < 0 {
<ide><path>daemon/cluster/executor/backend.go
<ide> type Backend interface {
<ide> FindNetwork(idName string) (libnetwork.Network, error)
<ide> SetupIngress(clustertypes.NetworkCreateRequest, string) (<-chan struct{}, error)
<ide> ReleaseIngress() (<-chan struct{}, error)
<del> CreateManagedContainer(config types.ContainerCreateConfig) (container.CreateResponse, error)
<del> ContainerStart(name string, hostConfig *container.HostConfig, checkpoint string, checkpointDir string) error
<add> CreateManagedContainer(ctx context.Context, config types.ContainerCreateConfig) (container.CreateResponse, error)
<add> ContainerStart(ctx context.Context, name string, hostConfig *container.HostConfig, checkpoint string, checkpointDir string) error
<ide> ContainerStop(ctx context.Context, name string, config container.StopOptions) error
<ide> ContainerLogs(ctx context.Context, name string, config *types.ContainerLogsOptions) (msgs <-chan *backend.LogMessage, tty bool, err error)
<ide> ConnectContainerToNetwork(containerName, networkName string, endpointConfig *network.EndpointSettings) error
<ide> type Backend interface {
<ide> SetContainerSecretReferences(name string, refs []*swarm.SecretReference) error
<ide> SetContainerConfigReferences(name string, refs []*swarm.ConfigReference) error
<ide> SystemInfo() *types.Info
<del> Containers(config *types.ContainerListOptions) ([]*types.Container, error)
<add> Containers(ctx context.Context, config *types.ContainerListOptions) ([]*types.Container, error)
<ide> SetNetworkBootstrapKeys([]*networktypes.EncryptionKey) error
<ide> DaemonJoinsCluster(provider cluster.Provider)
<ide> DaemonLeavesCluster()
<ide><path>daemon/cluster/executor/container/adapter.go
<ide> func (c *containerAdapter) waitForDetach(ctx context.Context) error {
<ide> func (c *containerAdapter) create(ctx context.Context) error {
<ide> var cr containertypes.CreateResponse
<ide> var err error
<del> if cr, err = c.backend.CreateManagedContainer(types.ContainerCreateConfig{
<add> if cr, err = c.backend.CreateManagedContainer(ctx, types.ContainerCreateConfig{
<ide> Name: c.container.name(),
<ide> Config: c.container.config(),
<ide> HostConfig: c.container.hostConfig(c.dependencies.Volumes()),
<ide> func (c *containerAdapter) start(ctx context.Context) error {
<ide> return err
<ide> }
<ide>
<del> return c.backend.ContainerStart(c.container.name(), nil, "", "")
<add> return c.backend.ContainerStart(ctx, c.container.name(), nil, "", "")
<ide> }
<ide>
<ide> func (c *containerAdapter) inspect(ctx context.Context) (types.ContainerJSON, error) {
<ide><path>daemon/cluster/swarm.go
<ide> func (c *Cluster) UnlockSwarm(req types.UnlockRequest) error {
<ide> }
<ide>
<ide> // Leave shuts down Cluster and removes current state.
<del>func (c *Cluster) Leave(force bool) error {
<add>func (c *Cluster) Leave(ctx context.Context, force bool) error {
<ide> c.controlMutex.Lock()
<ide> defer c.controlMutex.Unlock()
<ide>
<ide> func (c *Cluster) Leave(force bool) error {
<ide> c.mu.Unlock()
<ide>
<ide> if nodeID := state.NodeID(); nodeID != "" {
<del> nodeContainers, err := c.listContainerForNode(nodeID)
<add> nodeContainers, err := c.listContainerForNode(ctx, nodeID)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func initClusterSpec(node *swarmnode.Node, spec types.Spec) error {
<ide> return ctx.Err()
<ide> }
<ide>
<del>func (c *Cluster) listContainerForNode(nodeID string) ([]string, error) {
<add>func (c *Cluster) listContainerForNode(ctx context.Context, nodeID string) ([]string, error) {
<ide> var ids []string
<ide> filters := filters.NewArgs()
<ide> filters.Add("label", fmt.Sprintf("com.docker.swarm.node.id=%s", nodeID))
<del> containers, err := c.config.Backend.Containers(&apitypes.ContainerListOptions{
<add> containers, err := c.config.Backend.Containers(ctx, &apitypes.ContainerListOptions{
<ide> Filters: filters,
<ide> })
<ide> if err != nil {
<ide><path>daemon/commit.go
<ide> package daemon // import "github.com/docker/docker/daemon"
<ide>
<ide> import (
<add> "context"
<ide> "fmt"
<ide> "runtime"
<ide> "strings"
<ide> func merge(userConf, imageConf *containertypes.Config) error {
<ide> // CreateImageFromContainer creates a new image from a container. The container
<ide> // config will be updated by applying the change set to the custom config, then
<ide> // applying that config over the existing container config.
<del>func (daemon *Daemon) CreateImageFromContainer(name string, c *backend.CreateImageConfig) (string, error) {
<add>func (daemon *Daemon) CreateImageFromContainer(ctx context.Context, name string, c *backend.CreateImageConfig) (string, error) {
<ide> start := time.Now()
<ide> container, err := daemon.GetContainer(name)
<ide> if err != nil {
<ide> func (daemon *Daemon) CreateImageFromContainer(name string, c *backend.CreateIma
<ide> if c.Config == nil {
<ide> c.Config = container.Config
<ide> }
<del> newConfig, err := dockerfile.BuildFromConfig(c.Config, c.Changes, container.OS)
<add> newConfig, err := dockerfile.BuildFromConfig(ctx, c.Config, c.Changes, container.OS)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide><path>daemon/containerd/cache.go
<ide> package containerd
<ide>
<ide> import (
<add> "context"
<add>
<ide> "github.com/docker/docker/builder"
<ide> )
<ide>
<ide> // MakeImageCache creates a stateful image cache.
<del>func (i *ImageService) MakeImageCache(cacheFrom []string) builder.ImageCache {
<add>func (i *ImageService) MakeImageCache(ctx context.Context, cacheFrom []string) (builder.ImageCache, error) {
<ide> panic("not implemented")
<ide> }
<ide><path>daemon/containerd/image_import.go
<ide> package containerd
<ide>
<ide> import (
<add> "context"
<ide> "errors"
<ide> "io"
<ide>
<ide> import (
<ide> // inConfig (if src is "-"), or from a URI specified in src. Progress output is
<ide> // written to outStream. Repository and tag names can optionally be given in
<ide> // the repo and tag arguments, respectively.
<del>func (i *ImageService) ImportImage(src string, repository string, platform *specs.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error {
<add>func (i *ImageService) ImportImage(ctx context.Context, src string, repository string, platform *specs.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error {
<ide> return errdefs.NotImplemented(errors.New("not implemented"))
<ide> }
<ide><path>daemon/create.go
<ide> type createOpts struct {
<ide> }
<ide>
<ide> // CreateManagedContainer creates a container that is managed by a Service
<del>func (daemon *Daemon) CreateManagedContainer(params types.ContainerCreateConfig) (containertypes.CreateResponse, error) {
<del> return daemon.containerCreate(createOpts{
<add>func (daemon *Daemon) CreateManagedContainer(ctx context.Context, params types.ContainerCreateConfig) (containertypes.CreateResponse, error) {
<add> return daemon.containerCreate(ctx, createOpts{
<ide> params: params,
<ide> managed: true,
<ide> })
<ide> }
<ide>
<ide> // ContainerCreate creates a regular container
<del>func (daemon *Daemon) ContainerCreate(params types.ContainerCreateConfig) (containertypes.CreateResponse, error) {
<del> return daemon.containerCreate(createOpts{
<add>func (daemon *Daemon) ContainerCreate(ctx context.Context, params types.ContainerCreateConfig) (containertypes.CreateResponse, error) {
<add> return daemon.containerCreate(ctx, createOpts{
<ide> params: params,
<ide> })
<ide> }
<ide>
<ide> // ContainerCreateIgnoreImagesArgsEscaped creates a regular container. This is called from the builder RUN case
<ide> // and ensures that we do not take the images ArgsEscaped
<del>func (daemon *Daemon) ContainerCreateIgnoreImagesArgsEscaped(params types.ContainerCreateConfig) (containertypes.CreateResponse, error) {
<del> return daemon.containerCreate(createOpts{
<add>func (daemon *Daemon) ContainerCreateIgnoreImagesArgsEscaped(ctx context.Context, params types.ContainerCreateConfig) (containertypes.CreateResponse, error) {
<add> return daemon.containerCreate(ctx, createOpts{
<ide> params: params,
<ide> ignoreImagesArgsEscaped: true,
<ide> })
<ide> }
<ide>
<del>func (daemon *Daemon) containerCreate(opts createOpts) (containertypes.CreateResponse, error) {
<del> ctx := context.TODO()
<add>func (daemon *Daemon) containerCreate(ctx context.Context, opts createOpts) (containertypes.CreateResponse, error) {
<ide> start := time.Now()
<ide> if opts.params.Config == nil {
<ide> return containertypes.CreateResponse{}, errdefs.InvalidParameter(errors.New("Config cannot be empty in order to create a container"))
<ide> func (daemon *Daemon) containerCreate(opts createOpts) (containertypes.CreateRes
<ide> return containertypes.CreateResponse{Warnings: warnings}, errdefs.InvalidParameter(err)
<ide> }
<ide>
<del> ctr, err := daemon.create(opts)
<add> ctr, err := daemon.create(ctx, opts)
<ide> if err != nil {
<ide> return containertypes.CreateResponse{Warnings: warnings}, err
<ide> }
<ide> func (daemon *Daemon) containerCreate(opts createOpts) (containertypes.CreateRes
<ide> }
<ide>
<ide> // Create creates a new container from the given configuration with a given name.
<del>func (daemon *Daemon) create(opts createOpts) (retC *container.Container, retErr error) {
<del> ctx := context.TODO()
<add>func (daemon *Daemon) create(ctx context.Context, opts createOpts) (retC *container.Container, retErr error) {
<ide> var (
<ide> ctr *container.Container
<ide> img *image.Image
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) restore() error {
<ide> if err := daemon.prepareMountPoints(c); err != nil {
<ide> log.WithError(err).Error("failed to prepare mount points for container")
<ide> }
<del> if err := daemon.containerStart(c, "", "", true); err != nil {
<add> if err := daemon.containerStart(context.Background(), c, "", "", true); err != nil {
<ide> log.WithError(err).Error("failed to start container")
<ide> }
<ide> close(chNotify)
<ide> func (daemon *Daemon) RestartSwarmContainers() {
<ide> return
<ide> }
<ide>
<del> if err := daemon.containerStart(c, "", "", true); err != nil {
<add> if err := daemon.containerStart(ctx, c, "", "", true); err != nil {
<ide> logrus.WithField("container", c.ID).WithError(err).Error("failed to start swarm container")
<ide> }
<ide>
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> // initialization
<ide> defer func() {
<ide> if err != nil {
<del> if err := d.Shutdown(); err != nil {
<add> // Use a fresh context here. Passed context could be cancelled.
<add> if err := d.Shutdown(context.Background()); err != nil {
<ide> logrus.Error(err)
<ide> }
<ide> }
<ide> func (daemon *Daemon) ShutdownTimeout() int {
<ide> }
<ide>
<ide> // Shutdown stops the daemon.
<del>func (daemon *Daemon) Shutdown() error {
<add>func (daemon *Daemon) Shutdown(ctx context.Context) error {
<ide> daemon.shutdown = true
<ide> // Keep mounts and networking running on daemon shutdown if
<ide> // we are to keep containers running and restore them.
<ide>
<ide> if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
<ide> // check if there are any running containers, if none we should do some cleanup
<del> if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
<add> if ls, err := daemon.Containers(ctx, &types.ContainerListOptions{}); len(ls) != 0 || err != nil {
<ide> // metrics plugins still need some cleanup
<ide> daemon.cleanupMetricsPlugins()
<del> return nil
<add> return err
<ide> }
<ide> }
<ide>
<ide><path>daemon/disk_usage.go
<ide> import (
<ide> func (daemon *Daemon) ContainerDiskUsage(ctx context.Context) ([]*types.Container, error) {
<ide> ch := daemon.usage.DoChan("ContainerDiskUsage", func() (interface{}, error) {
<ide> // Retrieve container list
<del> containers, err := daemon.Containers(&types.ContainerListOptions{
<add> containers, err := daemon.Containers(context.TODO(), &types.ContainerListOptions{
<ide> Size: true,
<ide> All: true,
<ide> })
<ide><path>daemon/image_service.go
<ide> type ImageService interface {
<ide> CountImages() int
<ide> ImageDiskUsage(ctx context.Context) ([]*types.ImageSummary, error)
<ide> ImagesPrune(ctx context.Context, pruneFilters filters.Args) (*types.ImagesPruneReport, error)
<del> ImportImage(src string, repository string, platform *v1.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error
<add> ImportImage(ctx context.Context, src string, repository string, platform *v1.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error
<ide> TagImage(imageName, repository, tag string) (string, error)
<ide> TagImageWithReference(imageID image.ID, newTag reference.Named) error
<ide> GetImage(ctx context.Context, refOrID string, options imagetype.GetImageOpts) (*image.Image, error)
<ide> type ImageService interface {
<ide>
<ide> // Build
<ide>
<del> MakeImageCache(sourceRefs []string) builder.ImageCache
<add> MakeImageCache(ctx context.Context, cacheFrom []string) (builder.ImageCache, error)
<ide> CommitBuildStep(c backend.CommitConfig) (image.ID, error)
<ide>
<ide> // Other
<ide><path>daemon/images/cache.go
<ide> import (
<ide> imagetypes "github.com/docker/docker/api/types/image"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/image/cache"
<add> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> // MakeImageCache creates a stateful image cache.
<del>func (i *ImageService) MakeImageCache(sourceRefs []string) builder.ImageCache {
<del> ctx := context.TODO()
<add>func (i *ImageService) MakeImageCache(ctx context.Context, sourceRefs []string) (builder.ImageCache, error) {
<ide> if len(sourceRefs) == 0 {
<del> return cache.NewLocal(i.imageStore)
<add> return cache.NewLocal(i.imageStore), nil
<ide> }
<ide>
<ide> cache := cache.New(i.imageStore)
<ide>
<ide> for _, ref := range sourceRefs {
<ide> img, err := i.GetImage(ctx, ref, imagetypes.GetImageOpts{})
<ide> if err != nil {
<add> if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
<add> return nil, err
<add> }
<ide> logrus.Warnf("Could not look up %s for cache resolution, skipping: %+v", ref, err)
<ide> continue
<ide> }
<ide> cache.Populate(img)
<ide> }
<ide>
<del> return cache
<add> return cache, nil
<ide> }
<ide><path>daemon/images/image_import.go
<ide> package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<add> "context"
<ide> "encoding/json"
<ide> "io"
<ide> "net/http"
<ide> import (
<ide> // inConfig (if src is "-"), or from a URI specified in src. Progress output is
<ide> // written to outStream. Repository and tag names can optionally be given in
<ide> // the repo and tag arguments, respectively.
<del>func (i *ImageService) ImportImage(src string, repository string, platform *specs.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error {
<add>func (i *ImageService) ImportImage(ctx context.Context, src string, repository string, platform *specs.Platform, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, changes []string) error {
<ide> var (
<ide> rc io.ReadCloser
<ide> resp *http.Response
<ide> func (i *ImageService) ImportImage(src string, repository string, platform *spec
<ide> if !system.IsOSSupported(platform.OS) {
<ide> return errdefs.InvalidParameter(system.ErrNotSupportedOperatingSystem)
<ide> }
<del> config, err := dockerfile.BuildFromConfig(&container.Config{}, changes, platform.OS)
<add> config, err := dockerfile.BuildFromConfig(ctx, &container.Config{}, changes, platform.OS)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>daemon/list.go
<ide> type iterationAction int
<ide>
<ide> // containerReducer represents a reducer for a container.
<ide> // Returns the object to serialize by the api.
<del>type containerReducer func(*container.Snapshot, *listContext) (*types.Container, error)
<add>type containerReducer func(context.Context, *container.Snapshot, *listContext) (*types.Container, error)
<ide>
<ide> const (
<ide> // includeContainer is the action to include a container in the reducer.
<ide> func (r byCreatedDescending) Less(i, j int) bool {
<ide> }
<ide>
<ide> // Containers returns the list of containers to show given the user's filtering.
<del>func (daemon *Daemon) Containers(config *types.ContainerListOptions) ([]*types.Container, error) {
<del> return daemon.reduceContainers(config, daemon.refreshImage)
<add>func (daemon *Daemon) Containers(ctx context.Context, config *types.ContainerListOptions) ([]*types.Container, error) {
<add> return daemon.reduceContainers(ctx, config, daemon.refreshImage)
<ide> }
<ide>
<ide> func (daemon *Daemon) filterByNameIDMatches(view *container.View, filter *listContext) ([]container.Snapshot, error) {
<ide> func (daemon *Daemon) filterByNameIDMatches(view *container.View, filter *listCo
<ide> }
<ide>
<ide> // reduceContainers parses the user's filtering options and generates the list of containers to return based on a reducer.
<del>func (daemon *Daemon) reduceContainers(config *types.ContainerListOptions, reducer containerReducer) ([]*types.Container, error) {
<add>func (daemon *Daemon) reduceContainers(ctx context.Context, config *types.ContainerListOptions, reducer containerReducer) ([]*types.Container, error) {
<ide> if err := config.Filters.Validate(acceptedPsFilterTags); err != nil {
<ide> return nil, err
<ide> }
<ide> func (daemon *Daemon) reduceContainers(config *types.ContainerListOptions, reduc
<ide> containers = []*types.Container{}
<ide> )
<ide>
<del> filter, err := daemon.foldFilter(view, config)
<add> filter, err := daemon.foldFilter(ctx, view, config)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (daemon *Daemon) reduceContainers(config *types.ContainerListOptions, reduc
<ide> }
<ide>
<ide> for i := range containerList {
<del> t, err := daemon.reducePsContainer(&containerList[i], filter, reducer)
<add> t, err := daemon.reducePsContainer(ctx, &containerList[i], filter, reducer)
<ide> if err != nil {
<ide> if err != errStopIteration {
<ide> return nil, err
<ide> func (daemon *Daemon) reduceContainers(config *types.ContainerListOptions, reduc
<ide> }
<ide>
<ide> // reducePsContainer is the basic representation for a container as expected by the ps command.
<del>func (daemon *Daemon) reducePsContainer(container *container.Snapshot, filter *listContext, reducer containerReducer) (*types.Container, error) {
<add>func (daemon *Daemon) reducePsContainer(ctx context.Context, container *container.Snapshot, filter *listContext, reducer containerReducer) (*types.Container, error) {
<ide> // filter containers to return
<ide> switch includeContainerInList(container, filter) {
<ide> case excludeContainer:
<ide> func (daemon *Daemon) reducePsContainer(container *container.Snapshot, filter *l
<ide> }
<ide>
<ide> // transform internal container struct into api structs
<del> newC, err := reducer(container, filter)
<add> newC, err := reducer(ctx, container, filter)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (daemon *Daemon) reducePsContainer(container *container.Snapshot, filter *l
<ide> }
<ide>
<ide> // foldFilter generates the container filter based on the user's filtering options.
<del>func (daemon *Daemon) foldFilter(view *container.View, config *types.ContainerListOptions) (*listContext, error) {
<del> ctx := context.TODO()
<add>func (daemon *Daemon) foldFilter(ctx context.Context, view *container.View, config *types.ContainerListOptions) (*listContext, error) {
<ide> psFilters := config.Filters
<ide>
<ide> var filtExited []int
<ide> func includeContainerInList(container *container.Snapshot, filter *listContext)
<ide> }
<ide>
<ide> // refreshImage checks if the Image ref still points to the correct ID, and updates the ref to the actual ID when it doesn't
<del>func (daemon *Daemon) refreshImage(s *container.Snapshot, filter *listContext) (*types.Container, error) {
<del> ctx := context.TODO()
<add>func (daemon *Daemon) refreshImage(ctx context.Context, s *container.Snapshot, filter *listContext) (*types.Container, error) {
<ide> c := s.Container
<ide> tmpImage := s.Image // keep the original ref if still valid (hasn't changed)
<ide> if tmpImage != s.ImageID {
<ide><path>daemon/list_test.go
<ide> package daemon
<ide>
<ide> import (
<add> "context"
<ide> "os"
<ide> "path/filepath"
<ide> "testing"
<ide> func TestListInvalidFilter(t *testing.T) {
<ide>
<ide> f := filters.NewArgs(filters.Arg("invalid", "foo"))
<ide>
<del> _, err = d.Containers(&types.ContainerListOptions{
<add> _, err = d.Containers(context.Background(), &types.ContainerListOptions{
<ide> Filters: f,
<ide> })
<ide> assert.Assert(t, is.Error(err, "invalid filter 'invalid'"))
<ide> func TestNameFilter(t *testing.T) {
<ide>
<ide> // moby/moby #37453 - ^ regex not working due to prefix slash
<ide> // not being stripped
<del> containerList, err := d.Containers(&types.ContainerListOptions{
<add> containerList, err := d.Containers(context.Background(), &types.ContainerListOptions{
<ide> Filters: filters.NewArgs(filters.Arg("name", "^a")),
<ide> })
<ide> assert.NilError(t, err)
<ide> func TestNameFilter(t *testing.T) {
<ide> assert.Assert(t, containerListContainsName(containerList, two.Name))
<ide>
<ide> // Same as above but with slash prefix should produce the same result
<del> containerListWithPrefix, err := d.Containers(&types.ContainerListOptions{
<add> containerListWithPrefix, err := d.Containers(context.Background(), &types.ContainerListOptions{
<ide> Filters: filters.NewArgs(filters.Arg("name", "^/a")),
<ide> })
<ide> assert.NilError(t, err)
<ide> func TestNameFilter(t *testing.T) {
<ide> assert.Assert(t, containerListContainsName(containerListWithPrefix, two.Name))
<ide>
<ide> // Same as above but make sure it works for exact names
<del> containerList, err = d.Containers(&types.ContainerListOptions{
<add> containerList, err = d.Containers(context.Background(), &types.ContainerListOptions{
<ide> Filters: filters.NewArgs(filters.Arg("name", "b1")),
<ide> })
<ide> assert.NilError(t, err)
<ide> assert.Assert(t, is.Len(containerList, 1))
<ide> assert.Assert(t, containerListContainsName(containerList, three.Name))
<ide>
<ide> // Same as above but with slash prefix should produce the same result
<del> containerListWithPrefix, err = d.Containers(&types.ContainerListOptions{
<add> containerListWithPrefix, err = d.Containers(context.Background(), &types.ContainerListOptions{
<ide> Filters: filters.NewArgs(filters.Arg("name", "/b1")),
<ide> })
<ide> assert.NilError(t, err)
<ide><path>daemon/monitor.go
<ide> func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontaine
<ide> // But containerStart will use daemon.netController segment.
<ide> // So to avoid panic at startup process, here must wait util daemon restore done.
<ide> daemon.waitForStartupDone()
<del> if err = daemon.containerStart(c, "", "", false); err != nil {
<add> if err = daemon.containerStart(context.Background(), c, "", "", false); err != nil {
<ide> logrus.Debugf("failed to restart container: %+v", err)
<ide> }
<ide> }
<ide><path>daemon/oci_linux.go
<ide> func WithUser(c *container.Container) coci.SpecOpts {
<ide> }
<ide> }
<ide>
<del>func (daemon *Daemon) createSpec(c *container.Container) (retSpec *specs.Spec, err error) {
<add>func (daemon *Daemon) createSpec(ctx context.Context, c *container.Container) (retSpec *specs.Spec, err error) {
<ide> var (
<ide> opts []coci.SpecOpts
<ide> s = oci.DefaultSpec()
<ide> func (daemon *Daemon) createSpec(c *container.Container) (retSpec *specs.Spec, e
<ide> snapshotKey = c.ID
<ide> }
<ide>
<del> return &s, coci.ApplyOpts(context.Background(), nil, &containers.Container{
<add> return &s, coci.ApplyOpts(ctx, nil, &containers.Container{
<ide> ID: c.ID,
<ide> Snapshotter: snapshotter,
<ide> SnapshotKey: snapshotKey,
<ide><path>daemon/oci_linux_test.go
<ide> package daemon // import "github.com/docker/docker/daemon"
<ide>
<ide> import (
<add> "context"
<ide> "os"
<ide> "path/filepath"
<ide> "testing"
<ide> func TestTmpfsDevShmNoDupMount(t *testing.T) {
<ide> d := setupFakeDaemon(t, c)
<ide> defer cleanupFakeContainer(c)
<ide>
<del> _, err := d.createSpec(c)
<add> _, err := d.createSpec(context.TODO(), c)
<ide> assert.Check(t, err)
<ide> }
<ide>
<ide> func TestIpcPrivateVsReadonly(t *testing.T) {
<ide> d := setupFakeDaemon(t, c)
<ide> defer cleanupFakeContainer(c)
<ide>
<del> s, err := d.createSpec(c)
<add> s, err := d.createSpec(context.TODO(), c)
<ide> assert.Check(t, err)
<ide>
<ide> // Find the /dev/shm mount in ms, check it does not have ro
<ide> func TestSysctlOverride(t *testing.T) {
<ide> defer cleanupFakeContainer(c)
<ide>
<ide> // Ensure that the implicit sysctl is set correctly.
<del> s, err := d.createSpec(c)
<add> s, err := d.createSpec(context.TODO(), c)
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, s.Hostname, "foobar")
<ide> assert.Equal(t, s.Linux.Sysctl["kernel.domainname"], c.Config.Domainname)
<ide> func TestSysctlOverride(t *testing.T) {
<ide> assert.Assert(t, c.HostConfig.Sysctls["kernel.domainname"] != c.Config.Domainname)
<ide> c.HostConfig.Sysctls["net.ipv4.ip_unprivileged_port_start"] = "1024"
<ide>
<del> s, err = d.createSpec(c)
<add> s, err = d.createSpec(context.TODO(), c)
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, s.Hostname, "foobar")
<ide> assert.Equal(t, s.Linux.Sysctl["kernel.domainname"], c.HostConfig.Sysctls["kernel.domainname"])
<ide> assert.Equal(t, s.Linux.Sysctl["net.ipv4.ip_unprivileged_port_start"], c.HostConfig.Sysctls["net.ipv4.ip_unprivileged_port_start"])
<ide>
<ide> // Ensure the ping_group_range is not set on a daemon with user-namespaces enabled
<ide> d.configStore.RemappedRoot = "dummy:dummy"
<del> s, err = d.createSpec(c)
<add> s, err = d.createSpec(context.TODO(), c)
<ide> assert.NilError(t, err)
<ide> _, ok := s.Linux.Sysctl["net.ipv4.ping_group_range"]
<ide> assert.Assert(t, !ok)
<ide>
<ide> // Ensure the ping_group_range is set on a container in "host" userns mode
<ide> // on a daemon with user-namespaces enabled
<ide> c.HostConfig.UsernsMode = "host"
<del> s, err = d.createSpec(c)
<add> s, err = d.createSpec(context.TODO(), c)
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, s.Linux.Sysctl["net.ipv4.ping_group_range"], "0 2147483647")
<ide> }
<ide> func TestSysctlOverrideHost(t *testing.T) {
<ide> defer cleanupFakeContainer(c)
<ide>
<ide> // Ensure that the implicit sysctl is not set
<del> s, err := d.createSpec(c)
<add> s, err := d.createSpec(context.TODO(), c)
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, s.Linux.Sysctl["net.ipv4.ip_unprivileged_port_start"], "")
<ide> assert.Equal(t, s.Linux.Sysctl["net.ipv4.ping_group_range"], "")
<ide>
<ide> // Set an explicit sysctl.
<ide> c.HostConfig.Sysctls["net.ipv4.ip_unprivileged_port_start"] = "1024"
<ide>
<del> s, err = d.createSpec(c)
<add> s, err = d.createSpec(context.TODO(), c)
<ide> assert.NilError(t, err)
<ide> assert.Equal(t, s.Linux.Sysctl["net.ipv4.ip_unprivileged_port_start"], c.HostConfig.Sysctls["net.ipv4.ip_unprivileged_port_start"])
<ide> }
<ide><path>daemon/oci_windows.go
<ide> const (
<ide> credentialSpecFileLocation = "CredentialSpecs"
<ide> )
<ide>
<del>func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
<del> ctx := context.TODO()
<add>func (daemon *Daemon) createSpec(ctx context.Context, c *container.Container) (*specs.Spec, error) {
<ide> img, err := daemon.imageService.GetImage(ctx, string(c.ImageID), imagetypes.GetImageOpts{})
<ide> if err != nil {
<ide> return nil, err
<ide><path>daemon/restart.go
<ide> func (daemon *Daemon) containerRestart(ctx context.Context, container *container
<ide> }
<ide> }
<ide>
<del> if err := daemon.containerStart(container, "", "", true); err != nil {
<add> if err := daemon.containerStart(ctx, container, "", "", true); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>daemon/start.go
<ide> import (
<ide> )
<ide>
<ide> // ContainerStart starts a container.
<del>func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.HostConfig, checkpoint string, checkpointDir string) error {
<add>func (daemon *Daemon) ContainerStart(ctx context.Context, name string, hostConfig *containertypes.HostConfig, checkpoint string, checkpointDir string) error {
<ide> if checkpoint != "" && !daemon.HasExperimental() {
<ide> return errdefs.InvalidParameter(errors.New("checkpoint is only supported in experimental mode"))
<ide> }
<ide> func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.Hos
<ide> return errdefs.InvalidParameter(err)
<ide> }
<ide> }
<del> return daemon.containerStart(ctr, checkpoint, checkpointDir, true)
<add> return daemon.containerStart(ctx, ctr, checkpoint, checkpointDir, true)
<ide> }
<ide>
<ide> // containerStart prepares the container to run by setting up everything the
<ide> // container needs, such as storage and networking, as well as links
<ide> // between containers. The container is left waiting for a signal to
<ide> // begin running.
<del>func (daemon *Daemon) containerStart(container *container.Container, checkpoint string, checkpointDir string, resetRestartManager bool) (err error) {
<add>func (daemon *Daemon) containerStart(ctx context.Context, container *container.Container, checkpoint string, checkpointDir string, resetRestartManager bool) (err error) {
<ide> start := time.Now()
<ide> container.Lock()
<ide> defer container.Unlock()
<ide> func (daemon *Daemon) containerStart(container *container.Container, checkpoint
<ide> return err
<ide> }
<ide>
<del> spec, err := daemon.createSpec(container)
<add> spec, err := daemon.createSpec(ctx, container)
<ide> if err != nil {
<ide> return errdefs.System(err)
<ide> }
<ide> func (daemon *Daemon) containerStart(container *container.Container, checkpoint
<ide> return err
<ide> }
<ide>
<del> ctx := context.TODO()
<del>
<ide> ctr, err := libcontainerd.ReplaceContainer(ctx, daemon.containerd, container.ID, spec, shim, createOptions)
<ide> if err != nil {
<ide> return translateContainerdStartErr(container.Path, container.SetExitCode, err)
| 40
|
Javascript
|
Javascript
|
fix circular dependency in tracingsubscriptions
|
e1a067dea0ffcacd1f664f30cd14463b00f52fa7
|
<ide><path>packages/scheduler/src/TracingSubscriptions.js
<ide> import type {Interaction, Subscriber} from './Tracing';
<ide>
<ide> import {enableSchedulerTracing} from 'shared/ReactFeatureFlags';
<del>import {__subscriberRef} from 'scheduler/tracing';
<add>import {__subscriberRef} from './Tracing';
<ide>
<ide> let subscribers: Set<Subscriber> = (null: any);
<ide> if (enableSchedulerTracing) {
| 1
|
Go
|
Go
|
pass store test-unit
|
32b905d90ff133c92bb0dd89207a68c45fc81bbd
|
<ide><path>volume/store/store_test.go
<ide> func TestCreate(t *testing.T) {
<ide> t.Fatalf("Expected unknown driver error, got nil")
<ide> }
<ide>
<del> _, err = s.Create("fakeError", "fake", map[string]string{"error": "create error"})
<del> expected := &OpErr{Op: "create", Name: "fakeError", Err: errors.New("create error")}
<add> _, err = s.Create("fakeerror", "fake", map[string]string{"error": "create error"})
<add> expected := &OpErr{Op: "create", Name: "fakeerror", Err: errors.New("create error")}
<ide> if err != nil && err.Error() != expected.Error() {
<ide> t.Fatalf("Expected create fakeError: create error, got %v", err)
<ide> }
| 1
|
Text
|
Text
|
add links to platform specific mechanisms
|
138c7af42a8f8dd0b8f9b69ddc406eba16c71874
|
<ide><path>doc/api/fs.md
<ide> The recursive option is only supported on OS X and Windows.
<ide> This feature depends on the underlying operating system providing a way
<ide> to be notified of filesystem changes.
<ide>
<del>* On Linux systems, this uses `inotify`.
<del>* On BSD systems, this uses `kqueue`.
<del>* On OS X, this uses `kqueue` for files and 'FSEvents' for directories.
<del>* On SunOS systems (including Solaris and SmartOS), this uses `event ports`.
<del>* On Windows systems, this feature depends on `ReadDirectoryChangesW`.
<del>* On Aix systems, this feature depends on `AHAFS`, which must be enabled.
<add>* On Linux systems, this uses [`inotify`]
<add>* On BSD systems, this uses [`kqueue`]
<add>* On OS X, this uses [`kqueue`] for files and [`FSEvents`] for directories.
<add>* On SunOS systems (including Solaris and SmartOS), this uses [`event ports`].
<add>* On Windows systems, this feature depends on [`ReadDirectoryChangesW`].
<add>* On Aix systems, this feature depends on [`AHAFS`], which must be enabled.
<ide>
<ide> If the underlying functionality is not available for some reason, then
<ide> `fs.watch` will not be able to function. For example, watching files or
<ide> The following constants are meant for use with the [`fs.Stats`][] object's
<ide> [Writable Stream]: stream.html#stream_class_stream_writable
<ide> [inode]: http://www.linux.org/threads/intro-to-inodes.4130
<ide> [FS Constants]: #fs_fs_constants
<add>[`inotify`]: http://man7.org/linux/man-pages/man7/inotify.7.html
<add>[`kqueue`]: https://www.freebsd.org/cgi/man.cgi?kqueue
<add>[`FSEvents`]: https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005289-CH1-SW1
<add>[`event ports`]: http://illumos.org/man/port_create
<add>[`ReadDirectoryChangesW`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v=vs.85%29.aspx
<add>[`AHAFS`]: https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/
| 1
|
Javascript
|
Javascript
|
fix fuzziness images in uiexplorer <image> sample
|
3643c127a8f752c8cdbb8377baab266fba06d067
|
<ide><path>Examples/UIExplorer/ImageExample.js
<ide> exports.examples = [
<ide> ];
<ide>
<ide> var fullImage = {uri: 'http://facebook.github.io/react/img/logo_og.png'};
<del>var smallImage = {uri: 'http://facebook.github.io/react/img/logo_small.png'};
<add>var smallImage = {uri: 'http://facebook.github.io/react/img/logo_small_2x.png'};
<ide>
<ide> var styles = StyleSheet.create({
<ide> base: {
| 1
|
Javascript
|
Javascript
|
add test for linux perf
|
227ca87abb9c3a30e13152426c0efc442d908345
|
<ide><path>test/fixtures/linux-perf.js
<add>'use strict';
<add>
<add>const crypto = require('crypto');
<add>
<add>// Functions should be complex enough for V8 to run them a few times before
<add>// compiling, but not complex enough to always stay in interpreted mode. They
<add>// should also take some time to run, otherwise Linux perf might miss them
<add>// entirely even when sampling at a high frequency.
<add>function functionOne(i) {
<add> for (let j=i; j > 0; j--) {
<add> crypto.createHash('md5').update(functionTwo(i, j)).digest("hex");
<add> }
<add>}
<add>
<add>function functionTwo(x, y) {
<add> let data = ((((x * y) + (x / y)) * y) ** (x + 1)).toString();
<add> if (x % 2 == 0) {
<add> return crypto.createHash('md5').update(data.repeat((x % 100) + 1)).digest("hex");
<add> } else {
<add> return crypto.createHash('md5').update(data.repeat((y % 100) + 1)).digest("hex");
<add> }
<add>}
<add>
<add>for (let i = 0; i < 1000; i++) {
<add> functionOne(i);
<add>}
<ide><path>test/v8-updates/test-linux-perf.js
<add>'use strict';
<add>
<add>// This test verifies that JavaScript functions are being correctly sampled by
<add>// Linux perf. The test runs a JavaScript script, sampling the execution with
<add>// Linux perf. It then uses `perf script` to generate a human-readable output,
<add>// and uses regular expressions to find samples of the functions defined in
<add>// `fixtures/linux-perf.js`.
<add>
<add>// NOTE (mmarchini): this test is meant to run only on Linux machines with Linux
<add>// perf installed. It will skip if those criteria are not met.
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>const assert = require('assert');
<add>const { spawnSync } = require('child_process');
<add>const fixtures = require('../common/fixtures');
<add>const tmpdir = require('../common/tmpdir');
<add>tmpdir.refresh();
<add>
<add>if (process.config.variables.node_shared)
<add> common.skip("can't test Linux perf with shared libraries yet");
<add>
<add>const perfArgs = [
<add> 'record',
<add> '-F500',
<add> '-g',
<add> '--',
<add> process.execPath,
<add> '--perf-basic-prof',
<add> '--interpreted-frames-native-stack',
<add> '--no-turbo-inlining', // Otherwise simple functions might get inlined.
<add> fixtures.path('linux-perf.js'),
<add>];
<add>
<add>const perfScriptArgs = [
<add> 'script',
<add>];
<add>
<add>const options = {
<add> cwd: tmpdir.path,
<add> encoding: 'utf-8',
<add>};
<add>
<add>if (!common.isLinux)
<add> common.skip('only testing Linux for now');
<add>
<add>const perf = spawnSync('perf', perfArgs, options);
<add>
<add>if (perf.error && perf.error.errno === 'ENOENT')
<add> common.skip('perf not found on system');
<add>
<add>if (perf.status !== 0) {
<add> common.skip(`Failed to execute perf: ${perf.stderr}`);
<add>}
<add>
<add>const perfScript = spawnSync('perf', perfScriptArgs, options);
<add>
<add>if (perf.error)
<add> common.skip(`perf script aborted: ${perf.error.errno}`);
<add>
<add>if (perfScript.status !== 0) {
<add> common.skip(`Failed to execute perf script: ${perfScript.stderr}`);
<add>}
<add>
<add>const interpretedFunctionOneRe = /InterpretedFunction:functionOne/;
<add>const compiledFunctionOneRe = /LazyCompile:\*functionOne/;
<add>const interpretedFunctionTwoRe = /InterpretedFunction:functionTwo/;
<add>const compiledFunctionTwoRe = /LazyCompile:\*functionTwo/;
<add>
<add>const output = perfScript.stdout;
<add>
<add>assert.ok(output.match(interpretedFunctionOneRe),
<add> "Couldn't find interpreted functionOne()");
<add>assert.ok(output.match(compiledFunctionOneRe),
<add> "Couldn't find compiled functionOne()");
<add>assert.ok(output.match(interpretedFunctionTwoRe),
<add> "Couldn't find interpreted functionTwo()");
<add>assert.ok(output.match(compiledFunctionTwoRe),
<add> "Couldn't find compiled functionTwo");
| 2
|
Javascript
|
Javascript
|
remove chart.scale property (always undefined)
|
4d99658155cdf3d504749b43cdc3ab71ab1d18d6
|
<ide><path>src/core/core.controller.js
<ide> class Chart {
<ide> this._responsiveListeners = undefined;
<ide> this._sortedMetasets = [];
<ide> this.scales = {};
<del> this.scale = undefined;
<ide> this._plugins = new PluginService();
<ide> this.$proxies = {};
<ide> this._hiddenIndices = {};
| 1
|
Ruby
|
Ruby
|
add tex requirement
|
2d445d54b5110e03b6a089fed25865f1d02bfed4
|
<ide><path>Library/Homebrew/dependencies.rb
<ide> def parse_symbol_spec spec, tag
<ide> MysqlInstalled.new(tag)
<ide> when :postgresql
<ide> PostgresqlInstalled.new(tag)
<add> when :tex
<add> TeXInstalled.new(tag)
<ide> else
<ide> raise "Unsupported special dependency #{spec}"
<ide> end
<ide><path>Library/Homebrew/requirements.rb
<ide> def message
<ide> EOS
<ide> end
<ide> end
<add>
<add>class TeXInstalled < Requirement
<add> fatal true
<add> env :userpaths
<add>
<add> def satisfied?
<add> tex = which 'tex'
<add> latex = which 'latex'
<add> not tex.nil? and not latex.nil?
<add> end
<add>
<add> def message; <<-EOS.undent
<add> A LaTeX distribution is required to install.
<add>
<add> You can install MacTeX distribution from:
<add> http://www.tug.org/mactex/
<add>
<add> Make sure that its bin directory is in your PATH before proceed.
<add>
<add> You may also need to restore the ownership of Homebrew install:
<add> sudo chown -R $USER `brew --prefix`
<add> EOS
<add> end
<add>end
| 2
|
Text
|
Text
|
fix markdown syntax and html tag misses
|
17d0830cf88137eed940f81e4b86ad044d2b02da
|
<ide><path>doc/api/cli.md
<ide> warning will be written to stderr instead.
<ide>
<ide> The `file` name may be an absolute path. If it is not, the default directory it
<ide> will be written to is controlled by the
<del>[`--diagnostic-dir`]() command-line option.
<add>[`--diagnostic-dir`][] command-line option.
<ide>
<ide> ### `--report-compact`
<ide>
<ide><path>doc/api/crypto.md
<ide> See the [list of SSL OP Flags][] for details.
<ide> <td><code>SSL_OP_NO_TLSv1_3</code></td>
<ide> <td>Instructs OpenSSL to turn off TLS v1.3</td>
<ide> </tr>
<add> <tr>
<ide> <td><code>SSL_OP_PKCS1_CHECK_1</code></td>
<ide> <td></td>
<ide> </tr>
<ide> See the [list of SSL OP Flags][] for details.
<ide> <td>Instructs OpenSSL to always create a new key when using
<ide> temporary/ephemeral ECDH parameters.</td>
<ide> </tr>
<add> <tr>
<ide> <td><code>SSL_OP_SSLEAY_080_CLIENT_DH_BUG</code></td>
<ide> <td></td>
<ide> </tr>
<ide><path>doc/api/dns.md
<ide> records. The type and structure of individual results varies based on `rrtype`:
<ide> | `'TXT'` | text records | {string\[]} | [`dns.resolveTxt()`][] |
<ide>
<ide> On error, `err` is an [`Error`][] object, where `err.code` is one of the
<del>[DNS error codes]().
<add>[DNS error codes][].
<ide>
<ide> ## `dns.resolve4(hostname[, options], callback)`
<ide>
<ide> based on `rrtype`:
<ide> | `'TXT'` | text records | {string\[]} | [`dnsPromises.resolveTxt()`][] |
<ide>
<ide> On error, the `Promise` is rejected with an [`Error`][] object, where `err.code`
<del>is one of the [DNS error codes]().
<add>is one of the [DNS error codes][].
<ide>
<ide> ### `dnsPromises.resolve4(hostname[, options])`
<ide>
<ide> Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
<ide> array of host names.
<ide>
<ide> On error, the `Promise` is rejected with an [`Error`][] object, where `err.code`
<del>is one of the [DNS error codes]().
<add>is one of the [DNS error codes][].
<ide>
<ide> ### `dnsPromises.setDefaultResultOrder(order)`
<ide>
<ide><path>doc/api/os.md
<ide> The following error constants are exported by `os.constants.errno`.
<ide> </tr>
<ide> <tr>
<ide> <td><code>EXDEV</code></td>
<del> <td>Indicates an improper link.
<add> <td>Indicates an improper link.</td>
<ide> </tr>
<ide> </table>
<ide>
<ide><path>doc/api/tls.md
<ide> The `'secure'` event is emitted by the `SecurePair` object once a secure
<ide> connection has been established.
<ide>
<ide> As with checking for the server
<del>[`'secureConnection'`]()
<add>[`'secureConnection'`][]
<ide> event, `pair.cleartext.authorized` should be inspected to confirm whether the
<ide> certificate used is properly authorized.
<ide>
| 5
|
Javascript
|
Javascript
|
add message to warn users before changing name
|
c2e7809ccdeaed55aef9e4543b3bc0e90d21547b
|
<ide><path>client/src/components/settings/Username.js
<ide> const mapDispatchToProps = dispatch =>
<ide> const invalidCharsRE = /[/\s?:@=&"'<>#%{}|\\^~[\]`,.;!*()$]/;
<ide> const invlaidCharError = {
<ide> valid: false,
<del> error: 'Username contains invalid characters'
<add> error: 'Username contains invalid characters.'
<ide> };
<ide> const valididationSuccess = { valid: true, error: null };
<ide> const usernameTooShort = { valid: false, error: 'Username is too short' };
<ide>
<add>const hex = '[0-9a-f]';
<add>const tempUserRegex = new RegExp(`^fcc${hex}{8}-(${hex}{4}-){3}${hex}{12}$`);
<add>
<ide> class UsernameSettings extends Component {
<ide> constructor(props) {
<ide> super(props);
<ide> class UsernameSettings extends Component {
<ide> isFormPristine: true,
<ide> formValue: props.username,
<ide> characterValidation: { valid: false, error: null },
<del> submitClicked: false
<add> submitClicked: false,
<add> isUserNew: tempUserRegex.test(props.username)
<ide> };
<ide>
<ide> this.handleChange = this.handleChange.bind(this);
<ide> class UsernameSettings extends Component {
<ide> /* eslint-disable-next-line react/no-did-update-set-state */
<ide> return this.setState({
<ide> isFormPristine: username === formValue,
<del> submitClicked: false
<add> submitClicked: false,
<add> isUserNew: tempUserRegex.test(username)
<ide> });
<ide> }
<ide> return null;
<ide> class UsernameSettings extends Component {
<ide> if (!validating && !isValidUsername) {
<ide> return (
<ide> <FullWidthRow>
<del> <Alert bsStyle='warning'>Username not available</Alert>
<add> <Alert bsStyle='warning'>Username not available.</Alert>
<ide> </FullWidthRow>
<ide> );
<ide> }
<ide> if (validating) {
<ide> return (
<ide> <FullWidthRow>
<del> <Alert bsStyle='info'>Validating username</Alert>
<add> <Alert bsStyle='info'>Validating username...</Alert>
<ide> </FullWidthRow>
<ide> );
<ide> }
<del> if (!validating && isValidUsername) {
<add> if (!validating && isValidUsername && this.state.isUserNew) {
<add> return (
<add> <FullWidthRow>
<add> <Alert bsStyle='success'>Username is available.</Alert>
<add> </FullWidthRow>
<add> );
<add> } else if (!validating && isValidUsername && !this.state.isUserNew) {
<ide> return (
<ide> <FullWidthRow>
<del> <Alert bsStyle='success'>Username is available</Alert>
<add> <Alert bsStyle='success'>Username is available.</Alert>
<add> <Alert bsStyle='info'>
<add> Please note, changing your username will also change the URL to your
<add> profile and your certifications.
<add> </Alert>
<ide> </FullWidthRow>
<ide> );
<ide> }
| 1
|
Ruby
|
Ruby
|
remove bad exit status; need to fix another way
|
cd13553d5906b89258d1504329afc4b587967631
|
<ide><path>Library/Homebrew/cmd/install.rb
<ide> def install_formulae formulae
<ide> fi.finish
<ide> rescue CannotInstallFormulaError => e
<ide> onoe e.message
<del> exit 1
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade_formula f
<ide> installer.finish
<ide> rescue CannotInstallFormulaError => e
<ide> onoe e
<del> exit 1
<ide> rescue BuildError => e
<ide> e.dump
<ide> puts
<del> exit 1
<ide> ensure
<ide> # restore previous installation state if build failed
<ide> outdated_keg.link if outdated_keg and not f.installed? rescue nil
| 2
|
Javascript
|
Javascript
|
enforce component name
|
14cd15ef54dc944fcb090eba924e4c92db14a445
|
<ide><path>jest/mockComponent.js
<ide> module.exports = (moduleName, instanceMethods) => {
<ide> typeof RealComponent === 'function' ? RealComponent : React.Component;
<ide>
<ide> const Component = class extends SuperClass {
<add> static displayName = 'Component';
<add>
<ide> render() {
<ide> const name =
<ide> RealComponent.displayName ||
| 1
|
Java
|
Java
|
add log to view that is being dropped
|
0d7a0dc9976b179fab8ee1b77c9b9faf85f7d828
|
<ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java
<ide> public class ReactFeatureFlags {
<ide> * C++ CatalystInstanceImpl
<ide> */
<ide> public static boolean useTurboModules = false;
<add>
<add> /**
<add> * Log tags of when a view deleted on the native side
<add> * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView}
<add> */
<add> public static boolean logDroppedViews = false;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.bridge.SoftAssertions;
<ide> import com.facebook.react.bridge.UiThreadUtil;
<add>import com.facebook.react.config.ReactFeatureFlags;
<ide> import com.facebook.react.touch.JSResponderHandler;
<ide> import com.facebook.react.uimanager.layoutanimation.LayoutAnimationController;
<ide> import com.facebook.react.uimanager.layoutanimation.LayoutAnimationListener;
<ide> import com.facebook.systrace.Systrace;
<ide> import com.facebook.systrace.SystraceMessage;
<add>import java.util.Arrays;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide> import javax.annotation.Nullable;
<ide> public class NativeViewHierarchyManager {
<ide> private final RootViewManager mRootViewManager;
<ide> private final LayoutAnimationController mLayoutAnimator = new LayoutAnimationController();
<ide> private final Map<Integer, SparseIntArray> mTagsToPendingIndicesToDelete = new HashMap<>();
<add> private final int[] mDroppedViewArray = new int[100];
<ide>
<ide> private boolean mLayoutAnimationEnabled;
<ide> private PopupMenu mPopupMenu;
<add> private int mDroppedViewIndex = 0;
<ide>
<ide> public NativeViewHierarchyManager(ViewManagerRegistry viewManagers) {
<ide> this(viewManagers, new RootViewManager());
<ide> public synchronized final View resolveView(int tag) {
<ide> public synchronized final ViewManager resolveViewManager(int tag) {
<ide> ViewManager viewManager = mTagsToViewManagers.get(tag);
<ide> if (viewManager == null) {
<del> throw new IllegalViewOperationException("ViewManager for tag " + tag + " could not be found");
<add> boolean alreadyDropped = Arrays.asList(mDroppedViewArray).contains(tag);
<add> throw new IllegalViewOperationException("ViewManager for tag "
<add> + tag + " could not be found.\n View already dropped? "
<add> + alreadyDropped + ".\nLast index "+ mDroppedViewIndex + " in last 100 views"
<add> + mDroppedViewArray.toString());
<ide> }
<ide> return viewManager;
<ide> }
<ide> protected synchronized final void addRootViewGroup(int tag, View view) {
<ide> view.setId(tag);
<ide> }
<ide>
<add> private void cacheDroppedTag(int tag) {
<add> mDroppedViewArray[mDroppedViewIndex] = tag;
<add> mDroppedViewIndex = (mDroppedViewIndex + 1) % 100;
<add> }
<add>
<ide> /**
<ide> * Releases all references to given native View.
<ide> */
<ide> protected synchronized void dropView(View view) {
<ide> // Ignore this drop operation when view is null.
<ide> return;
<ide> }
<add> if (ReactFeatureFlags.logDroppedViews) {
<add> cacheDroppedTag(view.getId());
<add> }
<ide> if (mTagsToViewManagers.get(view.getId()) == null) {
<ide> // This view has already been dropped (likely due to a threading issue caused by async js
<ide> // execution). Ignore this drop operation.
| 2
|
Javascript
|
Javascript
|
remove uneeded closures
|
4e55ea5acce9798d9fc7d4f54bb6c1746be4e693
|
<ide><path>packages/ember-handlebars/lib/helpers/binding.js
<ide> var forEach = Ember.ArrayPolyfills.forEach;
<ide>
<ide> var EmberHandlebars = Ember.Handlebars, helpers = EmberHandlebars.helpers;
<ide>
<add>function exists(value){
<add> return !Ember.isNone(value);
<add>}
<add>
<ide> // Binds a property into the DOM. This will create a hook in DOM that the
<ide> // KVO system will look for and update if the property changes.
<ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer, childProperties) {
<ide> EmberHandlebars.registerHelper('bind', function(property, options) {
<ide> return simpleBind.call(context, property, options);
<ide> }
<ide>
<del> return bind.call(context, property, options, false, function(result) {
<del> return !Ember.isNone(result);
<del> });
<add> return bind.call(context, property, options, false, exists);
<ide> });
<ide>
<ide> /**
<ide> EmberHandlebars.registerHelper('with', function(context, options) {
<ide> Ember.bind(options.data.keywords, keywordName, contextPath);
<ide> }
<ide>
<del> return bind.call(this, path, options, true, function(result) {
<del> return !Ember.isNone(result);
<del> });
<add> return bind.call(this, path, options, true, exists);
<ide> } else {
<ide> Ember.assert("You must pass exactly one argument to the with helper", arguments.length === 2);
<ide> Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop);
| 1
|
Java
|
Java
|
remove unused methods in basicfuseableobserver
|
9461a7002d4203e22ae54c310ab7048dc469e6f3
|
<ide><path>src/main/java/io/reactivex/internal/observers/BasicFuseableObserver.java
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.exceptions.Exceptions;
<ide> import io.reactivex.internal.disposables.DisposableHelper;
<del>import io.reactivex.internal.functions.ObjectHelper;
<ide> import io.reactivex.internal.fuseable.QueueDisposable;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide>
<ide> protected void afterDownstream() {
<ide> // Convenience and state-aware methods
<ide> // -----------------------------------
<ide>
<del> /**
<del> * Emits the value to the actual subscriber if {@link #done} is false.
<del> * @param value the value to signal
<del> */
<del> protected final void next(R value) {
<del> if (done) {
<del> return;
<del> }
<del> actual.onNext(value);
<del> }
<del>
<ide> @Override
<ide> public void onError(Throwable t) {
<ide> if (done) {
<ide> public void onComplete() {
<ide> actual.onComplete();
<ide> }
<ide>
<del> /**
<del> * Checks if the value is null and if so, throws a NullPointerException.
<del> * @param value the value to check
<del> * @param message the message to indicate the source of the value
<del> * @return the value if not null
<del> */
<del> protected final <V> V nullCheck(V value, String message) {
<del> return ObjectHelper.requireNonNull(value, message);
<del> }
<del>
<ide> /**
<ide> * Calls the upstream's QueueDisposable.requestFusion with the mode and
<ide> * saves the established mode in {@link #sourceMode}.
| 1
|
Mixed
|
Javascript
|
remove tension option backwards compatibility
|
f0fb2c65b1ba9b0dbc60acac611daec3ee54b320
|
<ide><path>docs/getting-started/v3-migration.md
<ide> Chart.js is no longer providing the `Chart.bundle.js` and `Chart.bundle.min.js`.
<ide>
<ide> ### Options
<ide>
<add>* The dataset option `tension` was renamed to `lineTension`
<ide> * `scales.[x/y]Axes.barPercentage` was moved to dataset option `barPercentage`
<ide> * `scales.[x/y]Axes.barThickness` was moved to dataset option `barThickness`
<ide> * `scales.[x/y]Axes.categoryPercentage` was moved to dataset option `categoryPercentage`
<ide><path>src/controllers/controller.line.js
<ide> module.exports = DatasetController.extend({
<ide>
<ide> // Update Line
<ide> if (showLine) {
<del> // Compatibility: If the properties are defined with only the old name, use those values
<del> if (config.tension !== undefined && config.lineTension === undefined) {
<del> config.lineTension = config.tension;
<del> }
<del>
<ide> // Utility
<ide> line._datasetIndex = me.index;
<ide> // Data
| 2
|
Javascript
|
Javascript
|
use opaque canvas where possible
|
b10aa18b3eda4437668b5453e20f729790b4a437
|
<ide><path>src/display/api.js
<ide> var WorkerTransport = (function WorkerTransportClosure() {
<ide> info('The worker has been disabled.');
<ide> }
<ide> }
<del>//#endif
<add>//#endif
<ide> // Either workers are disabled, not supported or have thrown an exception.
<ide> // Thus, we fallback to a faked worker.
<ide> globalScope.PDFJS.disableWorker = true;
<ide><path>web/page_view.js
<ide> var PageView = function pageView(container, id, scale,
<ide> this.canvas = canvas;
<ide>
<ide> var scale = this.scale;
<del> var ctx = canvas.getContext('2d');
<add> var ctx = canvas.getContext('2d', {alpha: false});
<ide> var outputScale = getOutputScale(ctx);
<ide>
<ide> if (USE_ONLY_CSS_ZOOM) {
<ide><path>web/text_layer_builder.js
<ide> var TextLayerBuilder = function textLayerBuilder(options) {
<ide> this.renderLayer = function textLayerBuilderRenderLayer() {
<ide> var textDivs = this.textDivs;
<ide> var canvas = document.createElement('canvas');
<del> var ctx = canvas.getContext('2d');
<add> var ctx = canvas.getContext('2d', {alpha: false});
<ide>
<ide> // No point in rendering so many divs as it'd make the browser unusable
<ide> // even after the divs are rendered
<ide><path>web/thumbnail_view.js
<ide> var ThumbnailView = function thumbnailView(container, id, defaultViewport) {
<ide>
<ide> ring.appendChild(canvas);
<ide>
<del> var ctx = canvas.getContext('2d');
<add> var ctx = canvas.getContext('2d', {alpha: false});
<ide> ctx.save();
<ide> ctx.fillStyle = 'rgb(255, 255, 255)';
<ide> ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
| 4
|
Javascript
|
Javascript
|
add second argument to assert.throws
|
9de2e159c4e83bea80c1d96abdabc6a69207344c
|
<ide><path>test/addons-napi/test_constructor/test.js
<ide> assert.strictEqual(test_object.readwriteValue, 1);
<ide> test_object.readwriteValue = 2;
<ide> assert.strictEqual(test_object.readwriteValue, 2);
<ide>
<del>assert.throws(() => { test_object.readonlyValue = 3; });
<add>assert.throws(() => { test_object.readonlyValue = 3; }, TypeError);
<ide>
<ide> assert.ok(test_object.hiddenValue);
<ide>
<ide> assert.ok(propertyNames.indexOf('readonlyAccessor2') < 0);
<ide> test_object.readwriteAccessor1 = 1;
<ide> assert.strictEqual(test_object.readwriteAccessor1, 1);
<ide> assert.strictEqual(test_object.readonlyAccessor1, 1);
<del>assert.throws(() => { test_object.readonlyAccessor1 = 3; });
<add>assert.throws(() => { test_object.readonlyAccessor1 = 3; }, TypeError);
<ide> test_object.readwriteAccessor2 = 2;
<ide> assert.strictEqual(test_object.readwriteAccessor2, 2);
<ide> assert.strictEqual(test_object.readonlyAccessor2, 2);
<del>assert.throws(() => { test_object.readonlyAccessor2 = 3; });
<add>assert.throws(() => { test_object.readonlyAccessor2 = 3; }, TypeError);
<ide><path>test/addons-napi/test_properties/test.js
<ide> assert.strictEqual(test_object.readwriteValue, 1);
<ide> test_object.readwriteValue = 2;
<ide> assert.strictEqual(test_object.readwriteValue, 2);
<ide>
<del>assert.throws(() => { test_object.readonlyValue = 3; });
<add>assert.throws(() => { test_object.readonlyValue = 3; }, TypeError);
<ide>
<ide> assert.ok(test_object.hiddenValue);
<ide>
<ide> assert.ok(propertyNames.indexOf('readonlyAccessor2') < 0);
<ide> test_object.readwriteAccessor1 = 1;
<ide> assert.strictEqual(test_object.readwriteAccessor1, 1);
<ide> assert.strictEqual(test_object.readonlyAccessor1, 1);
<del>assert.throws(() => { test_object.readonlyAccessor1 = 3; });
<add>assert.throws(() => { test_object.readonlyAccessor1 = 3; }, TypeError);
<ide> test_object.readwriteAccessor2 = 2;
<ide> assert.strictEqual(test_object.readwriteAccessor2, 2);
<ide> assert.strictEqual(test_object.readonlyAccessor2, 2);
<del>assert.throws(() => { test_object.readonlyAccessor2 = 3; });
<add>assert.throws(() => { test_object.readonlyAccessor2 = 3; }, TypeError);
<ide><path>test/parallel/test-assert-checktag.js
<ide> function re(literals, ...values) {
<ide> }
<ide> assert.doesNotThrow(() => assert.deepEqual(fakeGlobal, global));
<ide> // Message will be truncated anyway, don't validate
<del> assert.throws(() => assert.deepStrictEqual(fakeGlobal, global));
<add> assert.throws(() => assert.deepStrictEqual(fakeGlobal, global),
<add> assert.AssertionError);
<ide> }
<ide>
<ide> { // At the moment process has its own type tag
<ide> function re(literals, ...values) {
<ide> }
<ide> assert.doesNotThrow(() => assert.deepEqual(fakeProcess, process));
<ide> // Message will be truncated anyway, don't validate
<del> assert.throws(() => assert.deepStrictEqual(fakeProcess, process));
<add> assert.throws(() => assert.deepStrictEqual(fakeProcess, process),
<add> assert.AssertionError);
<ide> }
<ide> /* eslint-enable */
<ide><path>test/parallel/test-assert-deep.js
<ide> function re(literals, ...values) {
<ide> const arr = new Uint8Array([120, 121, 122, 10]);
<ide> const buf = Buffer.from(arr);
<ide> // They have different [[Prototype]]
<del>assert.throws(() => assert.deepStrictEqual(arr, buf));
<add>assert.throws(() => assert.deepStrictEqual(arr, buf),
<add> re`${arr} deepStrictEqual ${buf}`);
<ide> assert.doesNotThrow(() => assert.deepEqual(arr, buf));
<ide>
<ide> const buf2 = Buffer.from(arr);
<ide> buf2.prop = 1;
<ide>
<del>assert.throws(() => assert.deepStrictEqual(buf2, buf));
<add>assert.throws(() => assert.deepStrictEqual(buf2, buf),
<add> re`${buf2} deepStrictEqual ${buf}`);
<ide> assert.doesNotThrow(() => assert.deepEqual(buf2, buf));
<ide>
<ide> const arr2 = new Uint8Array([120, 121, 122, 10]);
<ide> arr2.prop = 5;
<del>assert.throws(() => assert.deepStrictEqual(arr, arr2));
<add>assert.throws(() => assert.deepStrictEqual(arr, arr2),
<add> re`${arr} deepStrictEqual ${arr2}`);
<ide> assert.doesNotThrow(() => assert.deepEqual(arr, arr2));
<ide>
<ide> const date = new Date('2016');
<ide> function assertDeepAndStrictEqual(a, b) {
<ide> }
<ide>
<ide> function assertNotDeepOrStrict(a, b) {
<del> assert.throws(() => assert.deepEqual(a, b));
<del> assert.throws(() => assert.deepStrictEqual(a, b));
<add> assert.throws(() => assert.deepEqual(a, b), re`${a} deepEqual ${b}`);
<add> assert.throws(() => assert.deepStrictEqual(a, b),
<add> re`${a} deepStrictEqual ${b}`);
<ide>
<del> assert.throws(() => assert.deepEqual(b, a));
<del> assert.throws(() => assert.deepStrictEqual(b, a));
<add> assert.throws(() => assert.deepEqual(b, a), re`${b} deepEqual ${a}`);
<add> assert.throws(() => assert.deepStrictEqual(b, a),
<add> re`${b} deepStrictEqual ${a}`);
<ide> }
<ide>
<ide> function assertOnlyDeepEqual(a, b) {
<ide> assert.doesNotThrow(() => assert.deepEqual(a, b));
<del> assert.throws(() => assert.deepStrictEqual(a, b));
<add> assert.throws(() => assert.deepStrictEqual(a, b),
<add> re`${a} deepStrictEqual ${b}`);
<ide>
<ide> assert.doesNotThrow(() => assert.deepEqual(b, a));
<del> assert.throws(() => assert.deepStrictEqual(b, a));
<add> assert.throws(() => assert.deepStrictEqual(b, a),
<add> re`${b} deepStrictEqual ${a}`);
<ide> }
<ide>
<ide> // es6 Maps and Sets
<ide> assertDeepAndStrictEqual(
<ide> assertNotDeepOrStrict(m1, m2);
<ide> }
<ide>
<del>assert.deepEqual(new Map([[1, 1]]), new Map([[1, '1']]));
<del>assert.throws(() =>
<del> assert.deepStrictEqual(new Map([[1, 1]]), new Map([[1, '1']]))
<del>);
<add>{
<add> const map1 = new Map([[1, 1]]);
<add> const map2 = new Map([[1, '1']]);
<add> assert.deepEqual(map1, map2);
<add> assert.throws(() => assert.deepStrictEqual(map1, map2),
<add> re`${map1} deepStrictEqual ${map2}`);
<add>}
<ide>
<ide> {
<ide> // Two equivalent sets / maps with different key/values applied shouldn't be
<ide><path>test/parallel/test-assert.js
<ide> assert.doesNotThrow(makeBlock(a.deepStrictEqual, {a: 4}, {a: 4}));
<ide> assert.doesNotThrow(makeBlock(a.deepStrictEqual,
<ide> {a: 4, b: '2'},
<ide> {a: 4, b: '2'}));
<del>assert.throws(makeBlock(a.deepStrictEqual, [4], ['4']));
<add>assert.throws(makeBlock(a.deepStrictEqual, [4], ['4']),
<add> /^AssertionError: \[ 4 ] deepStrictEqual \[ '4' ]$/);
<ide> assert.throws(makeBlock(a.deepStrictEqual, {a: 4}, {a: 4, b: true}),
<del> a.AssertionError);
<del>assert.throws(makeBlock(a.deepStrictEqual, ['a'], {0: 'a'}));
<add> /^AssertionError: { a: 4 } deepStrictEqual { a: 4, b: true }$/);
<add>assert.throws(makeBlock(a.deepStrictEqual, ['a'], {0: 'a'}),
<add> /^AssertionError: \[ 'a' ] deepStrictEqual { '0': 'a' }$/);
<ide> //(although not necessarily the same order),
<ide> assert.doesNotThrow(makeBlock(a.deepStrictEqual,
<ide> {a: 4, b: '1'},
<ide> function thrower(errorConstructor) {
<ide> assert.throws(makeBlock(thrower, a.AssertionError),
<ide> a.AssertionError, 'message');
<ide> assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError);
<add>// eslint-disable-next-line assert-throws-arguments
<ide> assert.throws(makeBlock(thrower, a.AssertionError));
<ide>
<ide> // if not passing an error, catch all.
<add>// eslint-disable-next-line assert-throws-arguments
<ide> assert.throws(makeBlock(thrower, TypeError));
<ide>
<ide> // when passing a type, only catch errors of the appropriate type
<ide> testAssertionMessage({a: NaN, b: Infinity, c: -Infinity},
<ide> {
<ide> let threw = false;
<ide> try {
<add> // eslint-disable-next-line assert-throws-arguments
<ide> assert.throws(function() {
<ide> assert.ifError(null);
<ide> });
<ide><path>test/parallel/test-repl-context.js
<ide> function testContext(repl) {
<ide> assert.strictEqual(context.global, context);
<ide>
<ide> // ensure that the repl console instance does not have a setter
<del> assert.throws(() => context.console = 'foo');
<add> assert.throws(() => context.console = 'foo', TypeError);
<ide> }
<ide><path>test/parallel/test-vm-new-script-this-context.js
<ide> console.error('thrown error');
<ide> script = new Script('throw new Error(\'test\');');
<ide> assert.throws(function() {
<ide> script.runInThisContext(script);
<del>});
<add>}, /^Error: test$/);
<ide>
<ide> global.hello = 5;
<ide> script = new Script('hello = 2');
| 7
|
Ruby
|
Ruby
|
restore old filename for non-github package urls
|
b8d60c7fd6269aca252d56c4109d2e59cd60fdda
|
<ide><path>Library/Homebrew/dev-cmd/bottle.rb
<ide> def bottle_formula(f, args:)
<ide>
<ide> return unless args.json?
<ide>
<add> bottle_filename = if bottle.root_url.match?(GitHubPackages::URL_REGEX)
<add> filename.github_packages
<add> else
<add> filename.bintray
<add> end
<add>
<ide> json = {
<ide> f.full_name => {
<ide> "formula" => {
<ide> def bottle_formula(f, args:)
<ide> "date" => Pathname(local_filename).mtime.strftime("%F"),
<ide> "tags" => {
<ide> bottle_tag.to_s => {
<del> "filename" => filename.github_packages,
<add> "filename" => bottle_filename,
<ide> "local_filename" => local_filename,
<ide> "sha256" => sha256,
<ide> "formulae_brew_sh_path" => formulae_brew_sh_path,
| 1
|
Javascript
|
Javascript
|
detect external changes in `history.state`
|
2b360bf30528e636da429396f2fe740c3f97c6f8
|
<ide><path>src/ng/browser.js
<ide> function Browser(window, document, $log, $sniffer) {
<ide> };
<ide>
<ide> cacheState();
<del> lastHistoryState = cachedState;
<ide>
<ide> /**
<ide> * @name $browser#url
<ide> function Browser(window, document, $log, $sniffer) {
<ide> if ($sniffer.history && (!sameBase || !sameState)) {
<ide> history[replace ? 'replaceState' : 'pushState'](state, '', url);
<ide> cacheState();
<del> // Do the assignment again so that those two variables are referentially identical.
<del> lastHistoryState = cachedState;
<ide> } else {
<ide> if (!sameBase) {
<ide> pendingLocation = url;
<ide> function Browser(window, document, $log, $sniffer) {
<ide>
<ide> function cacheStateAndFireUrlChange() {
<ide> pendingLocation = null;
<del> cacheState();
<del> fireUrlChange();
<add> fireStateOrUrlChange();
<ide> }
<ide>
<ide> // This variable should be used *only* inside the cacheState function.
<ide> function Browser(window, document, $log, $sniffer) {
<ide> if (equals(cachedState, lastCachedState)) {
<ide> cachedState = lastCachedState;
<ide> }
<add>
<ide> lastCachedState = cachedState;
<add> lastHistoryState = cachedState;
<ide> }
<ide>
<del> function fireUrlChange() {
<del> if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
<add> function fireStateOrUrlChange() {
<add> var prevLastHistoryState = lastHistoryState;
<add> cacheState();
<add>
<add> if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
<ide> return;
<ide> }
<ide>
<ide> function Browser(window, document, $log, $sniffer) {
<ide> * Needs to be exported to be able to check for changes that have been done in sync,
<ide> * as hashchange/popstate events fire in async.
<ide> */
<del> self.$$checkUrlChange = fireUrlChange;
<add> self.$$checkUrlChange = fireStateOrUrlChange;
<ide>
<ide> //////////////////////////////////////////////////////////////
<ide> // Misc API
<ide><path>test/ng/locationSpec.js
<ide> describe('$location', function() {
<ide> });
<ide>
<ide> it('should update $location when browser state changes', function() {
<del> initService({html5Mode:true, supportHistory: true});
<del> mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
<del> inject(function($location, $window) {
<add> initService({html5Mode: true, supportHistory: true});
<add> mockUpBrowser({initialUrl: 'http://new.com/a/b/', baseHref: '/a/b/'});
<add> inject(function($location, $rootScope, $window) {
<ide> $window.history.pushState({b: 3});
<add> $rootScope.$digest();
<add>
<ide> expect($location.state()).toEqual({b: 3});
<add>
<add> $window.history.pushState({b: 4}, null, $window.location.href + 'c?d=e#f');
<add> $rootScope.$digest();
<add>
<add> expect($location.path()).toBe('/c');
<add> expect($location.search()).toEqual({d: 'e'});
<add> expect($location.hash()).toBe('f');
<add> expect($location.state()).toEqual({b: 4});
<ide> });
<ide> });
<ide>
<ide> describe('$location', function() {
<ide> replaceState: function(state, title, url) {
<ide> win.history.state = copy(state);
<ide> if (url) win.location.href = url;
<del> jqLite(win).triggerHandler('popstate');
<ide> },
<ide> pushState: function(state, title, url) {
<ide> win.history.state = copy(state);
<ide> if (url) win.location.href = url;
<del> jqLite(win).triggerHandler('popstate');
<ide> }
<ide> };
<ide> win.addEventListener = angular.noop;
| 2
|
Javascript
|
Javascript
|
update flakey preview test
|
3026fa586446beee1b116b5b6b5e20c2b857e870
|
<ide><path>test/integration/prerender-preview/pages/index.js
<ide> export default function ({ hasProps, preview, previewData, random }) {
<ide> >
<ide> Reload static props
<ide> </button>
<del> <p id="router">{JSON.stringify(router)}</p>
<add> <p id="router">{JSON.stringify({ isPreview: router.isPreview })}</p>
<ide> </>
<ide> )
<ide> }
| 1
|
PHP
|
PHP
|
add getgenericuser function
|
60f82796778b828432dcae8b32a9cc8f12829c21
|
<ide><path>src/Illuminate/Auth/DatabaseUserProvider.php
<ide> public function retrieveById($identifier)
<ide> {
<ide> $user = $this->conn->table($this->table)->find($identifier);
<ide>
<del> if ( ! is_null($user))
<del> {
<del> return new GenericUser((array) $user);
<del> }
<add> return $this->getGenericUser($user);
<ide> }
<ide>
<ide> /**
<ide> public function retrieveByToken($identifier, $token)
<ide> ->where('remember_token', $token)
<ide> ->first();
<ide>
<del> if ( ! is_null($user))
<del> {
<del> return new GenericUser((array) $user);
<del> }
<add> return $this->getGenericUser($user);
<ide> }
<ide>
<ide> /**
<ide> public function retrieveByCredentials(array $credentials)
<ide> // that there are no matching users for these given credential arrays.
<ide> $user = $query->first();
<ide>
<del> if ( ! is_null($user))
<add> return $this->getGenericUser($user);
<add> }
<add>
<add> /**
<add> * Get the generic user.
<add> *
<add> * @param mixed $user
<add> * @return \Illuminate\Auth\GenericUser|null
<add> */
<add> protected function getGenericUser($user)
<add> {
<add> if ($user !== null)
<ide> {
<ide> return new GenericUser((array) $user);
<ide> }
| 1
|
Mixed
|
Javascript
|
fix regression with linetension
|
b02a3a8175152d5e6d2bed54d5f0348ee9b3d840
|
<ide><path>docs/charts/radar.md
<ide> The radar chart allows a number of properties to be specified for each dataset.
<ide> | [`borderWidth`](#line-styling) | `number` | Yes | - | `3`
<ide> | [`fill`](#line-styling) | <code>boolean|string</code> | Yes | - | `true`
<ide> | [`label`](#general) | `string` | - | - | `''`
<del>| [`lineTension`](#line-styling) | `number` | - | - | `0.4`
<add>| [`lineTension`](#line-styling) | `number` | - | - | `0`
<ide> | [`pointBackgroundColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
<ide> | [`pointBorderColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
<ide> | [`pointBorderWidth`](#point-styling) | `number` | Yes | Yes | `1`
<ide><path>src/controllers/controller.line.js
<ide> module.exports = DatasetController.extend({
<ide> var line = meta.dataset;
<ide> var points = meta.data || [];
<ide> var options = me.chart.options;
<del> var dataset = me.getDataset();
<del> var showLine = me._showLine = valueOrDefault(me._config.showLine, options.showLines);
<add> var config = me._config;
<add> var showLine = me._showLine = valueOrDefault(config.showLine, options.showLines);
<ide> var i, ilen;
<ide>
<ide> me._xScale = me.getScaleForId(meta.xAxisID);
<ide> module.exports = DatasetController.extend({
<ide> // Update Line
<ide> if (showLine) {
<ide> // Compatibility: If the properties are defined with only the old name, use those values
<del> if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
<del> dataset.lineTension = dataset.tension;
<add> if (config.tension !== undefined && config.lineTension === undefined) {
<add> config.lineTension = config.tension;
<ide> }
<ide>
<ide> // Utility
<ide> module.exports = DatasetController.extend({
<ide> */
<ide> _resolveDatasetElementOptions: function(element) {
<ide> var me = this;
<del> var datasetOpts = me._config;
<add> var config = me._config;
<ide> var custom = element.custom || {};
<ide> var options = me.chart.options;
<ide> var lineOptions = options.elements.line;
<ide> module.exports = DatasetController.extend({
<ide> // The default behavior of lines is to break at null values, according
<ide> // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
<ide> // This option gives lines the ability to span gaps
<del> values.spanGaps = valueOrDefault(datasetOpts.spanGaps, options.spanGaps);
<del> values.tension = valueOrDefault(datasetOpts.lineTension, lineOptions.tension);
<del> values.steppedLine = resolve([custom.steppedLine, datasetOpts.steppedLine, lineOptions.stepped]);
<add> values.spanGaps = valueOrDefault(config.spanGaps, options.spanGaps);
<add> values.tension = valueOrDefault(config.lineTension, lineOptions.tension);
<add> values.steppedLine = resolve([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
<ide>
<ide> return values;
<ide> },
<ide><path>src/controllers/controller.radar.js
<ide> module.exports = DatasetController.extend({
<ide> var line = meta.dataset;
<ide> var points = meta.data || [];
<ide> var scale = me.chart.scale;
<del> var dataset = me.getDataset();
<add> var config = me._config;
<ide> var i, ilen;
<ide>
<ide> // Compatibility: If the properties are defined with only the old name, use those values
<del> if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
<del> dataset.lineTension = dataset.tension;
<add> if (config.tension !== undefined && config.lineTension === undefined) {
<add> config.lineTension = config.tension;
<ide> }
<ide>
<ide> // Utility
| 3
|
Python
|
Python
|
fix some warnings from lgtm
|
20e98fcded341d5aef6dfdfc5cdac431a55252bd
|
<ide><path>ciphers/enigma_machine2.py
<ide> def enigma(
<ide> rotorpos1 -= 1
<ide> rotorpos2 -= 1
<ide> rotorpos3 -= 1
<del> plugboard = plugboard
<ide>
<ide> result = []
<ide>
<ide><path>graphs/directed_and_undirected_(weighted)_graph.py
<ide> def has_cycle(self):
<ide> break
<ide> else:
<ide> return True
<add> # TODO:The following code is unreachable.
<ide> anticipating_nodes.add(stack[len_stack_minus_one])
<ide> len_stack_minus_one -= 1
<ide> if visited.count(node[1]) < 1:
<ide> def has_cycle(self):
<ide> break
<ide> else:
<ide> return True
<add> # TODO: the following code is unreachable
<add> # is this meant to be called in the else ?
<ide> anticipating_nodes.add(stack[len_stack_minus_one])
<ide> len_stack_minus_one -= 1
<ide> if visited.count(node[1]) < 1:
<ide><path>graphs/minimum_spanning_tree_boruvka.py
<ide> def union(self, item1, item2):
<ide> self.parent[root2] = root1
<ide> return root1
<ide>
<add> @staticmethod
<ide> def boruvka_mst(graph):
<ide> """
<ide> Implementation of Boruvka's algorithm
<ide><path>maths/chudnovsky_algorithm.py
<ide> def pi(precision: int) -> str:
<ide> getcontext().prec = precision
<ide> num_iterations = ceil(precision / 14)
<ide> constant_term = 426880 * Decimal(10005).sqrt()
<del> multinomial_term = 1
<ide> exponential_term = 1
<ide> linear_term = 13591409
<ide> partial_sum = Decimal(linear_term)
<ide><path>other/triplet_sum.py
<ide> def triplet_sum2(arr: List[int], target: int) -> Tuple[int, int, int]:
<ide> left += 1
<ide> elif arr[i] + arr[left] + arr[right] > target:
<ide> right -= 1
<del> else:
<del> return (0, 0, 0)
<add> return (0, 0, 0)
<ide>
<ide>
<ide> def solution_times() -> Tuple[float, float]:
<ide><path>scheduling/shortest_job_first.py
<ide> def calculate_waitingtime(
<ide> arrival_time: List[int], burst_time: List[int], no_of_processes: int
<ide> ) -> List[int]:
<del>
<ide> """
<ide> Calculate the waiting time of each processes
<ide> Return: list of waiting times.
<ide> def calculate_average_times(
<ide> for i in range(no_of_processes):
<ide> print("Enter the arrival time and brust time for process:--" + str(i + 1))
<ide> arrival_time[i], burst_time[i] = map(int, input().split())
<add>
<ide> waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes)
<add>
<ide> bt = burst_time
<ide> n = no_of_processes
<ide> wt = waiting_time
<ide> turn_around_time = calculate_turnaroundtime(bt, n, wt)
<add>
<ide> calculate_average_times(waiting_time, turn_around_time, no_of_processes)
<del> processes = list(range(1, no_of_processes + 1))
<add>
<ide> fcfs = pd.DataFrame(
<ide> list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)),
<ide> columns=[
| 6
|
PHP
|
PHP
|
set default cookie path to webroot instead of base
|
2f3d50b3558d64ee7f703ac350cf22058a097956
|
<ide><path>src/Controller/Component/CookieComponent.php
<ide> class CookieComponent extends Component {
<ide> * If path is set to '/foo/', the cookie will only be available within the
<ide> * /foo/ directory and all sub-directories such as /foo/bar/ of domain.
<ide> * The default value is base path of app. For e.g. if your app is running
<del> * under a subfolder "cakeapp" of document root the path would be "/cakeapp"
<add> * under a subfolder "cakeapp" of document root the path would be "/cakeapp/"
<ide> * else it would be "/".
<ide> * - `domain` - The domain that the cookie is available. To make the cookie
<ide> * available on all subdomains of example.com set domain to '.example.com'.
<ide> public function initialize(array $config) {
<ide> }
<ide>
<ide> if (empty($this->_config['path'])) {
<del> $this->config('path', $this->_request->base ?: '/');
<add> $this->config('path', $this->_request->webroot);
<ide> }
<ide>
<ide> if ($controller && isset($controller->response)) {
<ide><path>src/Controller/Component/CsrfComponent.php
<ide> protected function _setCookie(Request $request, Response $response) {
<ide> 'name' => $this->_config['cookieName'],
<ide> 'value' => $value,
<ide> 'expiry' => $this->_config['expiry'],
<del> 'path' => $request->base,
<add> 'path' => $request->webroot,
<ide> 'secure' => $this->_config['secure'],
<ide> ]);
<ide> }
<ide><path>src/Network/Request.php
<ide> public static function createFromGlobals() {
<ide> list($base, $webroot) = static::_base();
<ide> $sessionConfig = (array)Configure::read('Session') + [
<ide> 'defaults' => 'php',
<del> 'cookiePath' => $base
<add> 'cookiePath' => $webroot
<ide> ];
<ide>
<ide> $config = array(
<ide><path>tests/TestCase/Controller/Component/CsrfComponentTest.php
<ide> public function testSettingCookie() {
<ide> $_SERVER['REQUEST_METHOD'] = 'GET';
<ide>
<ide> $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
<del> $controller->request = new Request(['base' => '/dir']);
<add> $controller->request = new Request(['webroot' => '/dir/']);
<ide> $controller->response = new Response();
<ide>
<ide> $event = new Event('Controller.startup', $controller);
<ide> public function testSettingCookie() {
<ide> $this->assertNotEmpty($cookie, 'Should set a token.');
<ide> $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
<ide> $this->assertEquals(0, $cookie['expiry'], 'session duration.');
<del> $this->assertEquals('/dir', $cookie['path'], 'session path.');
<add> $this->assertEquals('/dir/', $cookie['path'], 'session path.');
<ide>
<ide> $this->assertEquals($cookie['value'], $controller->request->params['_csrfToken']);
<ide> }
<ide> public function testConfigurationCookieCreate() {
<ide> $_SERVER['REQUEST_METHOD'] = 'GET';
<ide>
<ide> $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
<del> $controller->request = new Request(['base' => '/dir']);
<add> $controller->request = new Request(['webroot' => '/dir/']);
<ide> $controller->response = new Response();
<ide>
<ide> $component = new CsrfComponent($this->registry, [
<ide> public function testConfigurationCookieCreate() {
<ide> $this->assertNotEmpty($cookie, 'Should set a token.');
<ide> $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
<ide> $this->assertEquals(90, $cookie['expiry'], 'session duration.');
<del> $this->assertEquals('/dir', $cookie['path'], 'session path.');
<add> $this->assertEquals('/dir/', $cookie['path'], 'session path.');
<ide> $this->assertTrue($cookie['secure'], 'cookie security flag missing');
<ide> }
<ide>
| 4
|
Python
|
Python
|
use django.utils to import the unittest module
|
721dc519ecdb8435bdeed6aa67d99be6968c0972
|
<ide><path>rest_framework/tests/authentication.py
<ide> from django.contrib.auth.models import User
<ide> from django.http import HttpResponse
<ide> from django.test import Client, TestCase
<add>from django.utils import unittest
<ide> from rest_framework import HTTP_HEADER_ENCODING
<ide> from rest_framework import exceptions
<ide> from rest_framework import permissions
<ide> import json
<ide> import base64
<ide> import datetime
<del>import unittest
<ide>
<ide>
<ide> factory = RequestFactory()
| 1
|
Text
|
Text
|
fix man pages
|
732141442affc096342801900641d9b303c24dbc
|
<ide><path>man/docker-ps.1.md
<ide> docker-ps - List containers
<ide>
<ide> # DESCRIPTION
<ide>
<del>List the containers in the local repository. By default this show only
<add>List the containers in the local repository. By default this shows only
<ide> the running containers.
<ide>
<ide> # OPTIONS
<ide> **-a**, **--all**=*true*|*false*
<ide> Show all containers. Only running containers are shown by default. The default is *false*.
<ide>
<ide> **--before**=""
<del> Show only container created before Id or Name, include non-running ones.
<add> Show only containers created before Id or Name, including non-running containers.
<ide>
<ide> **--help**
<ide> Print usage statement
<ide><path>man/docker-pull.1.md
<ide> registry located at `registry-1.docker.io` by default.
<ide> # OPTIONS
<ide> **-a**, **--all-tags**=*true*|*false*
<ide> Download all tagged images in the repository. The default is *false*.
<add>
<ide> **--help**
<ide> Print usage statement
<ide>
<ide><path>man/docker-search.1.md
<ide> TERM
<ide>
<ide> # DESCRIPTION
<ide>
<del>Search Docker Hub for an image with that matches the specified `TERM`. The table
<add>Search Docker Hub for images that match the specified `TERM`. The table
<ide> of images returned displays the name, description (truncated by default), number
<ide> of stars awarded, whether the image is official, and whether it is automated.
<ide>
| 3
|
Javascript
|
Javascript
|
protect internals against prototype tampering
|
2fe4e9473fb50630326754886dee1d301a1a661e
|
<ide><path>lib/internal/test_runner/test.js
<ide> class Test extends AsyncResource {
<ide> }
<ide> }
<ide>
<del> const test = new Factory({ fn, name, parent, ...options, ...overrides });
<add> const test = new Factory({ __proto__: null, fn, name, parent, ...options, ...overrides });
<ide>
<ide> if (parent.waitingOn === 0) {
<ide> parent.waitingOn = test.testNumber;
<ide><path>test/fixtures/test-runner/protoMutation.js
<add>'use strict';
<add>
<add>Object.prototype.skip = true;
<ide><path>test/parallel/test-runner-cli.js
<ide> const testFixtures = fixtures.path('test-runner');
<ide> assert.match(stdout, /ok 4 - .+random\.cjs/);
<ide> }
<ide>
<add>{
<add> // Same but with a prototype mutation in require scripts.
<add> const args = ['--require', join(testFixtures, 'protoMutation.js'), '--test', testFixtures];
<add> const child = spawnSync(process.execPath, args);
<add>
<add> const stdout = child.stdout.toString();
<add> assert.match(stdout, /ok 1 - .+index\.test\.js/);
<add> assert.match(stdout, /not ok 2 - .+random\.test\.mjs/);
<add> assert.match(stdout, /not ok 1 - this should fail/);
<add> assert.match(stdout, /ok 3 - .+subdir.+subdir_test\.js/);
<add> assert.match(stdout, /ok 4 - .+random\.cjs/);
<add> assert.strictEqual(child.status, 1);
<add> assert.strictEqual(child.signal, null);
<add> assert.strictEqual(child.stderr.toString(), '');
<add>}
<add>
<ide> {
<ide> // User specified files that don't match the pattern are still run.
<ide> const args = ['--test', testFixtures, join(testFixtures, 'index.js')];
| 3
|
Go
|
Go
|
fix flaky windows testrestartrunningcontainer test
|
bae22d167cd29016541a6d4f93d38f2608d8e51f
|
<ide><path>integration-cli/docker_cli_restart_test.go
<ide> func (s *DockerSuite) TestRestartRunningContainer(c *check.C) {
<ide>
<ide> c.Assert(waitRun(cleanedContainerID), checker.IsNil)
<ide>
<del> out, _ = dockerCmd(c, "logs", cleanedContainerID)
<del> c.Assert(out, checker.Equals, "foobar\n")
<del>
<del> dockerCmd(c, "restart", "-t", "1", cleanedContainerID)
<add> getLogs := func(c *check.C) (interface{}, check.CommentInterface) {
<add> out, _ := dockerCmd(c, "logs", cleanedContainerID)
<add> return out, nil
<add> }
<ide>
<del> out, _ = dockerCmd(c, "logs", cleanedContainerID)
<add> // Wait 10 seconds for the 'echo' to appear in the logs
<add> waitAndAssert(c, 10*time.Second, getLogs, checker.Equals, "foobar\n")
<ide>
<add> dockerCmd(c, "restart", "-t", "1", cleanedContainerID)
<ide> c.Assert(waitRun(cleanedContainerID), checker.IsNil)
<ide>
<del> c.Assert(out, checker.Equals, "foobar\nfoobar\n")
<add> // Wait 10 seconds for first 'echo' appear (again) in the logs
<add> waitAndAssert(c, 10*time.Second, getLogs, checker.Equals, "foobar\nfoobar\n")
<ide> }
<ide>
<ide> // Test that restarting a container with a volume does not create a new volume on restart. Regression test for #819.
| 1
|
Mixed
|
Ruby
|
add urlsafe option to messageverifier initializer
|
09c3f36a962a7ffd350dfda643d2f980734cb5c9
|
<ide><path>activesupport/CHANGELOG.md
<add>* Add `urlsafe` option to `ActiveSupport::MessageVerifier` initializer
<add>
<add> `ActiveSupport::MessageVerifier.new` now takes optional `urlsafe` argument.
<add> It can generate urlsafe strings by passing `urlsafe: true`.
<add>
<add> ```ruby
<add> verifier = ActiveSupport::MessageVerifier.new(urlsafe: true)
<add> message = verifier.generate(data) # => "urlsafe_string"
<add> ```
<add>
<add> This option is `false` by default to be backwards compatible.
<add>
<add> *Shouichi Kamiya*
<add>
<ide> * Enable connection pooling by default for `MemCacheStore` and `RedisCacheStore`.
<ide>
<ide> If you want to disable connection pooling, set `:pool` option to `false` when configuring the cache store:
<ide><path>activesupport/lib/active_support/message_verifier.rb
<ide> class InvalidSignature < StandardError; end
<ide>
<ide> cattr_accessor :default_message_verifier_serializer, instance_accessor: false, default: :marshal
<ide>
<del> def initialize(secret, digest: nil, serializer: nil)
<add> def initialize(secret, digest: nil, serializer: nil, urlsafe: false)
<ide> raise ArgumentError, "Secret should not be nil." unless secret
<ide> @secret = secret
<ide> @digest = digest&.to_s || "SHA1"
<ide> def initialize(secret, digest: nil, serializer: nil)
<ide> elsif @@default_message_verifier_serializer.equal?(:json)
<ide> JSON
<ide> end
<add> @urlsafe = urlsafe
<ide> end
<ide>
<ide> # Checks if a signed message could have been generated by signing an object
<ide> def generate(value, expires_at: nil, expires_in: nil, purpose: nil)
<ide>
<ide> private
<ide> def encode(data)
<del> ::Base64.strict_encode64(data)
<add> @urlsafe ? Base64.urlsafe_encode64(data) : Base64.strict_encode64(data)
<ide> end
<ide>
<ide> def decode(data)
<del> ::Base64.strict_decode64(data)
<add> @urlsafe ? Base64.urlsafe_decode64(data) : Base64.strict_decode64(data)
<ide> end
<ide>
<ide> def generate_digest(data)
<ide><path>activesupport/test/message_verifier_test.rb
<ide> def verifier_options
<ide> { serializer: ActiveSupport::MessageEncryptor::NullSerializer }
<ide> end
<ide> end
<add>
<add>class MessageVerifierUrlsafeTest < MessageVerifierMetadataTest
<add> def test_urlsafe
<add> message = generate(data)
<add> assert_equal message, URI.encode_www_form_component(message)
<add> end
<add>
<add> private
<add> def verifier_options
<add> { urlsafe: true }
<add> end
<add>end
| 3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.