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
Ruby
Ruby
use ruby style for inheritance
9ed51082c276ef4c6e24f92be266fe0394797746
<ide><path>Library/Homebrew/cmd/create.rb <ide> def generate <ide> def template; <<-EOS.undent <ide> require 'formula' <ide> <del> class #{Formula.class_s name} <Formula <add> class #{Formula.class_s name} < Formula <ide> url '#{url}' <ide> homepage '' <ide> md5 '#{md5}'
1
Javascript
Javascript
remove 3rd arg from to assert.strictequal()
cfe0c024fca5e12688de1c95af257092d03417cb
<ide><path>test/parallel/test-stream-transform-final-sync.js <ide> The order things are called <ide> const t = new stream.Transform({ <ide> objectMode: true, <ide> transform: common.mustCall(function(chunk, _, next) { <del> assert.strictEqual(++state, chunk, 'transformCallback part 1'); <add> // transformCallback part 1 <add> assert.strictEqual(++state, chunk); <ide> this.push(state); <del> assert.strictEqual(++state, chunk + 2, 'transformCallback part 2'); <add> // transformCallback part 2 <add> assert.strictEqual(++state, chunk + 2); <ide> process.nextTick(next); <ide> }, 3), <ide> final: common.mustCall(function(done) { <ide> state++; <del> assert.strictEqual(state, 10, 'finalCallback part 1'); <add> // finalCallback part 1 <add> assert.strictEqual(state, 10); <ide> state++; <del> assert.strictEqual(state, 11, 'finalCallback part 2'); <add> // finalCallback part 2 <add> assert.strictEqual(state, 11); <ide> done(); <ide> }, 1), <ide> flush: common.mustCall(function(done) { <ide> state++; <del> assert.strictEqual(state, 12, 'flushCallback part 1'); <add> // fluchCallback part 1 <add> assert.strictEqual(state, 12); <ide> process.nextTick(function() { <ide> state++; <del> assert.strictEqual(state, 15, 'flushCallback part 2'); <add> // fluchCallback part 2 <add> assert.strictEqual(state, 15); <ide> done(); <ide> }); <ide> }, 1) <ide> }); <ide> t.on('finish', common.mustCall(function() { <ide> state++; <del> assert.strictEqual(state, 13, 'finishListener'); <add> // finishListener <add> assert.strictEqual(state, 13); <ide> }, 1)); <ide> t.on('end', common.mustCall(function() { <ide> state++; <del> assert.strictEqual(state, 16, 'end event'); <add> // endEvent <add> assert.strictEqual(state, 16); <ide> }, 1)); <ide> t.on('data', common.mustCall(function(d) { <del> assert.strictEqual(++state, d + 1, 'dataListener'); <add> // dataListener <add> assert.strictEqual(++state, d + 1); <ide> }, 3)); <ide> t.write(1); <ide> t.write(4); <ide> t.end(7, common.mustCall(function() { <ide> state++; <del> assert.strictEqual(state, 14, 'endMethodCallback'); <add> // endMethodCallback <add> assert.strictEqual(state, 14); <ide> }, 1));
1
Go
Go
fix vet errors
18d9f1978b311ff9cadce9f0237313db14502f9f
<ide><path>docker/docker.go <ide> func main() { <ide> if err := cli.Cmd(flag.Args()...); err != nil { <ide> if sterr, ok := err.(*utils.StatusError); ok { <ide> if sterr.Status != "" { <del> log.Println("%s", sterr.Status) <add> log.Println(sterr.Status) <ide> } <ide> os.Exit(sterr.StatusCode) <ide> } <ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildEnvironmentReplacementEnv(t *testing.T) { <ide> if parts[0] == "bar" { <ide> found = true <ide> if parts[1] != "foo" { <del> t.Fatal("Could not find replaced var for env `bar`: got %q instead of `foo`", parts[1]) <add> t.Fatalf("Could not find replaced var for env `bar`: got %q instead of `foo`", parts[1]) <ide> } <ide> } <ide> } <ide> func TestBuildCopyDisallowRemote(t *testing.T) { <ide> COPY https://index.docker.io/robots.txt /`, <ide> true) <ide> if err == nil || !strings.Contains(out, "Source can't be a URL for COPY") { <del> t.Fatal("Error should be about disallowed remote source, got err: %s, out: %q", err, out) <add> t.Fatalf("Error should be about disallowed remote source, got err: %s, out: %q", err, out) <ide> } <ide> logDone("build - copy - disallow copy from remote") <ide> } <ide> func TestBuildForceRm(t *testing.T) { <ide> buildCmd := exec.Command(dockerBinary, "build", "-t", name, "--force-rm", ".") <ide> buildCmd.Dir = ctx.Dir <ide> if out, _, err := runCommandWithOutput(buildCmd); err == nil { <del> t.Fatal("failed to build the image: %s, %v", out, err) <add> t.Fatalf("failed to build the image: %s, %v", out, err) <ide> } <ide> <ide> containerCountAfter, err := getContainerCount() <ide> func TestBuildEntrypointInheritance(t *testing.T) { <ide> status, _ = runCommand(exec.Command(dockerBinary, "run", "child")) <ide> <ide> if status != 5 { <del> t.Fatal("expected exit code 5 but received %d", status) <add> t.Fatalf("expected exit code 5 but received %d", status) <ide> } <ide> <ide> logDone("build - clear entrypoint") <ide><path>integration-cli/docker_cli_history_test.go <ide> RUN echo "Z"`, <ide> <ide> out, exitCode, err := runCommandWithOutput(exec.Command(dockerBinary, "history", "testbuildhistory")) <ide> if err != nil || exitCode != 0 { <del> t.Fatal("failed to get image history: %s, %v", out, err) <add> t.Fatalf("failed to get image history: %s, %v", out, err) <ide> } <ide> <ide> actualValues := strings.Split(out, "\n")[1:27] <ide><path>integration-cli/docker_cli_info_test.go <ide> func TestInfoEnsureSucceeds(t *testing.T) { <ide> versionCmd := exec.Command(dockerBinary, "info") <ide> out, exitCode, err := runCommandWithOutput(versionCmd) <ide> if err != nil || exitCode != 0 { <del> t.Fatal("failed to execute docker info: %s, %v", out, err) <add> t.Fatalf("failed to execute docker info: %s, %v", out, err) <ide> } <ide> <ide> stringsToCheck := []string{"Containers:", "Execution Driver:", "Kernel Version:"} <ide><path>integration-cli/docker_cli_pull_test.go <ide> import ( <ide> func TestPullImageFromCentralRegistry(t *testing.T) { <ide> pullCmd := exec.Command(dockerBinary, "pull", "scratch") <ide> if out, _, err := runCommandWithOutput(pullCmd); err != nil { <del> t.Fatal("pulling the scratch image from the registry has failed: %s, %v", out, err) <add> t.Fatalf("pulling the scratch image from the registry has failed: %s, %v", out, err) <ide> } <ide> logDone("pull - pull scratch") <ide> } <ide> func TestPullImageFromCentralRegistry(t *testing.T) { <ide> func TestPullNonExistingImage(t *testing.T) { <ide> pullCmd := exec.Command(dockerBinary, "pull", "fooblahblah1234") <ide> if out, _, err := runCommandWithOutput(pullCmd); err == nil { <del> t.Fatal("expected non-zero exit status when pulling non-existing image: %s", out) <add> t.Fatalf("expected non-zero exit status when pulling non-existing image: %s", out) <ide> } <ide> logDone("pull - pull fooblahblah1234 (non-existing image)") <ide> } <ide><path>integration-cli/docker_cli_push_test.go <ide> func TestPushBusyboxImage(t *testing.T) { <ide> repoName := fmt.Sprintf("%v/busybox", privateRegistryURL) <ide> tagCmd := exec.Command(dockerBinary, "tag", "busybox", repoName) <ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil { <del> t.Fatal("image tagging failed: %s, %v", out, err) <add> t.Fatalf("image tagging failed: %s, %v", out, err) <ide> } <ide> <ide> pushCmd := exec.Command(dockerBinary, "push", repoName) <ide> if out, _, err := runCommandWithOutput(pushCmd); err != nil { <del> t.Fatal("pushing the image to the private registry has failed: %s, %v", out, err) <add> t.Fatalf("pushing the image to the private registry has failed: %s, %v", out, err) <ide> } <ide> <ide> deleteImages(repoName) <ide> func TestPushUnprefixedRepo(t *testing.T) { <ide> t.Skip() <ide> pushCmd := exec.Command(dockerBinary, "push", "busybox") <ide> if out, _, err := runCommandWithOutput(pushCmd); err == nil { <del> t.Fatal("pushing an unprefixed repo didn't result in a non-zero exit status: %s", out) <add> t.Fatalf("pushing an unprefixed repo didn't result in a non-zero exit status: %s", out) <ide> } <ide> logDone("push - push unprefixed busybox repo --> must fail") <ide> } <ide><path>integration-cli/docker_cli_rm_test.go <ide> func TestRmInvalidContainer(t *testing.T) { <ide> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rm", "unknown")); err == nil { <ide> t.Fatal("Expected error on rm unknown container, got none") <ide> } else if !strings.Contains(out, "failed to remove one or more containers") { <del> t.Fatal("Expected output to contain 'failed to remove one or more containers', got %q", out) <add> t.Fatalf("Expected output to contain 'failed to remove one or more containers', got %q", out) <ide> } <ide> <ide> logDone("rm - delete unknown container") <ide><path>integration-cli/docker_cli_search_test.go <ide> func TestSearchOnCentralRegistry(t *testing.T) { <ide> searchCmd := exec.Command(dockerBinary, "search", "busybox") <ide> out, exitCode, err := runCommandWithOutput(searchCmd) <ide> if err != nil || exitCode != 0 { <del> t.Fatal("failed to search on the central registry: %s, %v", out, err) <add> t.Fatalf("failed to search on the central registry: %s, %v", out, err) <ide> } <ide> <ide> if !strings.Contains(out, "Busybox base image.") { <ide><path>integration-cli/docker_cli_version_test.go <ide> func TestVersionEnsureSucceeds(t *testing.T) { <ide> versionCmd := exec.Command(dockerBinary, "version") <ide> out, _, err := runCommandWithOutput(versionCmd) <ide> if err != nil { <del> t.Fatal("failed to execute docker version: %s, %v", out, err) <add> t.Fatalf("failed to execute docker version: %s, %v", out, err) <ide> } <ide> <ide> stringsToCheck := []string{
9
Ruby
Ruby
add order docs
ad919087a4a816514a0a040ab9e2045e269a241f
<ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def group!(*args) <ide> self <ide> end <ide> <add> # Allows to specify an order attribute: <add> # <add> # User.order('name') <add> # => SELECT "users".* FROM "users" ORDER BY name <add> # <add> # User.order('name DESC') <add> # => SELECT "users".* FROM "users" ORDER BY name DESC <add> # <add> # User.order('name DESC, email') <add> # => SELECT "users".* FROM "users" ORDER BY name DESC, email <ide> def order(*args) <ide> args.blank? ? self : spawn.order!(*args) <ide> end
1
PHP
PHP
fix failing tests
cb8aad81bb87923a7d1e782ca438701bd843050b
<ide><path>lib/Cake/Log/Engine/ConsoleLog.php <ide> * @since CakePHP(tm) v 2.2.0 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <del> <ide> namespace Cake\Log\Engine; <add> <ide> use Cake\Console\ConsoleOutput; <ide> use Cake\Utility\Hash; <ide> use Cake\Error; <ide><path>lib/Cake/Test/TestCase/I18n/I18nTest.php <ide> public function tearDown() { <ide> * @return void <ide> */ <ide> public function testTranslationCaching() { <add> $this->skipIf( <add> !Cache::engine('_cake_core_'), <add> 'Missing _cake_core_ cache config, cannot test caching.' <add> ); <ide> Configure::write('Config.language', 'cache_test_po'); <ide> <ide> // reset internally stored entries <ide> public function testTranslationCaching() { <ide> Cache::clear(false, '_cake_core_'); <ide> $lang = Configure::read('Config.language'); <ide> <del> Cache::config('_cake_core_', Cache::config('default')); <del> <ide> // make some calls to translate using different domains <ide> $this->assertEquals('Dom 1 Foo', I18n::translate('dom1.foo', false, 'dom1')); <ide> $this->assertEquals('Dom 1 Bar', I18n::translate('dom1.bar', false, 'dom1')); <ide><path>lib/Cake/Test/TestCase/Log/Engine/ConsoleLogTest.php <ide> * <ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @package Cake.Test.Case.Log.Engine <ide> * @since CakePHP(tm) v 1.3 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <del> <ide> namespace Cake\Test\TestCase\Log\Engine; <add> <ide> use Cake\Console\ConsoleOutput; <ide> use Cake\Log\Engine\ConsoleLog; <ide> use Cake\Log\Log; <ide> use Cake\TestSuite\TestCase; <ide> <del>class TestConsoleLog extends ConsoleLog { <del> <del>} <del> <del>class TestCakeLog extends Log { <del> <del> public static function replace($key, &$engine) { <del> static::$_Collection->{$key} = $engine; <del> } <del> <del>} <del> <ide> /** <ide> * ConsoleLogTest class <ide> * <ide> * @package Cake.Test.Case.Log.Engine <ide> */ <ide> class ConsoleLogTest extends TestCase { <ide> <del> public function setUp() { <del> parent::setUp(); <del> Log::config('debug', array( <del> 'engine' => 'Cake\Log\Engine\FileLog', <del> 'types' => array('notice', 'info', 'debug'), <del> 'file' => 'debug', <del> )); <del> Log::config('error', array( <del> 'engine' => 'Cake\Log\Engine\FileLog', <del> 'types' => array('error', 'warning'), <del> 'file' => 'error', <del> )); <del> } <del> <del> public function tearDown() { <del> parent::tearDown(); <del> if (file_exists(LOGS . 'error.log')) { <del> unlink(LOGS . 'error.log'); <del> } <del> if (file_exists(LOGS . 'debug.log')) { <del> unlink(LOGS . 'debug.log'); <del> } <del> } <del> <ide> /** <ide> * Test writing to ConsoleOutput <ide> */ <ide> public function testConsoleOutputWrites() { <del> TestCakeLog::config('test_console_log', array( <del> 'engine' => __NAMESPACE__ . '\TestConsoleLog', <del> )); <del> <del> $mock = $this->getMock(__NAMESPACE__ . '\TestConsoleLog', array('write'), array( <del> array('types' => 'error'), <del> )); <del> TestCakeLog::replace('test_console_log', $mock); <del> <del> $message = 'Test error message'; <del> $mock->expects($this->once()) <del> ->method('write'); <del> TestCakeLog::write(LOG_ERR, $message); <del> } <add> $output = $this->getMock('Cake\Console\ConsoleOutput'); <ide> <del>/** <del> * Test logging to both ConsoleLog and FileLog <del> */ <del> public function testCombinedLogWriting() { <del> TestCakeLog::config('test_console_log', array( <del> 'engine' => __NAMESPACE__ . '\TestConsoleLog', <del> )); <del> $mock = $this->getMock(__NAMESPACE__ . '\TestConsoleLog', array('write'), array( <del> array('types' => 'error'), <del> )); <del> TestCakeLog::replace('test_console_log', $mock); <add> $output->expects($this->at(0)) <add> ->method('outputAs'); <ide> <del> // log to both file and console <del> $message = 'Test error message'; <del> $mock->expects($this->once()) <del> ->method('write'); <del> TestCakeLog::write(LOG_ERR, $message); <del> $this->assertTrue(file_exists(LOGS . 'error.log'), 'error.log missing'); <del> $logOutput = file_get_contents(LOGS . 'error.log'); <del> $this->assertContains($message, $logOutput); <add> $message = '<error>' . date('Y-m-d H:i:s') . " Error: oh noes\n</error>"; <add> $output->expects($this->at(1)) <add> ->method('write') <add> ->with($message); <ide> <del> // TestConsoleLog is only interested in `error` type <del> $message = 'Test info message'; <del> $mock->expects($this->never()) <del> ->method('write'); <del> TestCakeLog::write(LOG_INFO, $message); <add> $log = new ConsoleLog([ <add> 'stream' => $output <add> ]); <add> $log->write('error', 'oh noes'); <add> } <ide> <del> // checks that output is correctly written in the correct logfile <del> $this->assertTrue(file_exists(LOGS . 'error.log'), 'error.log missing'); <del> $this->assertTrue(file_exists(LOGS . 'debug.log'), 'debug.log missing'); <del> $logOutput = file_get_contents(LOGS . 'error.log'); <del> $this->assertNotContains($message, $logOutput); <del> $logOutput = file_get_contents(LOGS . 'debug.log'); <del> $this->assertContains($message, $logOutput); <add> public function testWriteToFileStream() { <add> $filename = tempnam(sys_get_temp_dir(), 'cake_log_test'); <add> $log = new ConsoleLog([ <add> 'stream' => $filename <add> ]); <add> $log->write('error', 'oh noes'); <add> $fh = fopen($filename, 'r'); <add> $line = fgets($fh); <add> $this->assertContains('Error: oh noes', $line); <ide> } <ide> <ide> /** <ide> * test default value of stream 'outputAs' <ide> */ <ide> public function testDefaultOutputAs() { <del> TestCakeLog::config('test_console_log', array( <del> 'engine' => __NAMESPACE__ . '\TestConsoleLog', <del> )); <ide> if (DS == '\\' && !(bool)env('ANSICON')) { <ide> $expected = ConsoleOutput::PLAIN; <ide> } else { <ide> $expected = ConsoleOutput::COLOR; <ide> } <del> $stream = TestCakeLog::stream('test_console_log'); <del> $config = $stream->config(); <add> $output = $this->getMock('Cake\Console\ConsoleOutput'); <add> <add> $output->expects($this->at(0)) <add> ->method('outputAs') <add> ->with($expected); <add> <add> $log = new ConsoleLog([ <add> 'stream' => $output, <add> ]); <add> $config = $log->config(); <ide> $this->assertEquals($expected, $config['outputAs']); <ide> } <ide>
3
Text
Text
add badging to readme.md
4704a6e1480eca02d1a10193f175bd2cde814b70
<ide><path>README.md <ide> three.js <ide> ======== <ide> <add>[![Latest NPM release][npm-badge]][npm-badge-url] <add>[![License][license-badge]][license-badge-url] <add>[![Dependencies][dependencies-badge]][dependencies-badge-url] <add>[![Dev Dependencies][devDependencies-badge]][devDependencies-badge-url] <add> <ide> #### JavaScript 3D library #### <ide> <ide> The aim of the project is to create an easy to use, lightweight, 3D library. The library provides &lt;canvas&gt;, &lt;svg&gt;, CSS3D and WebGL renderers. <ide> If everything went well you should see [this](http://jsfiddle.net/hfj7gm6t/). <ide> ### Change log ### <ide> <ide> [releases](https://github.com/mrdoob/three.js/releases) <add> <add> <add> <add>[npm-badge]: https://img.shields.io/npm/v/three.svg <add>[npm-badge-url]: https://www.npmjs.com/package/three <add>[license-badge]: https://img.shields.io/npm/l/three.svg <add>[license-badge-url]: ./LICENSE <add>[dependencies-badge]: https://img.shields.io/david/mrdoob/three.js.svg <add>[dependencies-badge-url]: https://david-dm.org/mrdoob/three.js <add>[devDependencies-badge]: https://img.shields.io/david/dev/mrdoob/three.js.svg <add>[devDependencies-badge-url]: https://david-dm.org/mrdoob/three.js#info=devDependencies
1
Java
Java
fix the websocket sendbinary error
774290093139f7bfa2670717de7ddf878f3a8316
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java <ide> public void sendBinary(String base64String, int id) { <ide> throw new RuntimeException("Cannot send a message. Unknown WebSocket id " + id); <ide> } <ide> try { <del> client.sendMessage(RequestBody.create(WebSocket.TEXT, ByteString.decodeBase64(base64String))); <add> client.sendMessage(RequestBody.create(WebSocket.BINARY, ByteString.decodeBase64(base64String))); <ide> } catch (IOException | IllegalStateException e) { <ide> notifyWebSocketFailed(id, e.getMessage()); <ide> }
1
Javascript
Javascript
add project and build names to browserstack
41fd5cb4e6d7df627a35394eb395b1c2e0f657d9
<ide><path>test/karma.conf.js <ide> module.exports = function(config) { <add> // build out a name for browserstack <add> // {TRAVIS_BUILD_NUMBER} [{TRAVIS_PULL_REQUEST} {PR_BRANCH}] {TRAVIS_BRANCH} <add> var browserstackName = process.env.TRAVIS_BUILD_NUMBER; <add> <add> if (process.env.TRAVIS_PULL_REQUEST !== 'false') { <add> browserstackName += ' ' + process.env.TRAVIS_PULL_REQUEST + ' ' + process.env.TRAVIS_PULL_REQUEST_BRANCH; <add> } <add> <add> browserstackName += ' ' + process.env.TRAVIS_BRANCH; <add> <ide> // Creating settings object first so we can modify based on travis <ide> var settings = { <ide> basePath: '', <ide> module.exports = function(config) { <ide> browserDisconnectTolerance: 3, <ide> <ide> browserStack: { <del> name: process.env.TRAVIS_BUILD_NUMBER + process.env.TRAVIS_BRANCH, <add> project: 'Video.js', <add> name: browserstackName, <add> build: browserstackName, <ide> pollingTimeout: 30000, <ide> captureTimeout: 600, <ide> timeout: 600
1
Ruby
Ruby
add test case to prevent possible sql injection
2d5d537d19d62e9c132cf49f7dbc9eb8ff9190e3
<ide><path>activerecord/lib/arel/visitors/to_sql.rb <ide> def quote_column_name(name) <ide> end <ide> <ide> def sanitize_as_sql_comment(o) <del> o.expr.map { |v| v.gsub(%r{ /\*\+?\s* | \s*\*/ }x, "") } <add> o.expr.map { |v| <add> v.gsub(%r{ (/ (?: | \g<1>) \*) \+? \s* | \s* (\* (?: | \g<2>) /) }x, "") <add> } <ide> end <ide> <ide> def collect_optimizer_hints(o, collector) <ide><path>activerecord/test/cases/adapters/mysql2/optimizer_hints_test.rb <ide> def test_optimizer_hints <ide> posts = posts.select(:id).where(author_id: [0, 1]) <ide> assert_includes posts.explain, "| index | index_posts_on_author_id | index_posts_on_author_id |" <ide> end <add> end <ide> <add> def test_optimizer_hints_is_sanitized <ide> assert_sql(%r{\ASELECT /\*\+ NO_RANGE_OPTIMIZATION\(posts index_posts_on_author_id\) \*/}) do <ide> posts = Post.optimizer_hints("/*+ NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id) */") <ide> posts = posts.select(:id).where(author_id: [0, 1]) <ide> assert_includes posts.explain, "| index | index_posts_on_author_id | index_posts_on_author_id |" <ide> end <ide> <add> assert_sql(%r{\ASELECT /\*\+ `posts`\.\*, \*/}) do <add> posts = Post.optimizer_hints("**// `posts`.*, //**") <add> posts = posts.select(:id).where(author_id: [0, 1]) <add> assert_equal({ "id" => 1 }, posts.first.as_json) <add> end <add> end <add> <add> def test_optimizer_hints_with_unscope <ide> assert_sql(%r{\ASELECT `posts`\.`id`}) do <ide> posts = Post.optimizer_hints("/*+ NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id) */") <ide> posts = posts.select(:id).where(author_id: [0, 1]) <ide><path>activerecord/test/cases/adapters/postgresql/optimizer_hints_test.rb <ide> def test_optimizer_hints <ide> posts = posts.select(:id).where(author_id: [0, 1]) <ide> assert_includes posts.explain, "Seq Scan on posts" <ide> end <add> end <ide> <add> def test_optimizer_hints_is_sanitized <ide> assert_sql(%r{\ASELECT /\*\+ SeqScan\(posts\) \*/}) do <ide> posts = Post.optimizer_hints("/*+ SeqScan(posts) */") <ide> posts = posts.select(:id).where(author_id: [0, 1]) <ide> assert_includes posts.explain, "Seq Scan on posts" <ide> end <ide> <add> assert_sql(%r{\ASELECT /\*\+ "posts"\.\*, \*/}) do <add> posts = Post.optimizer_hints("**// \"posts\".*, //**") <add> posts = posts.select(:id).where(author_id: [0, 1]) <add> assert_equal({ "id" => 1 }, posts.first.as_json) <add> end <add> end <add> <add> def test_optimizer_hints_with_unscope <ide> assert_sql(%r{\ASELECT "posts"\."id"}) do <ide> posts = Post.optimizer_hints("/*+ SeqScan(posts) */") <ide> posts = posts.select(:id).where(author_id: [0, 1])
3
Javascript
Javascript
fix no response event on continue request
be6844d1effa0427ca530e07b30de897b5dd7fb2
<ide><path>lib/internal/http2/core.js <ide> function onSessionHeaders(handle, id, cat, flags, headers, sensitiveHeaders) { <ide> } <ide> } else if (cat === NGHTTP2_HCAT_PUSH_RESPONSE) { <ide> event = 'push'; <del> // cat === NGHTTP2_HCAT_HEADERS: <del> } else if (!endOfStream && status !== undefined && status >= 200) { <add> } else if (status !== undefined && status >= 200) { <ide> event = 'response'; <ide> } else { <ide> event = endOfStream ? 'trailers' : 'headers'; <ide><path>test/parallel/test-http2-compat-expect-continue.js <ide> if (!common.hasCrypto) <ide> const assert = require('assert'); <ide> const http2 = require('http2'); <ide> <del>const testResBody = 'other stuff!\n'; <add>{ <add> const testResBody = 'other stuff!\n'; <ide> <del>// Checks the full 100-continue flow from client sending 'expect: 100-continue' <del>// through server receiving it, sending back :status 100, writing the rest of <del>// the request to finally the client receiving to. <add> // Checks the full 100-continue flow from client sending 'expect: 100-continue' <add> // through server receiving it, sending back :status 100, writing the rest of <add> // the request to finally the client receiving to. <ide> <del>const server = http2.createServer(); <add> const server = http2.createServer(); <ide> <del>let sentResponse = false; <add> let sentResponse = false; <ide> <del>server.on('request', common.mustCall((req, res) => { <del> res.end(testResBody); <del> sentResponse = true; <del>})); <add> server.on('request', common.mustCall((req, res) => { <add> res.end(testResBody); <add> sentResponse = true; <add> })); <add> <add> server.listen(0); <add> <add> server.on('listening', common.mustCall(() => { <add> let body = ''; <ide> <del>server.listen(0); <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> const req = client.request({ <add> ':method': 'POST', <add> 'expect': '100-continue' <add> }); <ide> <del>server.on('listening', common.mustCall(() => { <del> let body = ''; <add> let gotContinue = false; <add> req.on('continue', common.mustCall(() => { <add> gotContinue = true; <add> })); <ide> <del> const client = http2.connect(`http://localhost:${server.address().port}`); <del> const req = client.request({ <del> ':method': 'POST', <del> 'expect': '100-continue' <del> }); <add> req.on('response', common.mustCall((headers) => { <add> assert.strictEqual(gotContinue, true); <add> assert.strictEqual(sentResponse, true); <add> assert.strictEqual(headers[':status'], 200); <add> req.end(); <add> })); <ide> <del> let gotContinue = false; <del> req.on('continue', common.mustCall(() => { <del> gotContinue = true; <add> req.setEncoding('utf8'); <add> req.on('data', common.mustCall((chunk) => { body += chunk; })); <add> req.on('end', common.mustCall(() => { <add> assert.strictEqual(body, testResBody); <add> client.close(); <add> server.close(); <add> })); <ide> })); <add>} <add> <add>{ <add> // Checks the full 100-continue flow from client sending 'expect: 100-continue' <add> // through server receiving it and ending the request. <add> <add> const server = http2.createServer(); <ide> <del> req.on('response', common.mustCall((headers) => { <del> assert.strictEqual(gotContinue, true); <del> assert.strictEqual(sentResponse, true); <del> assert.strictEqual(headers[':status'], 200); <del> req.end(); <add> server.on('request', common.mustCall((req, res) => { <add> res.end(); <ide> })); <ide> <del> req.setEncoding('utf8'); <del> req.on('data', common.mustCall((chunk) => { body += chunk; })); <del> req.on('end', common.mustCall(() => { <del> assert.strictEqual(body, testResBody); <del> client.close(); <del> server.close(); <add> server.listen(0); <add> <add> server.on('listening', common.mustCall(() => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> const req = client.request({ <add> ':path': '/', <add> 'expect': '100-continue' <add> }); <add> <add> let gotContinue = false; <add> req.on('continue', common.mustCall(() => { <add> gotContinue = true; <add> })); <add> <add> let gotResponse = false; <add> req.on('response', common.mustCall(() => { <add> gotResponse = true; <add> })); <add> <add> req.setEncoding('utf8'); <add> req.on('end', common.mustCall(() => { <add> assert.strictEqual(gotContinue, true); <add> assert.strictEqual(gotResponse, true); <add> client.close(); <add> server.close(); <add> })); <ide> })); <del>})); <add>}
2
Python
Python
add random_crop with boxes and labels and tests
a1facb469a51e9e25f8fa19dd1ade7f44082f80f
<ide><path>official/vision/beta/ops/preprocess_ops.py <ide> def random_horizontal_flip(image, normalized_boxes=None, masks=None, seed=1): <ide> lambda: masks) <ide> <ide> return image, normalized_boxes, masks <add> <add> <add>def random_crop_image_with_boxes_and_labels(img, boxes, labels, min_scale, <add> aspect_ratio_range, <add> min_overlap_params, max_retry): <add> """Crops a random slice from the input image. <add> <add> The function will correspondingly recompute the bounding boxes and filter out <add> outside boxes and their labels. <add> <add> References: <add> [1] End-to-End Object Detection with Transformers <add> https://arxiv.org/abs/2005.12872 <add> <add> The preprocessing steps: <add> 1. Sample a minimum IoU overlap. <add> 2. For each trial, sample the new image width, height, and top-left corner. <add> 3. Compute the IoUs of bounding boxes with the cropped image and retry if <add> the maximum IoU is below the sampled threshold. <add> 4. Find boxes whose centers are in the cropped image. <add> 5. Compute new bounding boxes in the cropped region and only select those <add> boxes' labels. <add> <add> Args: <add> img: a 'Tensor' of shape [height, width, 3] representing the input image. <add> boxes: a 'Tensor' of shape [N, 4] representing the ground-truth bounding <add> boxes with (ymin, xmin, ymax, xmax). <add> labels: a 'Tensor' of shape [N,] representing the class labels of the boxes. <add> min_scale: a 'float' in [0.0, 1.0) indicating the lower bound of the random <add> scale variable. <add> aspect_ratio_range: a list of two 'float' that specifies the lower and upper <add> bound of the random aspect ratio. <add> min_overlap_params: a list of four 'float' representing the min value, max <add> value, step size, and offset for the minimum overlap sample. <add> max_retry: an 'int' representing the number of trials for cropping. If it is <add> exhausted, no cropping will be performed. <add> <add> Returns: <add> img: a Tensor representing the random cropped image. Can be the <add> original image if max_retry is exhausted. <add> boxes: a Tensor representing the bounding boxes in the cropped image. <add> labels: a Tensor representing the new bounding boxes' labels. <add> """ <add> <add> shape = tf.shape(img) <add> original_h = shape[0] <add> original_w = shape[1] <add> <add> minval, maxval, step, offset = min_overlap_params <add> <add> min_overlap = tf.math.floordiv( <add> tf.random.uniform([], minval=minval, maxval=maxval), step) * step - offset <add> <add> min_overlap = tf.clip_by_value(min_overlap, 0.0, 1.1) <add> <add> if min_overlap > 1.0: <add> return img, boxes, labels <add> <add> aspect_ratio_low = aspect_ratio_range[0] <add> aspect_ratio_high = aspect_ratio_range[1] <add> <add> for _ in tf.range(max_retry): <add> scale_h = tf.random.uniform([], min_scale, 1.0) <add> scale_w = tf.random.uniform([], min_scale, 1.0) <add> new_h = tf.cast( <add> scale_h * tf.cast(original_h, dtype=tf.float32), dtype=tf.int32) <add> new_w = tf.cast( <add> scale_w * tf.cast(original_w, dtype=tf.float32), dtype=tf.int32) <add> <add> # Aspect ratio has to be in the prespecified range <add> aspect_ratio = new_h / new_w <add> if aspect_ratio_low > aspect_ratio or aspect_ratio > aspect_ratio_high: <add> continue <add> <add> left = tf.random.uniform([], 0, original_w - new_w, dtype=tf.int32) <add> right = left + new_w <add> top = tf.random.uniform([], 0, original_h - new_h, dtype=tf.int32) <add> bottom = top + new_h <add> <add> normalized_left = tf.cast( <add> left, dtype=tf.float32) / tf.cast( <add> original_w, dtype=tf.float32) <add> normalized_right = tf.cast( <add> right, dtype=tf.float32) / tf.cast( <add> original_w, dtype=tf.float32) <add> normalized_top = tf.cast( <add> top, dtype=tf.float32) / tf.cast( <add> original_h, dtype=tf.float32) <add> normalized_bottom = tf.cast( <add> bottom, dtype=tf.float32) / tf.cast( <add> original_h, dtype=tf.float32) <add> <add> cropped_box = tf.expand_dims( <add> tf.stack([ <add> normalized_top, <add> normalized_left, <add> normalized_bottom, <add> normalized_right, <add> ]), <add> axis=0) <add> iou = box_ops.bbox_overlap( <add> tf.expand_dims(cropped_box, axis=0), <add> tf.expand_dims(boxes, axis=0)) # (1, 1, n_ground_truth) <add> iou = tf.squeeze(iou, axis=[0, 1]) <add> <add> # If not a single bounding box has a Jaccard overlap of greater than <add> # the minimum, try again <add> if tf.reduce_max(iou) < min_overlap: <add> continue <add> <add> centroids = box_ops.yxyx_to_cycxhw(boxes) <add> mask = tf.math.logical_and( <add> tf.math.logical_and(centroids[:, 0] > normalized_top, <add> centroids[:, 0] < normalized_bottom), <add> tf.math.logical_and(centroids[:, 1] > normalized_left, <add> centroids[:, 1] < normalized_right)) <add> # If not a single bounding box has its center in the crop, try again. <add> if tf.reduce_sum(tf.cast(mask, dtype=tf.int32)) > 0: <add> indices = tf.squeeze(tf.where(mask), axis=1) <add> <add> filtered_boxes = tf.gather(boxes, indices) <add> <add> boxes = tf.clip_by_value( <add> (filtered_boxes[..., :] * tf.cast( <add> tf.stack([original_h, original_w, original_h, original_w]), <add> dtype=tf.float32) - <add> tf.cast(tf.stack([top, left, top, left]), dtype=tf.float32)) / <add> tf.cast(tf.stack([new_h, new_w, new_h, new_w]), dtype=tf.float32), <add> 0.0, 1.0) <add> <add> img = tf.image.crop_to_bounding_box(img, top, left, bottom - top, <add> right - left) <add> <add> labels = tf.gather(labels, indices) <add> break <add> <add> return img, boxes, labels <add> <add> <add>def random_crop(image, <add> boxes, <add> labels, <add> min_scale=0.3, <add> aspect_ratio_range=(0.5, 2.0), <add> min_overlap_params=(0.0, 1.4, 0.2, 0.1), <add> max_retry=50, <add> seed=None): <add> """Randomly crop the image and boxes, filtering labels. <add> <add> Args: <add> image: a 'Tensor' of shape [height, width, 3] representing the input image. <add> boxes: a 'Tensor' of shape [N, 4] representing the ground-truth bounding <add> boxes with (ymin, xmin, ymax, xmax). <add> labels: a 'Tensor' of shape [N,] representing the class labels of the boxes. <add> min_scale: a 'float' in [0.0, 1.0) indicating the lower bound of the random <add> scale variable. <add> aspect_ratio_range: a list of two 'float' that specifies the lower and upper <add> bound of the random aspect ratio. <add> min_overlap_params: a list of four 'float' representing the min value, max <add> value, step size, and offset for the minimum overlap sample. <add> max_retry: an 'int' representing the number of trials for cropping. If it is <add> exhausted, no cropping will be performed. <add> seed: the random number seed of int, but could be None. <add> <add> Returns: <add> image: a Tensor representing the random cropped image. Can be the <add> original image if max_retry is exhausted. <add> boxes: a Tensor representing the bounding boxes in the cropped image. <add> labels: a Tensor representing the new bounding boxes' labels. <add> """ <add> with tf.name_scope('random_crop'): <add> do_crop = tf.greater(tf.random.uniform([], seed=seed), 0.5) <add> if do_crop: <add> return random_crop_image_with_boxes_and_labels(image, boxes, labels, <add> min_scale, <add> aspect_ratio_range, <add> min_overlap_params, <add> max_retry) <add> else: <add> return image, boxes, labels <ide><path>official/vision/beta/ops/preprocess_ops_test.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <del> <ide> """Tests for preprocess_ops.py.""" <ide> <ide> import io <ide> class InputUtilsTest(parameterized.TestCase, tf.test.TestCase): <ide> ([12, 2], 10), <ide> ([13, 2, 3], 10), <ide> ) <del> def testPadToFixedSize(self, input_shape, output_size): <add> def test_pad_to_fixed_size(self, input_shape, output_size): <ide> # Copies input shape to padding shape. <ide> clip_shape = input_shape[:] <ide> clip_shape[0] = min(output_size, clip_shape[0]) <ide> def testPadToFixedSize(self, input_shape, output_size): <ide> (100, 256, 128, 256, 32, 1.0, 1.0, 128, 256), <ide> (200, 512, 200, 128, 32, 0.25, 0.25, 224, 128), <ide> ) <del> def testResizeAndCropImageRectangluarCase(self, <del> input_height, <del> input_width, <del> desired_height, <del> desired_width, <del> stride, <del> scale_y, <del> scale_x, <del> output_height, <del> output_width): <add> def test_resize_and_crop_image_rectangluar_case(self, input_height, <add> input_width, desired_height, <add> desired_width, stride, <add> scale_y, scale_x, <add> output_height, output_width): <ide> image = tf.convert_to_tensor( <ide> np.random.rand(input_height, input_width, 3)) <ide> <ide> def testResizeAndCropImageRectangluarCase(self, <ide> (100, 200, 220, 220, 32, 1.1, 1.1, 224, 224), <ide> (512, 512, 1024, 1024, 32, 2.0, 2.0, 1024, 1024), <ide> ) <del> def testResizeAndCropImageSquareCase(self, <del> input_height, <del> input_width, <del> desired_height, <del> desired_width, <del> stride, <del> scale_y, <del> scale_x, <del> output_height, <del> output_width): <add> def test_resize_and_crop_image_square_case(self, input_height, input_width, <add> desired_height, desired_width, <add> stride, scale_y, scale_x, <add> output_height, output_width): <ide> image = tf.convert_to_tensor( <ide> np.random.rand(input_height, input_width, 3)) <ide> <ide> def testResizeAndCropImageSquareCase(self, <ide> (100, 200, 80, 100, 32, 0.5, 0.5, 50, 100, 96, 128), <ide> (200, 100, 80, 100, 32, 0.5, 0.5, 100, 50, 128, 96), <ide> ) <del> def testResizeAndCropImageV2(self, <del> input_height, <del> input_width, <del> short_side, <del> long_side, <del> stride, <del> scale_y, <del> scale_x, <del> desired_height, <del> desired_width, <del> output_height, <del> output_width): <add> def test_resize_and_crop_image_v2(self, input_height, input_width, short_side, <add> long_side, stride, scale_y, scale_x, <add> desired_height, desired_width, <add> output_height, output_width): <ide> image = tf.convert_to_tensor( <ide> np.random.rand(input_height, input_width, 3)) <ide> image_shape = tf.shape(image)[0:2] <ide> def testResizeAndCropImageV2(self, <ide> @parameterized.parameters( <ide> (400, 600), (600, 400), <ide> ) <del> def testCenterCropImage(self, <del> input_height, <del> input_width): <add> def test_center_crop_image(self, input_height, input_width): <ide> image = tf.convert_to_tensor( <ide> np.random.rand(input_height, input_width, 3)) <ide> cropped_image = preprocess_ops.center_crop_image(image) <ide> def testCenterCropImage(self, <ide> @parameterized.parameters( <ide> (400, 600), (600, 400), <ide> ) <del> def testCenterCropImageV2(self, <del> input_height, <del> input_width): <add> def test_center_crop_image_v2(self, input_height, input_width): <ide> image_bytes = tf.constant( <ide> _encode_image( <ide> np.uint8(np.random.rand(input_height, input_width, 3) * 255), <ide> def testCenterCropImageV2(self, <ide> @parameterized.parameters( <ide> (400, 600), (600, 400), <ide> ) <del> def testRandomCropImage(self, <del> input_height, <del> input_width): <add> def test_random_crop_image(self, input_height, input_width): <ide> image = tf.convert_to_tensor( <ide> np.random.rand(input_height, input_width, 3)) <ide> _ = preprocess_ops.random_crop_image(image) <ide> <ide> @parameterized.parameters( <ide> (400, 600), (600, 400), <ide> ) <del> def testRandomCropImageV2(self, <del> input_height, <del> input_width): <add> def test_random_crop_image_v2(self, input_height, input_width): <ide> image_bytes = tf.constant( <ide> _encode_image( <ide> np.uint8(np.random.rand(input_height, input_width, 3) * 255), <ide> def testRandomCropImageV2(self, <ide> _ = preprocess_ops.random_crop_image_v2( <ide> image_bytes, tf.constant([input_height, input_width, 3], tf.int32)) <ide> <add> @parameterized.parameters((640, 640, 20), (1280, 1280, 30)) <add> def test_random_crop(self, input_height, input_width, num_boxes): <add> image = tf.convert_to_tensor(np.random.rand(input_height, input_width, 3)) <add> boxes_height = np.random.randint(0, input_height, size=(num_boxes, 1)) <add> top = np.random.randint(0, high=(input_height - boxes_height)) <add> down = top + boxes_height <add> boxes_width = np.random.randint(0, input_width, size=(num_boxes, 1)) <add> left = np.random.randint(0, high=(input_width - boxes_width)) <add> right = left + boxes_width <add> boxes = tf.constant( <add> np.concatenate([top, left, down, right], axis=-1), tf.float32) <add> labels = tf.constant( <add> np.random.randint(low=0, high=num_boxes, size=(num_boxes,)), tf.int64) <add> _ = preprocess_ops.random_crop(image, boxes, labels) <add> <ide> <ide> if __name__ == '__main__': <ide> tf.test.main()
2
PHP
PHP
use the correct function to rm directories
4d3d54ffd541c095b131b2f48ea8691b6d8494e1
<ide><path>lib/Cake/Test/TestCase/Cache/Engine/FileEngineTest.php <ide> class FileEngineTest extends TestCase { <ide> public function setUp() { <ide> parent::setUp(); <ide> Cache::enable(); <add> Cache::drop('file_test'); <ide> Cache::config('file_test', [ <ide> 'engine' => 'File', <ide> 'path' => TMP . 'tests', <ide> ]); <add> Cache::clear(false, 'file_test'); <ide> } <ide> <ide> /** <ide> public function setUp() { <ide> * @return void <ide> */ <ide> public function tearDown() { <del> parent::tearDown(); <del> Cache::clear(false, 'file_test'); <ide> Cache::drop('file_test'); <ide> Cache::drop('file_groups'); <ide> Cache::drop('file_groups2'); <ide> Cache::drop('file_groups3'); <add> parent::tearDown(); <ide> } <ide> <ide> /** <ide> public function testWriteQuotedString() { <ide> */ <ide> public function testPathDoesNotExist() { <ide> $this->skipIf(is_dir(TMP . 'tests' . DS . 'autocreate'), 'Cannot run if test directory exists.'); <add> Configure::write('debug', 2); <ide> <ide> Cache::drop('file_test'); <ide> Cache::config('file_test', array( <ide> public function testPathDoesNotExist() { <ide> Cache::read('Test', 'file_test'); <ide> <ide> $this->assertTrue(file_exists(TMP . 'tests/autocreate'), 'Dir should exist.'); <del> unlink(TMP . 'tests/autocreate'); <add> <add> // Cleanup <add> rmdir(TMP . 'tests/autocreate'); <ide> } <ide> <ide> /** <ide> public function testPathDoesNotExistDebugOff() { <ide> $this->skipIf(is_dir(TMP . 'tests/autocreate'), 'Cannot run if test directory exists.'); <ide> Configure::write('debug', 0); <ide> <del> Cache::drop('file_test'); <del> Cache::config('file_test', array( <add> Cache::drop('file_groups'); <add> Cache::config('file_groups', array( <ide> 'engine' => 'File', <ide> 'duration' => '+1 year', <ide> 'prefix' => 'testing_invalid_', <ide> 'path' => TMP . 'tests/autocreate', <ide> )); <del> Cache::read('Test', 'test'); <add> Cache::read('Test', 'file_groups'); <add> Cache::drop('file_groups'); <ide> } <ide> <ide> /**
1
Python
Python
add option to propagate tags in ecsoperator
d590e5e7679322bebb1472fa8c7ec6d183e4154a
<ide><path>airflow/providers/amazon/aws/operators/ecs.py <ide> def __init__(self, task_definition, cluster, overrides, # pylint: disable=too-m <ide> aws_conn_id=None, region_name=None, launch_type='EC2', <ide> group=None, placement_constraints=None, platform_version='LATEST', <ide> network_configuration=None, tags=None, awslogs_group=None, <del> awslogs_region=None, awslogs_stream_prefix=None, **kwargs): <add> awslogs_region=None, awslogs_stream_prefix=None, propagate_tags=None, **kwargs): <ide> super().__init__(**kwargs) <ide> <ide> self.aws_conn_id = aws_conn_id <ide> def __init__(self, task_definition, cluster, overrides, # pylint: disable=too-m <ide> self.awslogs_group = awslogs_group <ide> self.awslogs_stream_prefix = awslogs_stream_prefix <ide> self.awslogs_region = awslogs_region <add> self.propagate_tags = propagate_tags <ide> <ide> if self.awslogs_region is None: <ide> self.awslogs_region = region_name <ide> def execute(self, context): <ide> run_opts['networkConfiguration'] = self.network_configuration <ide> if self.tags is not None: <ide> run_opts['tags'] = [{'key': k, 'value': v} for (k, v) in self.tags.items()] <add> if self.propagate_tags is not None: <add> run_opts['propagateTags'] = self.propagate_tags <ide> <ide> response = self.client.run_task(**run_opts) <ide> <ide><path>tests/providers/amazon/aws/operators/test_ecs.py <ide> def set_up_operator(self, aws_hook_mock, **kwargs): <ide> 'securityGroups': ['sg-123abc'], <ide> 'subnets': ['subnet-123456ab'] <ide> } <del> } <add> }, <add> 'propagate_tags': 'TASK_DEFINITION' <ide> } <ide> self.ecs = ECSOperator(**self.ecs_operator_args, **kwargs) <ide> self.ecs.get_hook() <ide> def test_execute_without_failures(self, launch_type, tags, <ide> 'subnets': ['subnet-123456ab'] <ide> } <ide> }, <add> propagateTags='TASK_DEFINITION', <ide> **extend_args <ide> ) <ide> <ide> def test_execute_with_failures(self): <ide> 'securityGroups': ['sg-123abc'], <ide> 'subnets': ['subnet-123456ab'], <ide> } <del> } <add> }, <add> propagateTags='TASK_DEFINITION' <ide> ) <ide> <ide> def test_wait_end_tasks(self):
2
Text
Text
add v3.4.8 to changelog
900028f01704feab6c0411b0efac97db91105c26
<ide><path>CHANGELOG.md <ide> - [#16978](https://github.com/emberjs/ember.js/pull/16978) [BUGFIX] Properly teardown alias <ide> - [#16877](https://github.com/emberjs/ember.js/pull/16877) [CLEANUP] Allow routes to be named "array" and "object" <ide> <add>### v3.4.8 (January 22, 2019) <add> <add>* Upgrade @glimmer/* packages to 0.35.10. Fixes a few issues: <add> * Usage of positional arguments with custom components. <add> * Forwarding attributes via `...attributes` to a dynamic component. <add> * Prevent errors when rendering many template blocks (`Error: Operand over 16-bits. Got 65536`). <add> <ide> ### v3.4.7 (December 7, 2018) <ide> <ide> - [#17271](https://github.com/emberjs/ember.js/pull/17271) [BUGFIX] Update `backburner.js` to 2.4.2.
1
Text
Text
update the link to the jsdom repository
a62309e01b3c76d2b73560ca666c454b7bbfcb77
<ide><path>build/fixtures/README.md <ide> To include jQuery in [Node](https://nodejs.org/), first install with npm. <ide> npm install jquery <ide> ``` <ide> <del>For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as [jsdom](https://github.com/tmpvar/jsdom). This can be useful for testing purposes. <add>For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as [jsdom](https://github.com/jsdom/jsdom). This can be useful for testing purposes. <ide> <ide> ```js <ide> const { JSDOM } = require( "jsdom" );
1
Javascript
Javascript
relax check in verify-graph
ee59763ab3b67f8792ed53a4d098212a040994f9
<ide><path>test/async-hooks/verify-graph.js <ide> module.exports = function verifyGraph(hooks, graph) { <ide> } <ide> assert.strictEqual(errors.length, 0); <ide> <del> // Verify that all expected types are present <add> // Verify that all expected types are present (but more/others are allowed) <ide> const expTypes = Object.create(null); <ide> for (let i = 0; i < graph.length; i++) { <ide> if (expTypes[graph[i].type] == null) expTypes[graph[i].type] = 0; <ide> expTypes[graph[i].type]++; <ide> } <ide> <ide> for (const type in expTypes) { <del> assert.strictEqual(typeSeen[type], expTypes[type], <del> `Type '${type}': expecting: ${expTypes[type]} ` + <del> `found ${typeSeen[type]}`); <add> assert.ok(typeSeen[type] >= expTypes[type], <add> `Type '${type}': expecting: ${expTypes[type]} ` + <add> `found: ${typeSeen[type]}`); <ide> } <ide> }; <ide>
1
Python
Python
remove useless classes
af41dbe0c479769402c46c0b99b841e781a8fa87
<ide><path>tests/test_basic.py <ide> from werkzeug.routing import BuildError <ide> <ide> <del>class TestBasicFunctionality(TestFlask): <add>class TestBasicFunctionality(object): <ide> <ide> def test_options_work(self): <ide> app = flask.Flask(__name__) <ide> def test_g_iteration_protocol(self): <ide> assert sorted(flask.g) == ['bar', 'foo'] <ide> <ide> <del>class TestSubdomain(TestFlask): <add>class TestSubdomain(object): <ide> <ide> def test_basic_support(self): <ide> app = flask.Flask(__name__) <ide><path>tests/test_blueprints.py <ide> from jinja2 import TemplateNotFound <ide> <ide> <del>class TestBlueprint(TestFlask): <add>def test_blueprint_specific_error_handling(): <add> frontend = flask.Blueprint('frontend', __name__) <add> backend = flask.Blueprint('backend', __name__) <add> sideend = flask.Blueprint('sideend', __name__) <ide> <del> def test_blueprint_specific_error_handling(self): <del> frontend = flask.Blueprint('frontend', __name__) <del> backend = flask.Blueprint('backend', __name__) <del> sideend = flask.Blueprint('sideend', __name__) <add> @frontend.errorhandler(403) <add> def frontend_forbidden(e): <add> return 'frontend says no', 403 <ide> <del> @frontend.errorhandler(403) <del> def frontend_forbidden(e): <del> return 'frontend says no', 403 <add> @frontend.route('/frontend-no') <add> def frontend_no(): <add> flask.abort(403) <ide> <del> @frontend.route('/frontend-no') <del> def frontend_no(): <del> flask.abort(403) <add> @backend.errorhandler(403) <add> def backend_forbidden(e): <add> return 'backend says no', 403 <ide> <del> @backend.errorhandler(403) <del> def backend_forbidden(e): <del> return 'backend says no', 403 <add> @backend.route('/backend-no') <add> def backend_no(): <add> flask.abort(403) <ide> <del> @backend.route('/backend-no') <del> def backend_no(): <del> flask.abort(403) <add> @sideend.route('/what-is-a-sideend') <add> def sideend_no(): <add> flask.abort(403) <ide> <del> @sideend.route('/what-is-a-sideend') <del> def sideend_no(): <del> flask.abort(403) <add> app = flask.Flask(__name__) <add> app.register_blueprint(frontend) <add> app.register_blueprint(backend) <add> app.register_blueprint(sideend) <ide> <del> app = flask.Flask(__name__) <del> app.register_blueprint(frontend) <del> app.register_blueprint(backend) <del> app.register_blueprint(sideend) <add> @app.errorhandler(403) <add> def app_forbidden(e): <add> return 'application itself says no', 403 <add> <add> c = app.test_client() <add> <add> assert c.get('/frontend-no').data == b'frontend says no' <add> assert c.get('/backend-no').data == b'backend says no' <add> assert c.get('/what-is-a-sideend').data == b'application itself says no' <add> <add>def test_blueprint_specific_user_error_handling(): <add> class MyDecoratorException(Exception): <add> pass <add> class MyFunctionException(Exception): <add> pass <add> <add> blue = flask.Blueprint('blue', __name__) <add> <add> @blue.errorhandler(MyDecoratorException) <add> def my_decorator_exception_handler(e): <add> assert isinstance(e, MyDecoratorException) <add> return 'boom' <add> <add> def my_function_exception_handler(e): <add> assert isinstance(e, MyFunctionException) <add> return 'bam' <add> blue.register_error_handler(MyFunctionException, my_function_exception_handler) <add> <add> @blue.route('/decorator') <add> def blue_deco_test(): <add> raise MyDecoratorException() <add> @blue.route('/function') <add> def blue_func_test(): <add> raise MyFunctionException() <add> <add> app = flask.Flask(__name__) <add> app.register_blueprint(blue) <add> <add> c = app.test_client() <add> <add> assert c.get('/decorator').data == b'boom' <add> assert c.get('/function').data == b'bam' <add> <add>def test_blueprint_url_definitions(): <add> bp = flask.Blueprint('test', __name__) <add> <add> @bp.route('/foo', defaults={'baz': 42}) <add> def foo(bar, baz): <add> return '%s/%d' % (bar, baz) <add> <add> @bp.route('/bar') <add> def bar(bar): <add> return text_type(bar) <add> <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23}) <add> app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19}) <add> <add> c = app.test_client() <add> assert c.get('/1/foo').data == b'23/42' <add> assert c.get('/2/foo').data == b'19/42' <add> assert c.get('/1/bar').data == b'23' <add> assert c.get('/2/bar').data == b'19' <add> <add>def test_blueprint_url_processors(): <add> bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>') <add> <add> @bp.url_defaults <add> def add_language_code(endpoint, values): <add> values.setdefault('lang_code', flask.g.lang_code) <add> <add> @bp.url_value_preprocessor <add> def pull_lang_code(endpoint, values): <add> flask.g.lang_code = values.pop('lang_code') <add> <add> @bp.route('/') <add> def index(): <add> return flask.url_for('.about') <add> <add> @bp.route('/about') <add> def about(): <add> return flask.url_for('.index') <add> <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp) <add> <add> c = app.test_client() <add> <add> assert c.get('/de/').data == b'/de/about' <add> assert c.get('/de/about').data == b'/de/' <add> <add>def test_templates_and_static(): <add> from blueprintapp import app <add> c = app.test_client() <add> <add> rv = c.get('/') <add> assert rv.data == b'Hello from the Frontend' <add> rv = c.get('/admin/') <add> assert rv.data == b'Hello from the Admin' <add> rv = c.get('/admin/index2') <add> assert rv.data == b'Hello from the Admin' <add> rv = c.get('/admin/static/test.txt') <add> assert rv.data.strip() == b'Admin File' <add> rv.close() <add> rv = c.get('/admin/static/css/test.css') <add> assert rv.data.strip() == b'/* nested file */' <add> rv.close() <add> <add> # try/finally, in case other tests use this app for Blueprint tests. <add> max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] <add> try: <add> expected_max_age = 3600 <add> if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age: <add> expected_max_age = 7200 <add> app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age <add> rv = c.get('/admin/static/css/test.css') <add> cc = parse_cache_control_header(rv.headers['Cache-Control']) <add> assert cc.max_age == expected_max_age <add> rv.close() <add> finally: <add> app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default <ide> <del> @app.errorhandler(403) <del> def app_forbidden(e): <del> return 'application itself says no', 403 <add> with app.test_request_context(): <add> assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt' <ide> <del> c = app.test_client() <add> with app.test_request_context(): <add> try: <add> flask.render_template('missing.html') <add> except TemplateNotFound as e: <add> assert e.name == 'missing.html' <add> else: <add> assert 0, 'expected exception' <ide> <del> assert c.get('/frontend-no').data == b'frontend says no' <del> assert c.get('/backend-no').data == b'backend says no' <del> assert c.get('/what-is-a-sideend').data == b'application itself says no' <add> with flask.Flask(__name__).test_request_context(): <add> assert flask.render_template('nested/nested.txt') == 'I\'m nested' <ide> <del> def test_blueprint_specific_user_error_handling(self): <del> class MyDecoratorException(Exception): <del> pass <del> class MyFunctionException(Exception): <del> pass <add>def test_default_static_cache_timeout(): <add> app = flask.Flask(__name__) <add> class MyBlueprint(flask.Blueprint): <add> def get_send_file_max_age(self, filename): <add> return 100 <ide> <del> blue = flask.Blueprint('blue', __name__) <add> blueprint = MyBlueprint('blueprint', __name__, static_folder='static') <add> app.register_blueprint(blueprint) <ide> <del> @blue.errorhandler(MyDecoratorException) <del> def my_decorator_exception_handler(e): <del> assert isinstance(e, MyDecoratorException) <del> return 'boom' <add> # try/finally, in case other tests use this app for Blueprint tests. <add> max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] <add> try: <add> with app.test_request_context(): <add> unexpected_max_age = 3600 <add> if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age: <add> unexpected_max_age = 7200 <add> app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age <add> rv = blueprint.send_static_file('index.html') <add> cc = parse_cache_control_header(rv.headers['Cache-Control']) <add> assert cc.max_age == 100 <add> rv.close() <add> finally: <add> app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default <ide> <del> def my_function_exception_handler(e): <del> assert isinstance(e, MyFunctionException) <del> return 'bam' <del> blue.register_error_handler(MyFunctionException, my_function_exception_handler) <add>def test_templates_list(): <add> from blueprintapp import app <add> templates = sorted(app.jinja_env.list_templates()) <add> assert templates == ['admin/index.html', 'frontend/index.html'] <ide> <del> @blue.route('/decorator') <del> def blue_deco_test(): <del> raise MyDecoratorException() <del> @blue.route('/function') <del> def blue_func_test(): <del> raise MyFunctionException() <add>def test_dotted_names(): <add> frontend = flask.Blueprint('myapp.frontend', __name__) <add> backend = flask.Blueprint('myapp.backend', __name__) <ide> <del> app = flask.Flask(__name__) <del> app.register_blueprint(blue) <add> @frontend.route('/fe') <add> def frontend_index(): <add> return flask.url_for('myapp.backend.backend_index') <ide> <del> c = app.test_client() <add> @frontend.route('/fe2') <add> def frontend_page2(): <add> return flask.url_for('.frontend_index') <ide> <del> assert c.get('/decorator').data == b'boom' <del> assert c.get('/function').data == b'bam' <add> @backend.route('/be') <add> def backend_index(): <add> return flask.url_for('myapp.frontend.frontend_index') <ide> <del> def test_blueprint_url_definitions(self): <del> bp = flask.Blueprint('test', __name__) <add> app = flask.Flask(__name__) <add> app.register_blueprint(frontend) <add> app.register_blueprint(backend) <ide> <del> @bp.route('/foo', defaults={'baz': 42}) <del> def foo(bar, baz): <del> return '%s/%d' % (bar, baz) <add> c = app.test_client() <add> assert c.get('/fe').data.strip() == b'/be' <add> assert c.get('/fe2').data.strip() == b'/fe' <add> assert c.get('/be').data.strip() == b'/fe' <ide> <del> @bp.route('/bar') <del> def bar(bar): <del> return text_type(bar) <add>def test_dotted_names_from_app(): <add> app = flask.Flask(__name__) <add> app.testing = True <add> test = flask.Blueprint('test', __name__) <ide> <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23}) <del> app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19}) <add> @app.route('/') <add> def app_index(): <add> return flask.url_for('test.index') <ide> <del> c = app.test_client() <del> assert c.get('/1/foo').data == b'23/42' <del> assert c.get('/2/foo').data == b'19/42' <del> assert c.get('/1/bar').data == b'23' <del> assert c.get('/2/bar').data == b'19' <add> @test.route('/test/') <add> def index(): <add> return flask.url_for('app_index') <ide> <del> def test_blueprint_url_processors(self): <del> bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>') <add> app.register_blueprint(test) <ide> <del> @bp.url_defaults <del> def add_language_code(endpoint, values): <del> values.setdefault('lang_code', flask.g.lang_code) <add> with app.test_client() as c: <add> rv = c.get('/') <add> assert rv.data == b'/test/' <ide> <del> @bp.url_value_preprocessor <del> def pull_lang_code(endpoint, values): <del> flask.g.lang_code = values.pop('lang_code') <add>def test_empty_url_defaults(): <add> bp = flask.Blueprint('bp', __name__) <ide> <del> @bp.route('/') <del> def index(): <del> return flask.url_for('.about') <add> @bp.route('/', defaults={'page': 1}) <add> @bp.route('/page/<int:page>') <add> def something(page): <add> return str(page) <ide> <del> @bp.route('/about') <del> def about(): <del> return flask.url_for('.index') <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp) <ide> <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp) <add> c = app.test_client() <add> assert c.get('/').data == b'1' <add> assert c.get('/page/2').data == b'2' <ide> <del> c = app.test_client() <add>def test_route_decorator_custom_endpoint(): <ide> <del> assert c.get('/de/').data == b'/de/about' <del> assert c.get('/de/about').data == b'/de/' <add> bp = flask.Blueprint('bp', __name__) <ide> <del> def test_templates_and_static(self): <del> from blueprintapp import app <del> c = app.test_client() <add> @bp.route('/foo') <add> def foo(): <add> return flask.request.endpoint <ide> <del> rv = c.get('/') <del> assert rv.data == b'Hello from the Frontend' <del> rv = c.get('/admin/') <del> assert rv.data == b'Hello from the Admin' <del> rv = c.get('/admin/index2') <del> assert rv.data == b'Hello from the Admin' <del> rv = c.get('/admin/static/test.txt') <del> assert rv.data.strip() == b'Admin File' <del> rv.close() <del> rv = c.get('/admin/static/css/test.css') <del> assert rv.data.strip() == b'/* nested file */' <del> rv.close() <add> @bp.route('/bar', endpoint='bar') <add> def foo_bar(): <add> return flask.request.endpoint <ide> <del> # try/finally, in case other tests use this app for Blueprint tests. <del> max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] <del> try: <del> expected_max_age = 3600 <del> if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age: <del> expected_max_age = 7200 <del> app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age <del> rv = c.get('/admin/static/css/test.css') <del> cc = parse_cache_control_header(rv.headers['Cache-Control']) <del> assert cc.max_age == expected_max_age <del> rv.close() <del> finally: <del> app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default <add> @bp.route('/bar/123', endpoint='123') <add> def foo_bar_foo(): <add> return flask.request.endpoint <ide> <del> with app.test_request_context(): <del> assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt' <add> @bp.route('/bar/foo') <add> def bar_foo(): <add> return flask.request.endpoint <ide> <del> with app.test_request_context(): <del> try: <del> flask.render_template('missing.html') <del> except TemplateNotFound as e: <del> assert e.name == 'missing.html' <del> else: <del> assert 0, 'expected exception' <del> <del> with flask.Flask(__name__).test_request_context(): <del> assert flask.render_template('nested/nested.txt') == 'I\'m nested' <del> <del> def test_default_static_cache_timeout(self): <del> app = flask.Flask(__name__) <del> class MyBlueprint(flask.Blueprint): <del> def get_send_file_max_age(self, filename): <del> return 100 <del> <del> blueprint = MyBlueprint('blueprint', __name__, static_folder='static') <del> app.register_blueprint(blueprint) <del> <del> # try/finally, in case other tests use this app for Blueprint tests. <del> max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] <del> try: <del> with app.test_request_context(): <del> unexpected_max_age = 3600 <del> if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age: <del> unexpected_max_age = 7200 <del> app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age <del> rv = blueprint.send_static_file('index.html') <del> cc = parse_cache_control_header(rv.headers['Cache-Control']) <del> assert cc.max_age == 100 <del> rv.close() <del> finally: <del> app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default <del> <del> def test_templates_list(self): <del> from blueprintapp import app <del> templates = sorted(app.jinja_env.list_templates()) <del> assert templates == ['admin/index.html', 'frontend/index.html'] <del> <del> def test_dotted_names(self): <del> frontend = flask.Blueprint('myapp.frontend', __name__) <del> backend = flask.Blueprint('myapp.backend', __name__) <del> <del> @frontend.route('/fe') <del> def frontend_index(): <del> return flask.url_for('myapp.backend.backend_index') <del> <del> @frontend.route('/fe2') <del> def frontend_page2(): <del> return flask.url_for('.frontend_index') <del> <del> @backend.route('/be') <del> def backend_index(): <del> return flask.url_for('myapp.frontend.frontend_index') <del> <del> app = flask.Flask(__name__) <del> app.register_blueprint(frontend) <del> app.register_blueprint(backend) <del> <del> c = app.test_client() <del> assert c.get('/fe').data.strip() == b'/be' <del> assert c.get('/fe2').data.strip() == b'/fe' <del> assert c.get('/be').data.strip() == b'/fe' <del> <del> def test_dotted_names_from_app(self): <del> app = flask.Flask(__name__) <del> app.testing = True <del> test = flask.Blueprint('test', __name__) <del> <del> @app.route('/') <del> def app_index(): <del> return flask.url_for('test.index') <del> <del> @test.route('/test/') <del> def index(): <del> return flask.url_for('app_index') <del> <del> app.register_blueprint(test) <del> <del> with app.test_client() as c: <del> rv = c.get('/') <del> assert rv.data == b'/test/' <del> <del> def test_empty_url_defaults(self): <del> bp = flask.Blueprint('bp', __name__) <del> <del> @bp.route('/', defaults={'page': 1}) <del> @bp.route('/page/<int:page>') <del> def something(page): <del> return str(page) <del> <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp) <del> <del> c = app.test_client() <del> assert c.get('/').data == b'1' <del> assert c.get('/page/2').data == b'2' <del> <del> def test_route_decorator_custom_endpoint(self): <del> <del> bp = flask.Blueprint('bp', __name__) <del> <del> @bp.route('/foo') <del> def foo(): <del> return flask.request.endpoint <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <ide> <del> @bp.route('/bar', endpoint='bar') <del> def foo_bar(): <del> return flask.request.endpoint <add> @app.route('/') <add> def index(): <add> return flask.request.endpoint <ide> <del> @bp.route('/bar/123', endpoint='123') <del> def foo_bar_foo(): <del> return flask.request.endpoint <add> c = app.test_client() <add> assert c.get('/').data == b'index' <add> assert c.get('/py/foo').data == b'bp.foo' <add> assert c.get('/py/bar').data == b'bp.bar' <add> assert c.get('/py/bar/123').data == b'bp.123' <add> assert c.get('/py/bar/foo').data == b'bp.bar_foo' <ide> <del> @bp.route('/bar/foo') <del> def bar_foo(): <del> return flask.request.endpoint <add>def test_route_decorator_custom_endpoint_with_dots(): <add> bp = flask.Blueprint('bp', __name__) <ide> <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <add> @bp.route('/foo') <add> def foo(): <add> return flask.request.endpoint <ide> <del> @app.route('/') <del> def index(): <add> try: <add> @bp.route('/bar', endpoint='bar.bar') <add> def foo_bar(): <ide> return flask.request.endpoint <add> except AssertionError: <add> pass <add> else: <add> raise AssertionError('expected AssertionError not raised') <ide> <del> c = app.test_client() <del> assert c.get('/').data == b'index' <del> assert c.get('/py/foo').data == b'bp.foo' <del> assert c.get('/py/bar').data == b'bp.bar' <del> assert c.get('/py/bar/123').data == b'bp.123' <del> assert c.get('/py/bar/foo').data == b'bp.bar_foo' <del> <del> def test_route_decorator_custom_endpoint_with_dots(self): <del> bp = flask.Blueprint('bp', __name__) <del> <del> @bp.route('/foo') <del> def foo(): <add> try: <add> @bp.route('/bar/123', endpoint='bar.123') <add> def foo_bar_foo(): <ide> return flask.request.endpoint <del> <del> try: <del> @bp.route('/bar', endpoint='bar.bar') <del> def foo_bar(): <del> return flask.request.endpoint <del> except AssertionError: <del> pass <del> else: <del> raise AssertionError('expected AssertionError not raised') <del> <del> try: <del> @bp.route('/bar/123', endpoint='bar.123') <del> def foo_bar_foo(): <del> return flask.request.endpoint <del> except AssertionError: <del> pass <del> else: <del> raise AssertionError('expected AssertionError not raised') <del> <del> def foo_foo_foo(): <del> pass <del> <del> pytest.raises( <del> AssertionError, <del> lambda: bp.add_url_rule( <del> '/bar/123', endpoint='bar.123', view_func=foo_foo_foo <del> ) <del> ) <del> <del> pytest.raises( <del> AssertionError, <del> bp.route('/bar/123', endpoint='bar.123'), <del> lambda: None <add> except AssertionError: <add> pass <add> else: <add> raise AssertionError('expected AssertionError not raised') <add> <add> def foo_foo_foo(): <add> pass <add> <add> pytest.raises( <add> AssertionError, <add> lambda: bp.add_url_rule( <add> '/bar/123', endpoint='bar.123', view_func=foo_foo_foo <ide> ) <del> <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> <del> c = app.test_client() <del> assert c.get('/py/foo').data == b'bp.foo' <del> # The rule's didn't actually made it through <del> rv = c.get('/py/bar') <del> assert rv.status_code == 404 <del> rv = c.get('/py/bar/123') <del> assert rv.status_code == 404 <del> <del> def test_template_filter(self): <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_filter() <del> def my_reverse(s): <del> return s[::-1] <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> assert 'my_reverse' in app.jinja_env.filters.keys() <del> assert app.jinja_env.filters['my_reverse'] == my_reverse <del> assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' <del> <del> def test_add_template_filter(self): <del> bp = flask.Blueprint('bp', __name__) <del> def my_reverse(s): <del> return s[::-1] <del> bp.add_app_template_filter(my_reverse) <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> assert 'my_reverse' in app.jinja_env.filters.keys() <del> assert app.jinja_env.filters['my_reverse'] == my_reverse <del> assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' <del> <del> def test_template_filter_with_name(self): <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_filter('strrev') <del> def my_reverse(s): <del> return s[::-1] <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> assert 'strrev' in app.jinja_env.filters.keys() <del> assert app.jinja_env.filters['strrev'] == my_reverse <del> assert app.jinja_env.filters['strrev']('abcd') == 'dcba' <del> <del> def test_add_template_filter_with_name(self): <del> bp = flask.Blueprint('bp', __name__) <del> def my_reverse(s): <del> return s[::-1] <del> bp.add_app_template_filter(my_reverse, 'strrev') <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> assert 'strrev' in app.jinja_env.filters.keys() <del> assert app.jinja_env.filters['strrev'] == my_reverse <del> assert app.jinja_env.filters['strrev']('abcd') == 'dcba' <del> <del> def test_template_filter_with_template(self): <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_filter() <del> def super_reverse(s): <del> return s[::-1] <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_filter.html', value='abcd') <del> rv = app.test_client().get('/') <del> assert rv.data == b'dcba' <del> <del> def test_template_filter_after_route_with_template(self): <del> app = flask.Flask(__name__) <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_filter.html', value='abcd') <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_filter() <del> def super_reverse(s): <del> return s[::-1] <del> app.register_blueprint(bp, url_prefix='/py') <del> rv = app.test_client().get('/') <del> assert rv.data == b'dcba' <del> <del> def test_add_template_filter_with_template(self): <del> bp = flask.Blueprint('bp', __name__) <del> def super_reverse(s): <del> return s[::-1] <del> bp.add_app_template_filter(super_reverse) <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_filter.html', value='abcd') <del> rv = app.test_client().get('/') <del> assert rv.data == b'dcba' <del> <del> def test_template_filter_with_name_and_template(self): <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_filter('super_reverse') <del> def my_reverse(s): <del> return s[::-1] <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_filter.html', value='abcd') <del> rv = app.test_client().get('/') <del> assert rv.data == b'dcba' <del> <del> def test_add_template_filter_with_name_and_template(self): <del> bp = flask.Blueprint('bp', __name__) <del> def my_reverse(s): <del> return s[::-1] <del> bp.add_app_template_filter(my_reverse, 'super_reverse') <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_filter.html', value='abcd') <del> rv = app.test_client().get('/') <del> assert rv.data == b'dcba' <del> <del> def test_template_test(self): <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_test() <del> def is_boolean(value): <del> return isinstance(value, bool) <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> assert 'is_boolean' in app.jinja_env.tests.keys() <del> assert app.jinja_env.tests['is_boolean'] == is_boolean <del> assert app.jinja_env.tests['is_boolean'](False) <del> <del> def test_add_template_test(self): <del> bp = flask.Blueprint('bp', __name__) <del> def is_boolean(value): <del> return isinstance(value, bool) <del> bp.add_app_template_test(is_boolean) <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> assert 'is_boolean' in app.jinja_env.tests.keys() <del> assert app.jinja_env.tests['is_boolean'] == is_boolean <del> assert app.jinja_env.tests['is_boolean'](False) <del> <del> def test_template_test_with_name(self): <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_test('boolean') <del> def is_boolean(value): <del> return isinstance(value, bool) <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> assert 'boolean' in app.jinja_env.tests.keys() <del> assert app.jinja_env.tests['boolean'] == is_boolean <del> assert app.jinja_env.tests['boolean'](False) <del> <del> def test_add_template_test_with_name(self): <del> bp = flask.Blueprint('bp', __name__) <del> def is_boolean(value): <del> return isinstance(value, bool) <del> bp.add_app_template_test(is_boolean, 'boolean') <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> assert 'boolean' in app.jinja_env.tests.keys() <del> assert app.jinja_env.tests['boolean'] == is_boolean <del> assert app.jinja_env.tests['boolean'](False) <del> <del> def test_template_test_with_template(self): <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_test() <del> def boolean(value): <del> return isinstance(value, bool) <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_test.html', value=False) <del> rv = app.test_client().get('/') <del> assert b'Success!' in rv.data <del> <del> def test_template_test_after_route_with_template(self): <del> app = flask.Flask(__name__) <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_test.html', value=False) <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_test() <del> def boolean(value): <del> return isinstance(value, bool) <del> app.register_blueprint(bp, url_prefix='/py') <del> rv = app.test_client().get('/') <del> assert b'Success!' in rv.data <del> <del> def test_add_template_test_with_template(self): <del> bp = flask.Blueprint('bp', __name__) <del> def boolean(value): <del> return isinstance(value, bool) <del> bp.add_app_template_test(boolean) <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_test.html', value=False) <del> rv = app.test_client().get('/') <del> assert b'Success!' in rv.data <del> <del> def test_template_test_with_name_and_template(self): <del> bp = flask.Blueprint('bp', __name__) <del> @bp.app_template_test('boolean') <del> def is_boolean(value): <del> return isinstance(value, bool) <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_test.html', value=False) <del> rv = app.test_client().get('/') <del> assert b'Success!' in rv.data <del> <del> def test_add_template_test_with_name_and_template(self): <del> bp = flask.Blueprint('bp', __name__) <del> def is_boolean(value): <del> return isinstance(value, bool) <del> bp.add_app_template_test(is_boolean, 'boolean') <del> app = flask.Flask(__name__) <del> app.register_blueprint(bp, url_prefix='/py') <del> @app.route('/') <del> def index(): <del> return flask.render_template('template_test.html', value=False) <del> rv = app.test_client().get('/') <del> assert b'Success!' in rv.data <del> <del>def suite(): <del> suite = unittest.TestSuite() <del> suite.addTest(unittest.makeSuite(TestBlueprint)) <del> return suite <add> ) <add> <add> pytest.raises( <add> AssertionError, <add> bp.route('/bar/123', endpoint='bar.123'), <add> lambda: None <add> ) <add> <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> <add> c = app.test_client() <add> assert c.get('/py/foo').data == b'bp.foo' <add> # The rule's didn't actually made it through <add> rv = c.get('/py/bar') <add> assert rv.status_code == 404 <add> rv = c.get('/py/bar/123') <add> assert rv.status_code == 404 <add> <add>def test_template_filter(): <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_filter() <add> def my_reverse(s): <add> return s[::-1] <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> assert 'my_reverse' in app.jinja_env.filters.keys() <add> assert app.jinja_env.filters['my_reverse'] == my_reverse <add> assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' <add> <add>def test_add_template_filter(): <add> bp = flask.Blueprint('bp', __name__) <add> def my_reverse(s): <add> return s[::-1] <add> bp.add_app_template_filter(my_reverse) <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> assert 'my_reverse' in app.jinja_env.filters.keys() <add> assert app.jinja_env.filters['my_reverse'] == my_reverse <add> assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' <add> <add>def test_template_filter_with_name(): <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_filter('strrev') <add> def my_reverse(s): <add> return s[::-1] <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> assert 'strrev' in app.jinja_env.filters.keys() <add> assert app.jinja_env.filters['strrev'] == my_reverse <add> assert app.jinja_env.filters['strrev']('abcd') == 'dcba' <add> <add>def test_add_template_filter_with_name(): <add> bp = flask.Blueprint('bp', __name__) <add> def my_reverse(s): <add> return s[::-1] <add> bp.add_app_template_filter(my_reverse, 'strrev') <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> assert 'strrev' in app.jinja_env.filters.keys() <add> assert app.jinja_env.filters['strrev'] == my_reverse <add> assert app.jinja_env.filters['strrev']('abcd') == 'dcba' <add> <add>def test_template_filter_with_template(): <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_filter() <add> def super_reverse(s): <add> return s[::-1] <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_filter.html', value='abcd') <add> rv = app.test_client().get('/') <add> assert rv.data == b'dcba' <add> <add>def test_template_filter_after_route_with_template(): <add> app = flask.Flask(__name__) <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_filter.html', value='abcd') <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_filter() <add> def super_reverse(s): <add> return s[::-1] <add> app.register_blueprint(bp, url_prefix='/py') <add> rv = app.test_client().get('/') <add> assert rv.data == b'dcba' <add> <add>def test_add_template_filter_with_template(): <add> bp = flask.Blueprint('bp', __name__) <add> def super_reverse(s): <add> return s[::-1] <add> bp.add_app_template_filter(super_reverse) <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_filter.html', value='abcd') <add> rv = app.test_client().get('/') <add> assert rv.data == b'dcba' <add> <add>def test_template_filter_with_name_and_template(): <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_filter('super_reverse') <add> def my_reverse(s): <add> return s[::-1] <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_filter.html', value='abcd') <add> rv = app.test_client().get('/') <add> assert rv.data == b'dcba' <add> <add>def test_add_template_filter_with_name_and_template(): <add> bp = flask.Blueprint('bp', __name__) <add> def my_reverse(s): <add> return s[::-1] <add> bp.add_app_template_filter(my_reverse, 'super_reverse') <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_filter.html', value='abcd') <add> rv = app.test_client().get('/') <add> assert rv.data == b'dcba' <add> <add>def test_template_test(): <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_test() <add> def is_boolean(value): <add> return isinstance(value, bool) <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> assert 'is_boolean' in app.jinja_env.tests.keys() <add> assert app.jinja_env.tests['is_boolean'] == is_boolean <add> assert app.jinja_env.tests['is_boolean'](False) <add> <add>def test_add_template_test(): <add> bp = flask.Blueprint('bp', __name__) <add> def is_boolean(value): <add> return isinstance(value, bool) <add> bp.add_app_template_test(is_boolean) <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> assert 'is_boolean' in app.jinja_env.tests.keys() <add> assert app.jinja_env.tests['is_boolean'] == is_boolean <add> assert app.jinja_env.tests['is_boolean'](False) <add> <add>def test_template_test_with_name(): <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_test('boolean') <add> def is_boolean(value): <add> return isinstance(value, bool) <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> assert 'boolean' in app.jinja_env.tests.keys() <add> assert app.jinja_env.tests['boolean'] == is_boolean <add> assert app.jinja_env.tests['boolean'](False) <add> <add>def test_add_template_test_with_name(): <add> bp = flask.Blueprint('bp', __name__) <add> def is_boolean(value): <add> return isinstance(value, bool) <add> bp.add_app_template_test(is_boolean, 'boolean') <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> assert 'boolean' in app.jinja_env.tests.keys() <add> assert app.jinja_env.tests['boolean'] == is_boolean <add> assert app.jinja_env.tests['boolean'](False) <add> <add>def test_template_test_with_template(): <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_test() <add> def boolean(value): <add> return isinstance(value, bool) <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_test.html', value=False) <add> rv = app.test_client().get('/') <add> assert b'Success!' in rv.data <add> <add>def test_template_test_after_route_with_template(): <add> app = flask.Flask(__name__) <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_test.html', value=False) <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_test() <add> def boolean(value): <add> return isinstance(value, bool) <add> app.register_blueprint(bp, url_prefix='/py') <add> rv = app.test_client().get('/') <add> assert b'Success!' in rv.data <add> <add>def test_add_template_test_with_template(): <add> bp = flask.Blueprint('bp', __name__) <add> def boolean(value): <add> return isinstance(value, bool) <add> bp.add_app_template_test(boolean) <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_test.html', value=False) <add> rv = app.test_client().get('/') <add> assert b'Success!' in rv.data <add> <add>def test_template_test_with_name_and_template(): <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_test('boolean') <add> def is_boolean(value): <add> return isinstance(value, bool) <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_test.html', value=False) <add> rv = app.test_client().get('/') <add> assert b'Success!' in rv.data <add> <add>def test_add_template_test_with_name_and_template(): <add> bp = flask.Blueprint('bp', __name__) <add> def is_boolean(value): <add> return isinstance(value, bool) <add> bp.add_app_template_test(is_boolean, 'boolean') <add> app = flask.Flask(__name__) <add> app.register_blueprint(bp, url_prefix='/py') <add> @app.route('/') <add> def index(): <add> return flask.render_template('template_test.html', value=False) <add> rv = app.test_client().get('/') <add> assert b'Success!' in rv.data <ide><path>tests/test_config.py <ide> SECRET_KEY = 'devkey' <ide> <ide> <del>class TestConfig(TestFlask): <add>class TestConfig(object): <ide> <ide> def common_object_test(self, app): <ide> assert app.secret_key == 'devkey' <ide> def test_get_namespace(self): <ide> assert 'bar stuff 2' == bar_options['STUFF_2'] <ide> <ide> <del>class TestInstance(TestFlask): <add>class TestInstance(object): <ide> def test_explicit_instance_paths(self, apps_tmpdir): <ide> with pytest.raises(ValueError) as excinfo: <ide> flask.Flask(__name__, instance_path='instance') <ide><path>tests/test_deprecations.py <ide> tests.deprecations <ide> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <ide> <del> Tests deprecation support. <add> Tests deprecation support. Not used currently. <ide> <ide> :copyright: (c) 2014 by Armin Ronacher. <ide> :license: BSD, see LICENSE for more details. <ide> import flask <ide> import unittest <ide> from tests import TestFlask, catch_warnings <del> <del> <del>class TestDeprecations(TestFlask): <del> """not used currently""" <del> <del> <del>def suite(): <del> suite = unittest.TestSuite() <del> suite.addTest(unittest.makeSuite(TestDeprecations)) <del> return suite <ide><path>tests/test_examples.py <del># -*- coding: utf-8 -*- <del>""" <del> tests.examples <del> ~~~~~~~~~~~~~~~~~~~~~~~~ <del> <del> Tests the examples. <del> <del> :copyright: (c) 2014 by Armin Ronacher. <del> :license: BSD, see LICENSE for more details. <del>""" <del>import os <del>import unittest <del>from tests import add_to_path <del> <del> <del>def setup_path(): <del> example_path = os.path.join(os.path.dirname(__file__), <del> os.pardir, os.pardir, 'examples') <del> add_to_path(os.path.join(example_path, 'flaskr')) <del> add_to_path(os.path.join(example_path, 'minitwit')) <del> <del> <del>def suite(): <del> setup_path() <del> suite = unittest.TestSuite() <del> try: <del> from minitwit_tests import TestMiniTwit <del> except ImportError: <del> pass <del> else: <del> suite.addTest(unittest.makeSuite(TestMiniTwit)) <del> try: <del> from flaskr_tests import TestFlaskr <del> except ImportError: <del> pass <del> else: <del> suite.addTest(unittest.makeSuite(TestFlaskr)) <del> return suite <ide><path>tests/test_helpers.py <ide> def has_encoding(name): <ide> return False <ide> <ide> <del>class TestJSON(TestFlask): <add>class TestJSON(object): <ide> <ide> def test_json_bad_requests(self): <ide> app = flask.Flask(__name__) <ide> def index(): <ide> except AssertionError: <ide> assert lines == sorted_by_str <ide> <del>class TestSendfile(TestFlask): <add>class TestSendfile(object): <ide> <ide> def test_send_file_regular(self): <ide> app = flask.Flask(__name__) <ide> def test_send_from_directory(self): <ide> rv.close() <ide> <ide> <del>class TestLogging(TestFlask): <add>class TestLogging(object): <ide> <ide> def test_logger_cache(self): <ide> app = flask.Flask(__name__) <ide> def post(self): <ide> assert flask.url_for('myview', _method='POST') == '/myview/create' <ide> <ide> <del>class TestNoImports(TestFlask): <add>class TestNoImports(object): <ide> """Test Flasks are created without import. <ide> <ide> Avoiding ``__import__`` helps create Flask instances where there are errors <ide> def test_name_with_import_error(self): <ide> assert False, 'Flask(import_name) is importing import_name.' <ide> <ide> <del>class TestStreaming(TestFlask): <add>class TestStreaming(object): <ide> <ide> def test_streaming_with_context(self): <ide> app = flask.Flask(__name__) <ide> def generate(): <ide> rv = c.get('/?name=World') <ide> assert rv.data == b'Hello World!' <ide> assert called == [42] <del> <del> <del>def suite(): <del> suite = unittest.TestSuite() <del> if flask.json_available: <del> suite.addTest(unittest.makeSuite(TestJSON)) <del> suite.addTest(unittest.makeSuite(TestSendfile)) <del> suite.addTest(unittest.makeSuite(TestLogging)) <del> suite.addTest(unittest.makeSuite(TestNoImports)) <del> suite.addTest(unittest.makeSuite(TestStreaming)) <del> return suite <ide><path>tests/test_regression.py <ide> def __exit__(self, exc_type, exc_value, tb): <ide> <ide> @pytest.mark.skipif(os.environ.get('RUN_FLASK_MEMORY_TESTS') != '1', <ide> reason='Turned off due to envvar.') <del>class TestMemory(TestFlask): <add>class TestMemory(object): <ide> <ide> def assert_no_leak(self): <ide> return _NoLeakAsserter(self) <ide> def test_safe_join_toplevel_pardir(self): <ide> safe_join('/foo', '..') <ide> <ide> <del>class TestException(TestFlask): <add>class TestException(object): <ide> <ide> def test_aborting(self): <ide> class Foo(Exception): <ide><path>tests/test_reqctx.py <ide> from tests import TestFlask <ide> <ide> <del>class TestRequestContext(TestFlask): <add>def test_teardown_on_pop(): <add> buffer = [] <add> app = flask.Flask(__name__) <add> @app.teardown_request <add> def end_of_request(exception): <add> buffer.append(exception) <add> <add> ctx = app.test_request_context() <add> ctx.push() <add> assert buffer == [] <add> ctx.pop() <add> assert buffer == [None] <add> <add>def test_teardown_with_previous_exception(): <add> buffer = [] <add> app = flask.Flask(__name__) <add> @app.teardown_request <add> def end_of_request(exception): <add> buffer.append(exception) <add> <add> try: <add> raise Exception('dummy') <add> except Exception: <add> pass <add> <add> with app.test_request_context(): <add> assert buffer == [] <add> assert buffer == [None] <ide> <del> def test_teardown_on_pop(self): <del> buffer = [] <del> app = flask.Flask(__name__) <del> @app.teardown_request <del> def end_of_request(exception): <del> buffer.append(exception) <add>def test_proper_test_request_context(): <add> app = flask.Flask(__name__) <add> app.config.update( <add> SERVER_NAME='localhost.localdomain:5000' <add> ) <ide> <del> ctx = app.test_request_context() <del> ctx.push() <del> assert buffer == [] <del> ctx.pop() <del> assert buffer == [None] <del> <del> def test_teardown_with_previous_exception(self): <del> buffer = [] <del> app = flask.Flask(__name__) <del> @app.teardown_request <del> def end_of_request(exception): <del> buffer.append(exception) <del> <del> try: <del> raise Exception('dummy') <del> except Exception: <del> pass <add> @app.route('/') <add> def index(): <add> return None <ide> <del> with app.test_request_context(): <del> assert buffer == [] <del> assert buffer == [None] <add> @app.route('/', subdomain='foo') <add> def sub(): <add> return None <ide> <del> def test_proper_test_request_context(self): <del> app = flask.Flask(__name__) <del> app.config.update( <del> SERVER_NAME='localhost.localdomain:5000' <del> ) <add> with app.test_request_context('/'): <add> assert flask.url_for('index', _external=True) == \ <add> 'http://localhost.localdomain:5000/' <ide> <del> @app.route('/') <del> def index(): <del> return None <del> <del> @app.route('/', subdomain='foo') <del> def sub(): <del> return None <del> <del> with app.test_request_context('/'): <del> assert flask.url_for('index', _external=True) == \ <del> 'http://localhost.localdomain:5000/' <del> <del> with app.test_request_context('/'): <del> assert flask.url_for('sub', _external=True) == \ <del> 'http://foo.localhost.localdomain:5000/' <del> <del> try: <del> with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): <del> pass <del> except ValueError as e: <del> assert str(e) == ( <del> "the server name provided " <del> "('localhost.localdomain:5000') does not match the " <del> "server name from the WSGI environment ('localhost')" <del> ) <del> <del> app.config.update(SERVER_NAME='localhost') <del> with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}): <del> pass <add> with app.test_request_context('/'): <add> assert flask.url_for('sub', _external=True) == \ <add> 'http://foo.localhost.localdomain:5000/' <ide> <del> app.config.update(SERVER_NAME='localhost:80') <del> with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): <add> try: <add> with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}): <ide> pass <add> except ValueError as e: <add> assert str(e) == ( <add> "the server name provided " <add> "('localhost.localdomain:5000') does not match the " <add> "server name from the WSGI environment ('localhost')" <add> ) <ide> <del> def test_context_binding(self): <del> app = flask.Flask(__name__) <del> @app.route('/') <del> def index(): <del> return 'Hello %s!' % flask.request.args['name'] <del> @app.route('/meh') <del> def meh(): <del> return flask.request.url <del> <del> with app.test_request_context('/?name=World'): <del> assert index() == 'Hello World!' <del> with app.test_request_context('/meh'): <del> assert meh() == 'http://localhost/meh' <del> assert flask._request_ctx_stack.top is None <del> <del> def test_context_test(self): <del> app = flask.Flask(__name__) <del> assert not flask.request <del> assert not flask.has_request_context() <del> ctx = app.test_request_context() <del> ctx.push() <del> try: <del> assert flask.request <del> assert flask.has_request_context() <del> finally: <del> ctx.pop() <del> <del> def test_manual_context_binding(self): <del> app = flask.Flask(__name__) <del> @app.route('/') <del> def index(): <del> return 'Hello %s!' % flask.request.args['name'] <del> <del> ctx = app.test_request_context('/?name=World') <del> ctx.push() <add> app.config.update(SERVER_NAME='localhost') <add> with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}): <add> pass <add> <add> app.config.update(SERVER_NAME='localhost:80') <add> with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}): <add> pass <add> <add>def test_context_binding(): <add> app = flask.Flask(__name__) <add> @app.route('/') <add> def index(): <add> return 'Hello %s!' % flask.request.args['name'] <add> @app.route('/meh') <add> def meh(): <add> return flask.request.url <add> <add> with app.test_request_context('/?name=World'): <ide> assert index() == 'Hello World!' <add> with app.test_request_context('/meh'): <add> assert meh() == 'http://localhost/meh' <add> assert flask._request_ctx_stack.top is None <add> <add>def test_context_test(): <add> app = flask.Flask(__name__) <add> assert not flask.request <add> assert not flask.has_request_context() <add> ctx = app.test_request_context() <add> ctx.push() <add> try: <add> assert flask.request <add> assert flask.has_request_context() <add> finally: <ide> ctx.pop() <del> try: <del> index() <del> except RuntimeError: <del> pass <del> else: <del> assert 0, 'expected runtime error' <del> <del> def test_greenlet_context_copying(self): <del> app = flask.Flask(__name__) <del> greenlets = [] <del> <del> @app.route('/') <del> def index(): <del> reqctx = flask._request_ctx_stack.top.copy() <del> def g(): <del> assert not flask.request <del> assert not flask.current_app <del> with reqctx: <del> assert flask.request <del> assert flask.current_app == app <del> assert flask.request.path == '/' <del> assert flask.request.args['foo'] == 'bar' <del> assert not flask.request <del> return 42 <del> greenlets.append(greenlet(g)) <del> return 'Hello World!' <del> <del> rv = app.test_client().get('/?foo=bar') <del> assert rv.data == b'Hello World!' <del> <del> result = greenlets[0].run() <del> assert result == 42 <del> <del> def test_greenlet_context_copying_api(self): <del> app = flask.Flask(__name__) <del> greenlets = [] <del> <del> @app.route('/') <del> def index(): <del> reqctx = flask._request_ctx_stack.top.copy() <del> @flask.copy_current_request_context <del> def g(): <add> <add>def test_manual_context_binding(): <add> app = flask.Flask(__name__) <add> @app.route('/') <add> def index(): <add> return 'Hello %s!' % flask.request.args['name'] <add> <add> ctx = app.test_request_context('/?name=World') <add> ctx.push() <add> assert index() == 'Hello World!' <add> ctx.pop() <add> try: <add> index() <add> except RuntimeError: <add> pass <add> else: <add> assert 0, 'expected runtime error' <add> <add>@pytest.mark.skipif(greenlet is None, reason='greenlet not installed') <add>def test_greenlet_context_copying(): <add> app = flask.Flask(__name__) <add> greenlets = [] <add> <add> @app.route('/') <add> def index(): <add> reqctx = flask._request_ctx_stack.top.copy() <add> def g(): <add> assert not flask.request <add> assert not flask.current_app <add> with reqctx: <ide> assert flask.request <ide> assert flask.current_app == app <ide> assert flask.request.path == '/' <ide> assert flask.request.args['foo'] == 'bar' <del> return 42 <del> greenlets.append(greenlet(g)) <del> return 'Hello World!' <del> <del> rv = app.test_client().get('/?foo=bar') <del> assert rv.data == b'Hello World!' <del> <del> result = greenlets[0].run() <del> assert result == 42 <del> <del> # Disable test if we don't have greenlets available <del> if greenlet is None: <del> test_greenlet_context_copying = None <del> test_greenlet_context_copying_api = None <del> <del> <del>def suite(): <del> suite = unittest.TestSuite() <del> suite.addTest(unittest.makeSuite(TestRequestContext)) <del> return suite <add> assert not flask.request <add> return 42 <add> greenlets.append(greenlet(g)) <add> return 'Hello World!' <add> <add> rv = app.test_client().get('/?foo=bar') <add> assert rv.data == b'Hello World!' <add> <add> result = greenlets[0].run() <add> assert result == 42 <add> <add>@pytest.mark.skipif(greenlet is None, reason='greenlet not installed') <add>def test_greenlet_context_copying_api(): <add> app = flask.Flask(__name__) <add> greenlets = [] <add> <add> @app.route('/') <add> def index(): <add> reqctx = flask._request_ctx_stack.top.copy() <add> @flask.copy_current_request_context <add> def g(): <add> assert flask.request <add> assert flask.current_app == app <add> assert flask.request.path == '/' <add> assert flask.request.args['foo'] == 'bar' <add> return 42 <add> greenlets.append(greenlet(g)) <add> return 'Hello World!' <add> <add> rv = app.test_client().get('/?foo=bar') <add> assert rv.data == b'Hello World!' <add> <add> result = greenlets[0].run() <add> assert result == 42 <ide><path>tests/test_signals.py <ide> reason='Signals require the blinker library.' <ide> ) <ide> <del>class TestSignals(TestFlask): <del> <del> def test_template_rendered(self): <del> app = flask.Flask(__name__) <del> <del> @app.route('/') <del> def index(): <del> return flask.render_template('simple_template.html', whiskey=42) <del> <del> recorded = [] <del> <del> def record(sender, template, context): <del> recorded.append((template, context)) <del> <del> flask.template_rendered.connect(record, app) <del> try: <del> app.test_client().get('/') <del> assert len(recorded) == 1 <del> template, context = recorded[0] <del> assert template.name == 'simple_template.html' <del> assert context['whiskey'] == 42 <del> finally: <del> flask.template_rendered.disconnect(record, app) <del> <del> def test_request_signals(self): <del> app = flask.Flask(__name__) <del> calls = [] <del> <del> def before_request_signal(sender): <del> calls.append('before-signal') <del> <del> def after_request_signal(sender, response): <del> assert response.data == b'stuff' <del> calls.append('after-signal') <del> <del> @app.before_request <del> def before_request_handler(): <del> calls.append('before-handler') <del> <del> @app.after_request <del> def after_request_handler(response): <del> calls.append('after-handler') <del> response.data = 'stuff' <del> return response <del> <del> @app.route('/') <del> def index(): <del> calls.append('handler') <del> return 'ignored anyway' <del> <del> flask.request_started.connect(before_request_signal, app) <del> flask.request_finished.connect(after_request_signal, app) <del> <del> try: <del> rv = app.test_client().get('/') <del> assert rv.data == b'stuff' <del> <del> assert calls == ['before-signal', 'before-handler', 'handler', <del> 'after-handler', 'after-signal'] <del> finally: <del> flask.request_started.disconnect(before_request_signal, app) <del> flask.request_finished.disconnect(after_request_signal, app) <del> <del> def test_request_exception_signal(self): <del> app = flask.Flask(__name__) <del> recorded = [] <del> <del> @app.route('/') <del> def index(): <del> 1 // 0 <del> <del> def record(sender, exception): <del> recorded.append(exception) <del> <del> flask.got_request_exception.connect(record, app) <del> try: <del> assert app.test_client().get('/').status_code == 500 <add>def test_template_rendered(): <add> app = flask.Flask(__name__) <add> <add> @app.route('/') <add> def index(): <add> return flask.render_template('simple_template.html', whiskey=42) <add> <add> recorded = [] <add> <add> def record(sender, template, context): <add> recorded.append((template, context)) <add> <add> flask.template_rendered.connect(record, app) <add> try: <add> app.test_client().get('/') <add> assert len(recorded) == 1 <add> template, context = recorded[0] <add> assert template.name == 'simple_template.html' <add> assert context['whiskey'] == 42 <add> finally: <add> flask.template_rendered.disconnect(record, app) <add> <add>def test_request_signals(): <add> app = flask.Flask(__name__) <add> calls = [] <add> <add> def before_request_signal(sender): <add> calls.append('before-signal') <add> <add> def after_request_signal(sender, response): <add> assert response.data == b'stuff' <add> calls.append('after-signal') <add> <add> @app.before_request <add> def before_request_handler(): <add> calls.append('before-handler') <add> <add> @app.after_request <add> def after_request_handler(response): <add> calls.append('after-handler') <add> response.data = 'stuff' <add> return response <add> <add> @app.route('/') <add> def index(): <add> calls.append('handler') <add> return 'ignored anyway' <add> <add> flask.request_started.connect(before_request_signal, app) <add> flask.request_finished.connect(after_request_signal, app) <add> <add> try: <add> rv = app.test_client().get('/') <add> assert rv.data == b'stuff' <add> <add> assert calls == ['before-signal', 'before-handler', 'handler', <add> 'after-handler', 'after-signal'] <add> finally: <add> flask.request_started.disconnect(before_request_signal, app) <add> flask.request_finished.disconnect(after_request_signal, app) <add> <add>def test_request_exception_signal(): <add> app = flask.Flask(__name__) <add> recorded = [] <add> <add> @app.route('/') <add> def index(): <add> 1 // 0 <add> <add> def record(sender, exception): <add> recorded.append(exception) <add> <add> flask.got_request_exception.connect(record, app) <add> try: <add> assert app.test_client().get('/').status_code == 500 <add> assert len(recorded) == 1 <add> assert isinstance(recorded[0], ZeroDivisionError) <add> finally: <add> flask.got_request_exception.disconnect(record, app) <add> <add>def test_appcontext_signals(): <add> app = flask.Flask(__name__) <add> recorded = [] <add> <add> def record_push(sender, **kwargs): <add> recorded.append('push') <add> <add> def record_pop(sender, **kwargs): <add> recorded.append('pop') <add> <add> @app.route('/') <add> def index(): <add> return 'Hello' <add> <add> flask.appcontext_pushed.connect(record_push, app) <add> flask.appcontext_popped.connect(record_pop, app) <add> try: <add> with app.test_client() as c: <add> rv = c.get('/') <add> assert rv.data == b'Hello' <add> assert recorded == ['push'] <add> assert recorded == ['push', 'pop'] <add> finally: <add> flask.appcontext_pushed.disconnect(record_push, app) <add> flask.appcontext_popped.disconnect(record_pop, app) <add> <add>def test_flash_signal(): <add> app = flask.Flask(__name__) <add> app.config['SECRET_KEY'] = 'secret' <add> <add> @app.route('/') <add> def index(): <add> flask.flash('This is a flash message', category='notice') <add> return flask.redirect('/other') <add> <add> recorded = [] <add> <add> def record(sender, message, category): <add> recorded.append((message, category)) <add> <add> flask.message_flashed.connect(record, app) <add> try: <add> client = app.test_client() <add> with client.session_transaction(): <add> client.get('/') <ide> assert len(recorded) == 1 <del> assert isinstance(recorded[0], ZeroDivisionError) <del> finally: <del> flask.got_request_exception.disconnect(record, app) <del> <del> def test_appcontext_signals(self): <del> app = flask.Flask(__name__) <del> recorded = [] <del> <del> def record_push(sender, **kwargs): <del> recorded.append('push') <del> <del> def record_pop(sender, **kwargs): <del> recorded.append('pop') <del> <del> @app.route('/') <del> def index(): <del> return 'Hello' <del> <del> flask.appcontext_pushed.connect(record_push, app) <del> flask.appcontext_popped.connect(record_pop, app) <del> try: <del> with app.test_client() as c: <del> rv = c.get('/') <del> assert rv.data == b'Hello' <del> assert recorded == ['push'] <del> assert recorded == ['push', 'pop'] <del> finally: <del> flask.appcontext_pushed.disconnect(record_push, app) <del> flask.appcontext_popped.disconnect(record_pop, app) <del> <del> def test_flash_signal(self): <del> app = flask.Flask(__name__) <del> app.config['SECRET_KEY'] = 'secret' <del> <del> @app.route('/') <del> def index(): <del> flask.flash('This is a flash message', category='notice') <del> return flask.redirect('/other') <del> <del> recorded = [] <del> <del> def record(sender, message, category): <del> recorded.append((message, category)) <del> <del> flask.message_flashed.connect(record, app) <del> try: <del> client = app.test_client() <del> with client.session_transaction(): <del> client.get('/') <del> assert len(recorded) == 1 <del> message, category = recorded[0] <del> assert message == 'This is a flash message' <del> assert category == 'notice' <del> finally: <del> flask.message_flashed.disconnect(record, app) <add> message, category = recorded[0] <add> assert message == 'This is a flash message' <add> assert category == 'notice' <add> finally: <add> flask.message_flashed.disconnect(record, app) <ide><path>tests/test_testing.py <ide> from flask._compat import text_type <ide> <ide> <del>class TestTestTools(TestFlask): <add>class TestTestTools(object): <ide> <ide> def test_environ_defaults_from_config(self): <ide> app = flask.Flask(__name__) <ide> def action(): <ide> assert 'vodka' in flask.request.args <ide> <ide> <del>class TestSubdomain(TestFlask): <add>class TestSubdomain(object): <ide> <ide> @pytest.fixture <ide> def app(self, request):
10
Text
Text
fix incorrect example
13a3c993ab20e7af510d615a5eafaa87667b8efb
<ide><path>docs/api-guide/generic-views.md <ide> May be overridden to provide dynamic behavior such as returning a queryset that <ide> For example: <ide> <ide> def get_queryset(self): <del> return self.user.accounts.all() <add> user = self.request.user <add> return user.accounts.all() <ide> <ide> #### `get_object(self)` <ide>
1
Go
Go
fix typos in pkg
7a7a8a33a4a79e7ea1e67f8a77b4060f95e936ea
<ide><path>pkg/system/path.go <ide> func DefaultPathEnv(os string) string { <ide> // This is used, for example, when validating a user provided path in docker cp. <ide> // If a drive letter is supplied, it must be the system drive. The drive letter <ide> // is always removed. Also, it translates it to OS semantics (IOW / to \). We <del>// need the path in this syntax so that it can ultimately be contatenated with <add>// need the path in this syntax so that it can ultimately be concatenated with <ide> // a Windows long-path which doesn't support drive-letters. Examples: <ide> // C: --> Fail <ide> // C:\ --> \ <ide><path>pkg/tailfile/tailfile.go <ide> var eol = []byte("\n") <ide> // ErrNonPositiveLinesNumber is an error returned if the lines number was negative. <ide> var ErrNonPositiveLinesNumber = errors.New("The number of lines to extract from the file must be positive") <ide> <del>//TailFile returns last n lines of reader f (could be a fil). <add>//TailFile returns last n lines of reader f (could be a nil). <ide> func TailFile(f io.ReadSeeker, n int) ([][]byte, error) { <ide> if n <= 0 { <ide> return nil, ErrNonPositiveLinesNumber
2
Ruby
Ruby
use dedicated version class
cfdd23b3efcfc994908dfb6792c8d062a19f12f1
<ide><path>Library/Homebrew/bottle_version.rb <add>class BottleVersion < Version <add> def self._parse spec <add> spec = Pathname.new(spec) unless spec.is_a? Pathname <add> stem = spec.stem <add> <add> super <add> end <add>end <ide><path>Library/Homebrew/bottles.rb <ide> require 'tab' <ide> require 'macos' <ide> require 'extend/ARGV' <add>require 'bottle_version' <ide> <ide> # TODO: use options={} for some arguments. <ide> <ide> def bottle_tag <ide> end <ide> <ide> def bottle_filename_formula_name filename <del> version = Version.parse(filename).to_s <ide> path = Pathname.new filename <add> version = BottleVersion.parse(path).to_s <ide> basename = path.basename.to_s <ide> basename.rpartition("-#{version}").first <ide> end <ide><path>Library/Homebrew/test/test_bottle_versions.rb <add>require 'testing_env' <add>require 'bottle_version' <add> <add>class BottleVersionParsingTests < Test::Unit::TestCase <add> def assert_version_detected expected, path <add> assert_equal expected, BottleVersion.parse(path).to_s <add> end <add>end
3
Javascript
Javascript
write test to demonstrate injection grammar bug
fdd60afecbcc16dd21a1d308568630b488404c30
<ide><path>spec/tree-sitter-language-mode-spec.js <ide> describe('TreeSitterLanguageMode', () => { <ide> ]); <ide> }); <ide> <add> it('correctly closes the scopes of nodes that contain injected grammars', async () => { <add> await atom.packages.activatePackage('language-javascript'); <add> editor.setGrammar(atom.grammars.grammarForScopeName('source.js')); <add> editor.setText('/**\n*/\n{\n}'); <add> <add> expectTokensToEqual(editor, [ <add> [{ text: '/**', scopes: ['source js', 'comment block'] }], <add> [{ text: '*/', scopes: ['source js', 'comment block'] }], <add> [ <add> { <add> text: '{', <add> scopes: [ <add> 'source js', <add> 'punctuation definition function body begin bracket curly' <add> ] <add> } <add> ], <add> [ <add> { <add> text: '}', <add> scopes: [ <add> 'source js', <add> 'punctuation definition function body end bracket curly' <add> ] <add> } <add> ] <add> ]); <add> }); <add> <ide> describe('when the buffer changes during a parse', () => { <ide> it('immediately parses again when the current parse completes', async () => { <ide> const grammar = new TreeSitterGrammar(atom.grammars, jsGrammarPath, { <ide> function expectTokensToEqual(editor, expectedTokenLines) { <ide> } <ide> <ide> for (let row = startRow; row <= lastRow; row++) { <add> console.log('Row', row); <ide> const tokenLine = tokenLines[row]; <ide> const expectedTokenLine = expectedTokenLines[row]; <ide>
1
Ruby
Ruby
drop one more string allocation
87d0bde03f89d70f9f80d37de696e2577870170c
<ide><path>actionview/lib/action_view/log_subscriber.rb <ide> def logger <ide> <ide> EMPTY = '' <ide> def from_rails_root(string) <del> string.sub(rails_root, EMPTY).sub(VIEWS_PATTERN, EMPTY) <add> string = string.sub(rails_root, EMPTY) <add> string.sub!(VIEWS_PATTERN, EMPTY) <add> string <ide> end <ide> <ide> def rails_root
1
Python
Python
fix flake8 error
a96ebd74b1c27f4fa63f7bae5f9157f1140f9570
<ide><path>rest_framework/authentication.py <ide> from rest_framework.authtoken.models import Token <ide> from rest_framework.compat import get_user_model <ide> <add> <ide> def get_authorization_header(request): <ide> """ <ide> Return request's 'Authorization:' header, as a bytestring.
1
Text
Text
update status of python 3 support
7bee77f7e23e55bf1a07ed478e55e4300c2d69cc
<ide><path>BUILDING.md <ide> Consult previous versions of this document for older versions of Node.js: <ide> <ide> ### Note about Python 2 and Python 3 <ide> <del>The Node.js project uses Python as part of its build process and has <del>historically only been Python 2 compatible. <del> <del>Python 2 will reach its _end-of-life_ at the end of 2019 at which point the <del>interpreter will cease receiving updates. See https://python3statement.org/ <del>for more information. <del> <del>The Node.js project is in the process of transitioning its Python code to <del>Python 3 compatibility. Installing both versions of Python while building <del>and testing Node.js allows developers and end users to test, benchmark, <del>and debug Node.js running on both versions to ensure a smooth and complete <del>transition before the year-end deadline. <add>The Node.js project supports both Python 3 and Python 2 for building. <add>If both are installed Python 3 will be used. If only Python 2 is available <add>it will be used instead. When possible we recommend that you build and <add>test with Python 3. <ide> <ide> ### Unix and macOS <ide> <ide> transition before the year-end deadline. <ide> * GNU Make 3.81 or newer <ide> * Python (see note above) <ide> * Python 2.7 <del> * Python 3.5, 3.6, 3.7, and 3.8 are experimental. <add> * Python 3.5, 3.6, 3.7, and 3.8. <ide> <ide> Installation via Linux package manager can be achieved with: <ide> <ide> FreeBSD and OpenBSD users may also need to install `libexecinfo`. <ide> * Xcode Command Line Tools >= 10 for macOS <ide> * Python (see note above) <ide> * Python 2.7 <del> * Python 3.5, 3.6, 3.7, and 3.8 are experimental. <add> * Python 3.5, 3.6, 3.7, and 3.8. <ide> <ide> macOS users can install the `Xcode Command Line Tools` by running <ide> `xcode-select --install`. Alternatively, if you already have the full Xcode
1
PHP
PHP
fix redirect response docblock
06788ba388a91682dd98d01d30876fccd17ecda4
<ide><path>src/Illuminate/Http/RedirectResponse.php <ide> class RedirectResponse extends BaseRedirectResponse <ide> * <ide> * @param string|array $key <ide> * @param mixed $value <del> * @return \Illuminate\Http\RedirectResponse <add> * @return $this <ide> */ <ide> public function with($key, $value = null) <ide> { <ide> public function onlyInput() <ide> /** <ide> * Flash an array of input to the session. <ide> * <del> * @return \Illuminate\Http\RedirectResponse <add> * @return $this <ide> */ <ide> public function exceptInput() <ide> { <ide> public function setSession(SessionStore $session) <ide> * <ide> * @param string $method <ide> * @param array $parameters <del> * @return $this <add> * @return mixed <ide> * <ide> * @throws \BadMethodCallException <ide> */
1
Java
Java
fix failing test
9c438a8f7831d4841b82149f317804a262946f94
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java <ide> package org.springframework.web.reactive; <ide> <ide> import java.net.URI; <add>import java.time.Duration; <ide> import java.util.Collections; <ide> <ide> import org.junit.Before; <ide> public void webExceptionHandler() throws Exception { <ide> <ide> WebExceptionHandler exceptionHandler = new ServerError500ExceptionHandler(); <ide> WebHandler webHandler = new ExceptionHandlingWebHandler(this.dispatcherHandler, exceptionHandler); <del> Mono<Void> publisher = webHandler.handle(this.exchange); <del> <del> TestSubscriber.subscribe(publisher) <del> .assertErrorWith(ex -> assertEquals( <del> HttpStatus.INTERNAL_SERVER_ERROR, this.exchange.getResponse().getStatusCode())); <add> webHandler.handle(this.exchange).block(Duration.ofSeconds(5)); <ide> <add> assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, this.exchange.getResponse().getStatusCode()); <ide> } <ide> <ide>
1
Javascript
Javascript
add tests for variable scale.nice
f6108db93b46754dc82b8c005966adbf58b5feec
<ide><path>test/scale/linear-test.js <ide> suite.addBatch({ <ide> assert.deepEqual(x.domain(), [1, 1, 2, 3, 11]); <ide> var x = d3.scale.linear().domain([123.1, 1, 2, 3, -.9]).nice(); <ide> assert.deepEqual(x.domain(), [130, 1, 2, 3, -10]); <add> }, <add> "accepts a tick count to control nicing step": function(d3) { <add> var x = d3.scale.linear().domain([12, 87]).nice(5); <add> assert.deepEqual(x.domain(), [0, 100]); <add> var x = d3.scale.linear().domain([12, 87]).nice(10); <add> assert.deepEqual(x.domain(), [10, 90]); <add> var x = d3.scale.linear().domain([12, 87]).nice(100); <add> assert.deepEqual(x.domain(), [12, 87]); <ide> } <ide> }, <ide> <ide><path>test/scale/pow-test.js <ide> suite.addBatch({ <ide> assert.deepEqual(x.domain(), [1, 1, 2, 3, 11]); <ide> var x = d3.scale.pow().domain([123.1, 1, 2, 3, -.9]).nice(); <ide> assert.deepEqual(x.domain(), [130, 1, 2, 3, -10]); <add> }, <add> "accepts a tick count to control nicing step": function(d3) { <add> var x = d3.scale.pow().domain([12, 87]).nice(5); <add> assert.deepEqual(x.domain(), [0, 100]); <add> var x = d3.scale.pow().domain([12, 87]).nice(10); <add> assert.deepEqual(x.domain(), [10, 90]); <add> var x = d3.scale.pow().domain([12, 87]).nice(100); <add> assert.deepEqual(x.domain(), [12, 87]); <ide> } <ide> }, <ide>
2
Text
Text
add v3.22.0-beta.1 to changelog
1a17a61a4d4e7e89a0fd51ac39d6acf7dbbc9991
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.22.0-beta.1 (August 24, 2020) <add> <add>- [#19062](https://github.com/emberjs/ember.js/pull/19062) / [#19068](https://github.com/emberjs/ember.js/pull/19068) [FEATURE] Add @ember/destroyable feature from the [Destroyables RFC](https://github.com/emberjs/rfcs/blob/master/text/0580-destroyables.md). <add>- [#18984](https://github.com/emberjs/ember.js/pull/18984) / [#19067](https://github.com/emberjs/ember.js/pull/19067) [FEATURE] Add low-level Cache API per [Autotracking Memoization RFC](https://github.com/emberjs/rfcs/blob/master/text/0615-autotracking-memoization.md) <add>- [#19086](https://github.com/emberjs/ember.js/pull/19086) [FEATURE] Pass transition object to activate/deactivate hooks and events <add> <ide> ### v3.21.0 (August 24, 2020) <ide> <ide> - [#18993](https://github.com/emberjs/ember.js/pull/18993) [DEPRECATION] Deprecate `getWithDefault` per [RFC #554](https://github.com/emberjs/rfcs/blob/master/text/0554-deprecate-getwithdefault.md).
1
Javascript
Javascript
add test for binding in input type=checkbox
a97f8c5c5181c776896591db34216697f199d7a1
<ide><path>packages/ember-glimmer/lib/components/checkbox.js <ide> export default EmberComponent.extend({ <ide> ], <ide> <ide> type: 'checkbox', <del> checked: false, <ide> disabled: false, <ide> indeterminate: false, <ide> <ide> export default EmberComponent.extend({ <ide> }, <ide> <ide> change() { <del> set(this, 'checked', this.$().prop('checked')); <add> set(this, 'checked', this.$().prop('checked')); <ide> } <ide> }); <ide><path>packages/ember-glimmer/tests/integration/helpers/input-test.js <ide> moduleFor(`Helpers test: {{input type='checkbox'}}`, class extends InputRenderin <ide> this.assertCheckboxIsChecked(); <ide> } <ide> <add> ['@test native click changes check property'](assert) { <add> this.render(`{{input type="checkbox"}}`); <add> <add> this.assertSingleCheckbox(); <add> this.assertCheckboxIsNotChecked(); <add> this.$input()[0].click(); <add> this.assertCheckboxIsChecked(); <add> this.$input()[0].click(); <add> this.assertCheckboxIsNotChecked(); <add> } <add> <ide> ['@test with static values'](assert) { <ide> this.render(`{{input type="checkbox" disabled=false tabindex=10 name="original-name" checked=false}}`); <ide> <ide> moduleFor(`Helpers test: {{input type='checkbox'}}`, class extends InputRenderin <ide> this.assertAttr('tabindex', '10'); <ide> this.assertAttr('name', 'original-name'); <ide> } <del> <ide> }); <ide> <ide> moduleFor(`Helpers test: {{input type='text'}}`, class extends InputRenderingTest {
2
PHP
PHP
remove unused use
9c1b4c5084273d6b99ed8e36b5e8692ebf439dd7
<ide><path>src/Controller/ErrorController.php <ide> namespace Cake\Controller; <ide> <ide> use Cake\Event\Event; <del>use Cake\Routing\Router; <ide> <ide> /** <ide> * Error Handling Controller <ide><path>src/Database/Dialect/SqliteDialectTrait.php <ide> */ <ide> namespace Cake\Database\Dialect; <ide> <del>use Cake\Database\ExpressionInterface; <ide> use Cake\Database\Expression\FunctionExpression; <ide> use Cake\Database\Schema\SqliteSchema; <ide> use Cake\Database\SqlDialectTrait; <ide><path>src/Database/Type/ExpressionTypeInterface.php <ide> */ <ide> namespace Cake\Database\Type; <ide> <del>use Cake\Database\Driver; <ide> <ide> /** <ide> * An interface used by Type objects to signal whether the value should <ide><path>src/Database/Type/UuidType.php <ide> namespace Cake\Database\Type; <ide> <ide> use Cake\Database\Driver; <del>use Cake\Database\Type; <del>use Cake\Database\TypeInterface; <ide> use Cake\Utility\Text; <ide> <ide> /** <ide><path>src/Datasource/ModelAwareTrait.php <ide> namespace Cake\Datasource; <ide> <ide> use Cake\Datasource\Exception\MissingModelException; <del>use InvalidArgumentException; <ide> use UnexpectedValueException; <ide> <ide> /** <ide><path>src/Http/ActionDispatcher.php <ide> use Cake\Http\ControllerFactory; <ide> use Cake\Network\Request; <ide> use Cake\Network\Response; <del>use Cake\Routing\DispatcherFactory; <del>use Cake\Routing\Exception\MissingControllerException; <ide> use Cake\Routing\Router; <ide> use LogicException; <ide> <ide><path>src/Http/Client/Adapter/Stream.php <ide> namespace Cake\Http\Client\Adapter; <ide> <ide> use Cake\Core\Exception\Exception; <del>use Cake\Http\Client\FormData; <ide> use Cake\Http\Client\Request; <ide> use Cake\Http\Client\Response; <ide> <ide><path>src/Http/RequestTransformer.php <ide> */ <ide> namespace Cake\Http; <ide> <del>use Cake\Core\Configure; <ide> use Cake\Network\Request as CakeRequest; <ide> use Cake\Utility\Hash; <ide> use Psr\Http\Message\ServerRequestInterface as PsrRequest; <ide><path>src/Routing/Dispatcher.php <ide> */ <ide> namespace Cake\Routing; <ide> <del>use Cake\Controller\Controller; <ide> use Cake\Event\EventDispatcherTrait; <ide> use Cake\Event\EventListenerInterface; <ide> use Cake\Http\ActionDispatcher; <ide> use Cake\Network\Request; <ide> use Cake\Network\Response; <del>use LogicException; <ide> <ide> /** <ide> * Dispatcher converts Requests into controller actions. It uses the dispatched Request <ide><path>src/Routing/Filter/ControllerFactoryFilter.php <ide> */ <ide> namespace Cake\Routing\Filter; <ide> <del>use Cake\Core\App; <ide> use Cake\Event\Event; <ide> use Cake\Http\ControllerFactory; <ide> use Cake\Routing\DispatcherFilter; <del>use Cake\Utility\Inflector; <del>use ReflectionClass; <ide> <ide> /** <ide> * A dispatcher filter that builds the controller to dispatch <ide><path>src/Shell/CacheShell.php <ide> use Cake\Cache\Engine\ApcEngine; <ide> use Cake\Cache\Engine\WincacheEngine; <ide> use Cake\Console\Shell; <del>use Cake\Core\Configure; <ide> <ide> /** <ide> * Cache Shell. <ide><path>src/TestSuite/IntegrationTestCase.php <ide> use Cake\Core\Configure; <ide> use Cake\Database\Exception as DatabaseException; <ide> use Cake\Network\Session; <del>use Cake\Routing\DispatcherFactory; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\LegacyRequestDispatcher; <ide> use Cake\TestSuite\MiddlewareDispatcher; <del>use Cake\TestSuite\Stub\Response; <ide> use Cake\Utility\CookieCryptTrait; <ide> use Cake\Utility\Hash; <ide> use Cake\Utility\Security; <ide> use Exception; <ide> use LogicException; <ide> use PHPUnit_Exception; <del>use PHPUnit_Framework_Constraint_IsEqual; <ide> <ide> /** <ide> * A test case class intended to make integration tests of <ide><path>src/TestSuite/LegacyRequestDispatcher.php <ide> */ <ide> namespace Cake\TestSuite; <ide> <del>use Cake\Core\Configure; <ide> use Cake\Network\Request; <del>use Cake\Network\Session; <ide> use Cake\Routing\DispatcherFactory; <ide> use Cake\TestSuite\Stub\Response; <ide>
13
Javascript
Javascript
fix sorting issue
07992cf588897e6cbb8b0423ecb9a7d12d3f4528
<ide><path>lib/Chunk.js <ide> class Chunk { <ide> this._modules.sortWith(sortByFn || sortById); <ide> } <ide> <del> sortItems() { <add> sortItems(sortChunks) { <ide> this.sortModules(); <ide> this.origins.sort((a, b) => { <ide> const aIdent = a.module.identifier(); <ide> class Chunk { <ide> if(origin.reasons) <ide> origin.reasons.sort(); <ide> }); <del> this._parents.sort(); <del> this._chunks.sort(); <add> if(sortChunks) { <add> this._parents.sort(); <add> this._chunks.sort(); <add> } <ide> } <ide> <ide> toString() { <ide><path>lib/Compilation.js <ide> class Compilation extends Tapable { <ide> <ide> const chunks = this.chunks; <ide> for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { <del> chunks[indexChunk].sortItems(); <add> chunks[indexChunk].sortItems(false); <ide> } <ide> } <ide> <ide> class Compilation extends Tapable { <ide> <ide> const chunks = this.chunks; <ide> for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { <del> chunks[indexChunk].sortItems(); <add> chunks[indexChunk].sortItems(true); <ide> } <ide> <ide> const byMessage = (a, b) => { <ide><path>lib/util/SortableSet.js <ide> module.exports = class SortableSet extends Set { <ide> const sortedArray = Array.from(this).sort(sortFn); <ide> super.clear(); <ide> for(let i = 0; i < sortedArray.length; i += 1) { <del> this.add(sortedArray[i]); <add> super.add(sortedArray[i]); <ide> } <ide> this._lastActiveSortFn = sortFn; <add> this._frozenArray = null; <ide> } <ide> <ide> /**
3
Javascript
Javascript
add math unittests
5a026e572824f86e932e8a6af665d5c34fd0712d
<ide><path>test/unit/src/math/Math.tests.js <ide> export default QUnit.module( 'Maths', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( "lerp", ( assert ) => { <add> QUnit.test( "lerp", ( assert ) => { <add> <add> <add> assert.strictEqual(ThreeMath.lerp(1, 2, 0), 1, "Value equal to lower boundary"); <add> assert.strictEqual(ThreeMath.lerp(1, 2, 1), 2, "Value equal to upper boundary"); <add> assert.strictEqual(ThreeMath.lerp(1, 2, 0.4), 1.4, "Value within range"); <ide> <del> assert.ok( false, "everything's gonna be alright" ); <ide> <ide> } ); <ide> <ide> export default QUnit.module( 'Maths', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( "smootherstep", ( assert ) => { <add> QUnit.test( "smootherstep", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> assert.strictEqual(ThreeMath.smootherstep(- 1, 0, 2), 0, "Value lower than minimum"); <add> assert.strictEqual(ThreeMath.smootherstep(0, 0, 2), 0, "Value equal to minimum"); <add> assert.strictEqual(ThreeMath.smootherstep(0.5, 0, 2), 0.103515625, "Value within limits"); <add> assert.strictEqual(ThreeMath.smootherstep(1, 0, 2), 0.5, "Value within limits"); <add> assert.strictEqual(ThreeMath.smootherstep(1.5, 0, 2), 0.896484375, "Value within limits"); <add> assert.strictEqual(ThreeMath.smootherstep(2, 0, 2), 1, "Value equal to maximum"); <add> assert.strictEqual(ThreeMath.smootherstep(3, 0, 2), 1, "Value highter than maximum"); <ide> <ide> } ); <ide>
1
Javascript
Javascript
compare objects not identical by reference
5e52e27a76eddcb93a25d04c15a51578b27773c7
<ide><path>test/parallel/test-assert-deep.js <ide> assert.deepStrictEqual(obj1, obj2); <ide> ); <ide> } <ide> <add>// Strict equal with identical objects that are not identical <add>// by reference and longer than 30 elements <add>// E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) <add>{ <add> const a = {}; <add> const b = {}; <add> for (let i = 0; i < 35; i++) { <add> a[`symbol${i}`] = Symbol(); <add> b[`symbol${i}`] = Symbol(); <add> } <add> <add> assert.throws( <add> () => assert.deepStrictEqual(a, b), <add> { <add> code: 'ERR_ASSERTION', <add> name: 'AssertionError [ERR_ASSERTION]', <add> message: /\.\.\./g <add> } <add> ); <add>} <add> <ide> // Basic valueOf check. <ide> { <ide> const a = new String(1);
1
Javascript
Javascript
use standard version of promise.prototype.finally
d5ae59ab2a09cda5109303abb9c269318a1e6686
<ide><path>Libraries/Promise.js <ide> 'use strict'; <ide> <ide> const Promise = require('promise/setimmediate/es6-extensions'); <del>require('promise/setimmediate/done'); <ide> <del>Promise.prototype.finally = function(onSettled) { <del> return this.then(onSettled, onSettled); <del>}; <add>require('promise/setimmediate/done'); <add>require('promise/setimmediate/finally'); <ide> <ide> if (__DEV__) { <ide> require('promise/setimmediate/rejection-tracking').enable({
1
Javascript
Javascript
move template rendering related tests
98b073b31700abe76b56f6a81feb9862b0b6e429
<ide><path>packages/ember/tests/routing/decoupled_basic_test.js <ide> import RSVP from 'rsvp'; <ide> import { compile } from 'ember-template-compiler'; <ide> import { Route, NoneLocation, HistoryLocation } from '@ember/-internals/routing'; <ide> import Controller from '@ember/controller'; <del>import { Object as EmberObject, A as emberA } from '@ember/-internals/runtime'; <add>import { Object as EmberObject } from '@ember/-internals/runtime'; <ide> import { <ide> moduleFor, <ide> ApplicationTestCase, <ide> import { <ide> } from 'internal-test-helpers'; <ide> import { run } from '@ember/runloop'; <ide> import { Mixin, set, addObserver } from '@ember/-internals/metal'; <del>import { Component } from '@ember/-internals/glimmer'; <ide> import Engine from '@ember/engine'; <ide> import { InternalTransition as Transition } from 'router_js'; <ide> <ide> moduleFor( <ide> }); <ide> } <ide> <del> [`@test The Homepage with explicit template name in renderTemplate`](assert) { <del> this.add( <del> 'route:home', <del> Route.extend({ <del> renderTemplate() { <del> this.render('homepage'); <del> }, <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> let text = this.$('#troll').text(); <del> assert.equal(text, 'Megatroll', 'the homepage template was rendered'); <del> }); <del> } <del> <del> async [`@test an alternate template will pull in an alternate controller`](assert) { <del> this.add( <del> 'route:home', <del> Route.extend({ <del> renderTemplate() { <del> this.render('homepage'); <del> }, <del> }) <del> ); <del> this.add( <del> 'controller:homepage', <del> Controller.extend({ <del> init() { <del> this._super(...arguments); <del> this.name = 'Comes from homepage'; <del> }, <del> }) <del> ); <del> <del> await this.visit('/'); <del> <del> assert.equal(this.$('p').text(), 'Comes from homepage', 'the homepage template was rendered'); <del> } <del> <del> async [`@test An alternate template will pull in an alternate controller instead of controllerName`]( <del> assert <del> ) { <del> this.add( <del> 'route:home', <del> Route.extend({ <del> controllerName: 'foo', <del> renderTemplate() { <del> this.render('homepage'); <del> }, <del> }) <del> ); <del> this.add( <del> 'controller:foo', <del> Controller.extend({ <del> init() { <del> this._super(...arguments); <del> this.name = 'Comes from foo'; <del> }, <del> }) <del> ); <del> this.add( <del> 'controller:homepage', <del> Controller.extend({ <del> init() { <del> this._super(...arguments); <del> this.name = 'Comes from homepage'; <del> }, <del> }) <del> ); <del> <del> await this.visit('/'); <del> <del> assert.equal(this.$('p').text(), 'Comes from homepage', 'the homepage template was rendered'); <del> } <del> <del> async [`@test The template will pull in an alternate controller via key/value`](assert) { <del> this.router.map(function() { <del> this.route('homepage', { path: '/' }); <del> }); <del> <del> this.add( <del> 'route:homepage', <del> Route.extend({ <del> renderTemplate() { <del> this.render({ controller: 'home' }); <del> }, <del> }) <del> ); <del> this.add( <del> 'controller:home', <del> Controller.extend({ <del> init() { <del> this._super(...arguments); <del> this.name = 'Comes from home.'; <del> }, <del> }) <del> ); <del> <del> await this.visit('/'); <del> <del> assert.equal( <del> this.$('p').text(), <del> 'Comes from home.', <del> 'the homepage template was rendered from data from the HomeController' <del> ); <del> } <del> <del> async [`@test The Homepage with explicit template name in renderTemplate and controller`]( <del> assert <del> ) { <del> this.add( <del> 'controller:home', <del> Controller.extend({ <del> init() { <del> this._super(...arguments); <del> this.name = 'YES I AM HOME'; <del> }, <del> }) <del> ); <del> this.add( <del> 'route:home', <del> Route.extend({ <del> renderTemplate() { <del> this.render('homepage'); <del> }, <del> }) <del> ); <del> <del> await this.visit('/'); <del> <del> assert.equal(this.$('p').text(), 'YES I AM HOME', 'The homepage template was rendered'); <del> } <del> <del> [`@feature(!EMBER_ROUTING_MODEL_ARG) Model passed via renderTemplate model is set as controller's model`]( <del> assert <del> ) { <del> this.addTemplate('bio', '<p>{{this.model.name}}</p>'); <del> this.add( <del> 'route:home', <del> Route.extend({ <del> renderTemplate() { <del> this.render('bio', { <del> model: { name: 'emberjs' }, <del> }); <del> }, <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> let text = this.$('p').text(); <del> <del> assert.equal(text, 'emberjs', `Passed model was set as controller's model`); <del> }); <del> } <del> <del> async [`@feature(EMBER_ROUTING_MODEL_ARG) Model passed via renderTemplate model is set as controller's model`]( <del> assert <del> ) { <del> this.addTemplate( <del> 'bio', <del> '<p>Model: {{@model.name}}</p><p>Controller: {{this.model.name}}</p>' <del> ); <del> this.add( <del> 'route:home', <del> Route.extend({ <del> renderTemplate() { <del> this.render('bio', { <del> model: { name: 'emberjs' }, <del> }); <del> }, <del> }) <del> ); <del> <del> await this.visit('/'); <del> <del> let text = this.$('p').text(); <del> <del> assert.ok( <del> text.indexOf('Model: emberjs') > -1, <del> 'Passed model was available as the `@model` argument' <del> ); <del> <del> assert.ok( <del> text.indexOf('Controller: emberjs') > -1, <del> "Passed model was set as controller's `model` property" <del> ); <del> } <del> <del> ['@test render uses templateName from route'](assert) { <del> this.addTemplate('the_real_home_template', '<p>THIS IS THE REAL HOME</p>'); <del> this.add( <del> 'route:home', <del> Route.extend({ <del> templateName: 'the_real_home_template', <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> let text = this.$('p').text(); <del> <del> assert.equal(text, 'THIS IS THE REAL HOME', 'the homepage template was rendered'); <del> }); <del> } <del> <del> ['@test defining templateName allows other templates to be rendered'](assert) { <del> this.addTemplate('alert', `<div class='alert-box'>Invader!</div>`); <del> this.addTemplate('the_real_home_template', `<p>THIS IS THE REAL HOME</p>{{outlet 'alert'}}`); <del> this.add( <del> 'route:home', <del> Route.extend({ <del> templateName: 'the_real_home_template', <del> actions: { <del> showAlert() { <del> this.render('alert', { <del> into: 'home', <del> outlet: 'alert', <del> }); <del> }, <del> }, <del> }) <del> ); <del> <del> return this.visit('/') <del> .then(() => { <del> let text = this.$('p').text(); <del> assert.equal(text, 'THIS IS THE REAL HOME', 'the homepage template was rendered'); <del> <del> return runTask(() => this.appRouter.send('showAlert')); <del> }) <del> .then(() => { <del> let text = this.$('.alert-box').text(); <del> <del> assert.equal(text, 'Invader!', 'Template for alert was rendered into the outlet'); <del> }); <del> } <del> <del> ['@test templateName is still used when calling render with no name and options'](assert) { <del> this.addTemplate('alert', `<div class='alert-box'>Invader!</div>`); <del> this.addTemplate('home', `<p>THIS IS THE REAL HOME</p>{{outlet 'alert'}}`); <del> <del> this.add( <del> 'route:home', <del> Route.extend({ <del> templateName: 'alert', <del> renderTemplate() { <del> this.render({}); <del> }, <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> let text = this.$('.alert-box').text(); <del> <del> assert.equal(text, 'Invader!', 'default templateName was rendered into outlet'); <del> }); <del> } <del> <ide> ['@feature(!EMBER_ROUTING_MODEL_ARG) The Special Page returning a promise puts the app into a loading state until the promise is resolved']() { <ide> this.router.map(function() { <ide> this.route('home', { path: '/' }); <ide> moduleFor( <ide> }) <ide> ); <ide> <del> let promise = runTask(() => <del> handleURLRejectsWith(this, assert, '/specials/1', 'Setup error') <del> ); <add> let promise = runTask(() => handleURLRejectsWith(this, assert, '/specials/1', 'Setup error')); <ide> <ide> resolve(menuItem); <ide> <ide> moduleFor( <ide> }); <ide> } <ide> <del> ['@test Generated names can be customized when providing routes with dot notation'](assert) { <del> assert.expect(4); <add> ['@test Router accounts for rootURL on page load when using history location'](assert) { <add> let rootURL = window.location.pathname + '/app'; <add> let postsTemplateRendered = false; <add> let setHistory; <ide> <del> this.addTemplate('index', '<div>Index</div>'); <del> this.addTemplate('application', "<h1>Home</h1><div class='main'>{{outlet}}</div>"); <del> this.addTemplate('foo', "<div class='middle'>{{outlet}}</div>"); <del> this.addTemplate('bar', "<div class='bottom'>{{outlet}}</div>"); <del> this.addTemplate('bar.baz', '<p>{{name}}Bottom!</p>'); <add> setHistory = function(obj, path) { <add> obj.set('history', { state: { path: path } }); <add> }; <ide> <del> this.router.map(function() { <del> this.route('foo', { path: '/top' }, function() { <del> this.route('bar', { path: '/middle', resetNamespace: true }, function() { <del> this.route('baz', { path: '/bottom' }); <add> let location = HistoryLocation.create({ <add> initState() { <add> let path = rootURL + '/posts'; <add> <add> setHistory(this, path); <add> this.set('location', { <add> pathname: path, <add> href: 'http://localhost/' + path, <ide> }); <del> }); <add> }, <add> <add> replaceState(path) { <add> setHistory(this, path); <add> }, <add> <add> pushState(path) { <add> setHistory(this, path); <add> }, <ide> }); <ide> <del> this.add( <del> 'route:foo', <del> Route.extend({ <del> renderTemplate() { <del> assert.ok(true, 'FooBarRoute was called'); <del> return this._super(...arguments); <del> }, <del> }) <del> ); <add> this.router.reopen({ <add> // location: 'historyTest', <add> location, <add> rootURL: rootURL, <add> }); <add> <add> this.router.map(function() { <add> this.route('posts', { path: '/posts' }); <add> }); <ide> <ide> this.add( <del> 'route:bar.baz', <add> 'route:posts', <ide> Route.extend({ <add> model() {}, <ide> renderTemplate() { <del> assert.ok(true, 'BarBazRoute was called'); <del> return this._super(...arguments); <add> postsTemplateRendered = true; <ide> }, <ide> }) <ide> ); <ide> <del> this.add( <del> 'controller:bar', <del> Controller.extend({ <del> name: 'Bar', <del> }) <del> ); <del> <del> this.add( <del> 'controller:bar.baz', <del> Controller.extend({ <del> name: 'BarBaz', <del> }) <del> ); <add> return this.visit('/').then(() => { <add> assert.ok(postsTemplateRendered, 'Posts route successfully stripped from rootURL'); <ide> <del> return this.visit('/top/middle/bottom').then(() => { <del> assert.ok(true, '/top/middle/bottom has been handled'); <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> getTextOf(rootElement.querySelector('.main .middle .bottom p')), <del> 'BarBazBottom!', <del> 'The templates were rendered into their appropriate parents' <del> ); <del> }); <del> } <del> <del> ["@test Child routes render into their parent route's template by default"](assert) { <del> this.addTemplate('index', '<div>Index</div>'); <del> this.addTemplate('application', "<h1>Home</h1><div class='main'>{{outlet}}</div>"); <del> this.addTemplate('top', "<div class='middle'>{{outlet}}</div>"); <del> this.addTemplate('middle', "<div class='bottom'>{{outlet}}</div>"); <del> this.addTemplate('middle.bottom', '<p>Bottom!</p>'); <del> <del> this.router.map(function() { <del> this.route('top', function() { <del> this.route('middle', { resetNamespace: true }, function() { <del> this.route('bottom'); <del> }); <del> }); <del> }); <del> <del> return this.visit('/top/middle/bottom').then(() => { <del> assert.ok(true, '/top/middle/bottom has been handled'); <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> getTextOf(rootElement.querySelector('.main .middle .bottom p')), <del> 'Bottom!', <del> 'The templates were rendered into their appropriate parents' <del> ); <del> }); <del> } <del> <del> ['@test Child routes render into specified template'](assert) { <del> this.addTemplate('index', '<div>Index</div>'); <del> this.addTemplate('application', "<h1>Home</h1><div class='main'>{{outlet}}</div>"); <del> this.addTemplate('top', "<div class='middle'>{{outlet}}</div>"); <del> this.addTemplate('middle', "<div class='bottom'>{{outlet}}</div>"); <del> this.addTemplate('middle.bottom', '<p>Bottom!</p>'); <del> <del> this.router.map(function() { <del> this.route('top', function() { <del> this.route('middle', { resetNamespace: true }, function() { <del> this.route('bottom'); <del> }); <del> }); <del> }); <del> <del> this.add( <del> 'route:middle.bottom', <del> Route.extend({ <del> renderTemplate() { <del> this.render('middle/bottom', { into: 'top' }); <del> }, <del> }) <del> ); <del> <del> return this.visit('/top/middle/bottom').then(() => { <del> assert.ok(true, '/top/middle/bottom has been handled'); <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> rootElement.querySelectorAll('.main .middle .bottom p').length, <del> 0, <del> 'should not render into the middle template' <del> ); <del> assert.equal( <del> getTextOf(rootElement.querySelector('.main .middle > p')), <del> 'Bottom!', <del> 'The template was rendered into the top template' <del> ); <del> }); <del> } <del> <del> ['@test Rendering into specified template with slash notation'](assert) { <del> this.addTemplate('person.profile', 'profile {{outlet}}'); <del> this.addTemplate('person.details', 'details!'); <del> <del> this.router.map(function() { <del> this.route('home', { path: '/' }); <del> }); <del> <del> this.add( <del> 'route:home', <del> Route.extend({ <del> renderTemplate() { <del> this.render('person/profile'); <del> this.render('person/details', { into: 'person/profile' }); <del> }, <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> rootElement.textContent.trim(), <del> 'profile details!', <del> 'The templates were rendered' <del> ); <del> }); <del> } <del> <del> ['@test Router accounts for rootURL on page load when using history location'](assert) { <del> let rootURL = window.location.pathname + '/app'; <del> let postsTemplateRendered = false; <del> let setHistory; <del> <del> setHistory = function(obj, path) { <del> obj.set('history', { state: { path: path } }); <del> }; <del> <del> let location = HistoryLocation.create({ <del> initState() { <del> let path = rootURL + '/posts'; <del> <del> setHistory(this, path); <del> this.set('location', { <del> pathname: path, <del> href: 'http://localhost/' + path, <del> }); <del> }, <del> <del> replaceState(path) { <del> setHistory(this, path); <del> }, <del> <del> pushState(path) { <del> setHistory(this, path); <del> }, <del> }); <del> <del> this.router.reopen({ <del> // location: 'historyTest', <del> location, <del> rootURL: rootURL, <del> }); <del> <del> this.router.map(function() { <del> this.route('posts', { path: '/posts' }); <del> }); <del> <del> this.add( <del> 'route:posts', <del> Route.extend({ <del> model() {}, <del> renderTemplate() { <del> postsTemplateRendered = true; <del> }, <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> assert.ok(postsTemplateRendered, 'Posts route successfully stripped from rootURL'); <del> <del> runDestroy(location); <del> location = null; <add> runDestroy(location); <add> location = null; <ide> }); <ide> } <ide> <ide> moduleFor( <ide> return this.visit('/'); <ide> } <ide> <del> ['@test Only use route rendered into main outlet for default into property on child'](assert) { <del> this.addTemplate('application', "{{outlet 'menu'}}{{outlet}}"); <del> this.addTemplate('posts', '{{outlet}}'); <del> this.addTemplate('posts.index', '<p class="posts-index">postsIndex</p>'); <del> this.addTemplate('posts.menu', '<div class="posts-menu">postsMenu</div>'); <del> <del> this.router.map(function() { <del> this.route('posts', function() {}); <del> }); <del> <del> this.add( <del> 'route:posts', <del> Route.extend({ <del> renderTemplate() { <del> this.render(); <del> this.render('posts/menu', { <del> into: 'application', <del> outlet: 'menu', <del> }); <del> }, <del> }) <del> ); <del> <del> return this.visit('/posts').then(() => { <del> assert.ok(true, '/posts has been handled'); <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-menu')), <del> 'postsMenu', <del> 'The posts/menu template was rendered' <del> ); <del> assert.equal( <del> getTextOf(rootElement.querySelector('p.posts-index')), <del> 'postsIndex', <del> 'The posts/index template was rendered' <del> ); <del> }); <del> } <del> <ide> ['@test Generating a URL should not affect currentModel'](assert) { <ide> this.router.map(function() { <ide> this.route('post', { path: '/posts/:post_id' }); <ide> moduleFor( <ide> }); <ide> } <ide> <del> ['@test Application template does not duplicate when re-rendered'](assert) { <del> this.addTemplate('application', '<h3 class="render-once">I render once</h3>{{outlet}}'); <add> ['@test Promises encountered on app load put app into loading state until resolved'](assert) { <add> assert.expect(2); <ide> <add> let deferred = RSVP.defer(); <ide> this.router.map(function() { <del> this.route('posts'); <add> this.route('index', { path: '/' }); <ide> }); <ide> <ide> this.add( <del> 'route:application', <add> 'route:index', <ide> Route.extend({ <ide> model() { <del> return emberA(); <add> return deferred.promise; <ide> }, <ide> }) <ide> ); <ide> <del> return this.visit('/posts').then(() => { <del> assert.ok(true, '/posts has been handled'); <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal(getTextOf(rootElement.querySelector('h3.render-once')), 'I render once'); <del> }); <add> this.addTemplate('index', '<p>INDEX</p>'); <add> this.addTemplate('loading', '<p>LOADING</p>'); <add> <add> run(() => this.visit('/')); <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> getTextOf(rootElement.querySelector('p')), <add> 'LOADING', <add> 'The loading state is displaying.' <add> ); <add> run(deferred.resolve); <add> assert.equal( <add> getTextOf(rootElement.querySelector('p')), <add> 'INDEX', <add> 'The index route is display.' <add> ); <ide> } <ide> <del> ['@test Child routes should render inside the application template if the application template causes a redirect']( <del> assert <del> ) { <del> this.addTemplate('application', '<h3>App</h3> {{outlet}}'); <del> this.addTemplate('posts', 'posts'); <add> ['@test Router `willTransition` hook passes in cancellable transition'](assert) { <add> assert.expect(8); <add> this.router.reopen({ <add> willTransition(_, _2, transition) { <add> assert.ok(true, 'willTransition was called'); <add> if (transition.intent.url !== '/') { <add> transition.abort(); <add> } <add> }, <add> }); <ide> <ide> this.router.map(function() { <del> this.route('posts'); <del> this.route('photos'); <add> this.route('nork'); <add> this.route('about'); <ide> }); <ide> <ide> this.add( <del> 'route:application', <add> 'route:loading', <ide> Route.extend({ <del> afterModel() { <del> this.transitionTo('posts'); <add> activate() { <add> assert.ok(false, 'LoadingRoute was not entered'); <ide> }, <ide> }) <ide> ); <ide> <del> return this.visit('/posts').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal(rootElement.textContent.trim(), 'App posts'); <del> }); <del> } <del> <del> ["@feature(!EMBER_ROUTING_MODEL_ARG) The template is not re-rendered when the route's context changes"]( <del> assert <del> ) { <del> this.router.map(function() { <del> this.route('page', { path: '/page/:name' }); <del> }); <del> <ide> this.add( <del> 'route:page', <add> 'route:nork', <ide> Route.extend({ <del> model(params) { <del> return EmberObject.create({ name: params.name }); <add> activate() { <add> assert.ok(false, 'NorkRoute was not entered'); <ide> }, <ide> }) <ide> ); <ide> <del> let insertionCount = 0; <ide> this.add( <del> 'component:foo-bar', <del> Component.extend({ <del> didInsertElement() { <del> insertionCount += 1; <add> 'route:about', <add> Route.extend({ <add> activate() { <add> assert.ok(false, 'AboutRoute was not entered'); <ide> }, <ide> }) <ide> ); <ide> <del> this.addTemplate('page', '<p>{{this.model.name}}{{foo-bar}}</p>'); <add> let deprecation = /You attempted to override the "willTransition" method which is deprecated\./; <ide> <del> let rootElement = document.getElementById('qunit-fixture'); <del> return this.visit('/page/first') <del> .then(() => { <del> assert.ok(true, '/page/first has been handled'); <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'first'); <del> assert.equal(insertionCount, 1); <del> return this.visit('/page/second'); <del> }) <del> .then(() => { <del> assert.ok(true, '/page/second has been handled'); <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'second'); <del> assert.equal(insertionCount, 1, 'view should have inserted only once'); <del> let router = this.applicationInstance.lookup('router:main'); <del> return run(() => router.transitionTo('page', EmberObject.create({ name: 'third' }))); <del> }) <del> .then(() => { <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'third'); <del> assert.equal(insertionCount, 1, 'view should still have inserted only once'); <add> return expectDeprecationAsync(() => { <add> return this.visit('/').then(() => { <add> this.handleURLAborts(assert, '/nork', deprecation); <add> this.handleURLAborts(assert, '/about', deprecation); <ide> }); <add> }, deprecation); <ide> } <ide> <del> async ["@feature(EMBER_ROUTING_MODEL_ARG) The template is not re-rendered when the route's model changes"]( <add> ['@test Aborting/redirecting the transition in `willTransition` prevents LoadingRoute from being entered']( <ide> assert <ide> ) { <add> assert.expect(5); <add> <ide> this.router.map(function() { <del> this.route('page', { path: '/page/:name' }); <add> this.route('index'); <add> this.route('nork'); <add> this.route('about'); <ide> }); <ide> <add> let redirect = false; <add> <ide> this.add( <del> 'route:page', <add> 'route:index', <ide> Route.extend({ <del> model(params) { <del> return EmberObject.create({ name: params.name }); <add> actions: { <add> willTransition(transition) { <add> assert.ok(true, 'willTransition was called'); <add> if (redirect) { <add> // router.js won't refire `willTransition` for this redirect <add> this.transitionTo('about'); <add> } else { <add> transition.abort(); <add> } <add> }, <ide> }, <ide> }) <ide> ); <ide> <del> let insertionCount = 0; <add> let deferred = null; <add> <ide> this.add( <del> 'component:foo-bar', <del> Component.extend({ <del> didInsertElement() { <del> insertionCount += 1; <add> 'route:loading', <add> Route.extend({ <add> activate() { <add> assert.ok(deferred, 'LoadingRoute should be entered at this time'); <add> }, <add> deactivate() { <add> assert.ok(true, 'LoadingRoute was exited'); <ide> }, <ide> }) <ide> ); <ide> <del> this.addTemplate('page', '<p>{{@model.name}}{{foo-bar}}</p>'); <del> <del> let rootElement = document.getElementById('qunit-fixture'); <del> <del> await this.visit('/page/first'); <del> <del> assert.ok(true, '/page/first has been handled'); <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'first'); <del> assert.equal(insertionCount, 1); <del> <del> await this.visit('/page/second'); <del> <del> assert.ok(true, '/page/second has been handled'); <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'second'); <del> assert.equal(insertionCount, 1, 'view should have inserted only once'); <del> let router = this.applicationInstance.lookup('router:main'); <del> <del> await run(() => router.transitionTo('page', EmberObject.create({ name: 'third' }))); <del> <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'third'); <del> assert.equal(insertionCount, 1, 'view should still have inserted only once'); <del> } <del> <del> ['@test The template is not re-rendered when two routes present the exact same template & controller']( <del> assert <del> ) { <del> this.router.map(function() { <del> this.route('first'); <del> this.route('second'); <del> this.route('third'); <del> this.route('fourth'); <del> }); <del> <del> // Note add a component to test insertion <del> <del> let insertionCount = 0; <ide> this.add( <del> 'component:x-input', <del> Component.extend({ <del> didInsertElement() { <del> insertionCount += 1; <del> }, <add> 'route:nork', <add> Route.extend({ <add> activate() { <add> assert.ok(true, 'NorkRoute was entered'); <add> }, <ide> }) <ide> ); <ide> <del> let SharedRoute = Route.extend({ <del> setupController() { <del> this.controllerFor('shared').set('message', 'This is the ' + this.routeName + ' message'); <del> }, <del> <del> renderTemplate() { <del> this.render('shared', { controller: 'shared' }); <del> }, <del> }); <del> <del> this.add('route:shared', SharedRoute); <del> this.add('route:first', SharedRoute.extend()); <del> this.add('route:second', SharedRoute.extend()); <del> this.add('route:third', SharedRoute.extend()); <del> this.add('route:fourth', SharedRoute.extend()); <add> this.add( <add> 'route:about', <add> Route.extend({ <add> activate() { <add> assert.ok(true, 'AboutRoute was entered'); <add> }, <add> model() { <add> if (deferred) { <add> return deferred.promise; <add> } <add> }, <add> }) <add> ); <ide> <del> this.add('controller:shared', Controller.extend()); <add> return this.visit('/').then(() => { <add> let router = this.applicationInstance.lookup('router:main'); <add> // Attempted transitions out of index should abort. <add> run(router, 'transitionTo', 'nork'); <add> run(router, 'handleURL', '/nork'); <ide> <del> this.addTemplate('shared', '<p>{{message}}{{x-input}}</p>'); <add> // Attempted transitions out of index should redirect to about <add> redirect = true; <add> run(router, 'transitionTo', 'nork'); <add> run(router, 'transitionTo', 'index'); <ide> <del> let rootElement = document.getElementById('qunit-fixture'); <del> return this.visit('/first') <del> .then(() => { <del> assert.ok(true, '/first has been handled'); <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'This is the first message'); <del> assert.equal(insertionCount, 1, 'expected one assertion'); <del> return this.visit('/second'); <del> }) <del> .then(() => { <del> assert.ok(true, '/second has been handled'); <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'This is the second message'); <del> assert.equal(insertionCount, 1, 'expected one assertion'); <del> return run(() => { <del> this.applicationInstance <del> .lookup('router:main') <del> .transitionTo('third') <del> .then( <del> function() { <del> assert.ok(true, 'expected transition'); <del> }, <del> function(reason) { <del> assert.ok(false, 'unexpected transition failure: ', QUnit.jsDump.parse(reason)); <del> } <del> ); <del> }); <del> }) <del> .then(() => { <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'This is the third message'); <del> assert.equal(insertionCount, 1, 'expected one assertion'); <del> return this.visit('fourth'); <del> }) <del> .then(() => { <del> assert.ok(true, '/fourth has been handled'); <del> assert.equal(insertionCount, 1, 'expected one assertion'); <del> assert.equal(getTextOf(rootElement.querySelector('p')), 'This is the fourth message'); <del> }); <add> // Redirected transitions out of index to a route with a <add> // promise model should pause the transition and <add> // activate LoadingRoute <add> deferred = RSVP.defer(); <add> run(router, 'transitionTo', 'nork'); <add> run(deferred.resolve); <add> }); <ide> } <ide> <del> ['@test Promises encountered on app load put app into loading state until resolved'](assert) { <del> assert.expect(2); <add> async ['@test `didTransition` event fires on the router'](assert) { <add> assert.expect(3); <ide> <del> let deferred = RSVP.defer(); <ide> this.router.map(function() { <del> this.route('index', { path: '/' }); <add> this.route('nork'); <ide> }); <ide> <del> this.add( <del> 'route:index', <del> Route.extend({ <del> model() { <del> return deferred.promise; <del> }, <del> }) <del> ); <add> await this.visit('/'); <ide> <del> this.addTemplate('index', '<p>INDEX</p>'); <del> this.addTemplate('loading', '<p>LOADING</p>'); <add> let router = this.applicationInstance.lookup('router:main'); <add> router.one('didTransition', function() { <add> assert.ok(true, 'didTransition fired on initial routing'); <add> }); <ide> <del> run(() => this.visit('/')); <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> getTextOf(rootElement.querySelector('p')), <del> 'LOADING', <del> 'The loading state is displaying.' <del> ); <del> run(deferred.resolve); <del> assert.equal( <del> getTextOf(rootElement.querySelector('p')), <del> 'INDEX', <del> 'The index route is display.' <del> ); <add> await this.visit('/'); <add> <add> router.one('didTransition', function() { <add> assert.ok(true, 'didTransition fired on the router'); <add> assert.equal( <add> router.get('url'), <add> '/nork', <add> 'The url property is updated by the time didTransition fires' <add> ); <add> }); <add> <add> await this.visit('/nork'); <ide> } <ide> <del> ['@test Route should tear down multiple outlets'](assert) { <del> this.addTemplate('application', "{{outlet 'menu'}}{{outlet}}{{outlet 'footer'}}"); <del> this.addTemplate('posts', '{{outlet}}'); <del> this.addTemplate('users', 'users'); <del> this.addTemplate('posts.index', '<p class="posts-index">postsIndex</p>'); <del> this.addTemplate('posts.menu', '<div class="posts-menu">postsMenu</div>'); <del> this.addTemplate('posts.footer', '<div class="posts-footer">postsFooter</div>'); <add> ['@test `activate` event fires on the route'](assert) { <add> assert.expect(2); <add> <add> let eventFired = 0; <ide> <ide> this.router.map(function() { <del> this.route('posts', function() {}); <del> this.route('users', function() {}); <add> this.route('nork'); <ide> }); <ide> <ide> this.add( <del> 'route:posts', <add> 'route:nork', <ide> Route.extend({ <del> renderTemplate() { <del> this.render('posts/menu', { <del> into: 'application', <del> outlet: 'menu', <del> }); <del> <del> this.render(); <add> init() { <add> this._super(...arguments); <ide> <del> this.render('posts/footer', { <del> into: 'application', <del> outlet: 'footer', <add> this.on('activate', function() { <add> assert.equal(++eventFired, 1, 'activate event is fired once'); <ide> }); <ide> }, <add> <add> activate() { <add> assert.ok(true, 'activate hook is called'); <add> }, <ide> }) <ide> ); <ide> <del> let rootElement = document.getElementById('qunit-fixture'); <del> return this.visit('/posts') <del> .then(() => { <del> assert.ok(true, '/posts has been handled'); <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-menu')), <del> 'postsMenu', <del> 'The posts/menu template was rendered' <del> ); <del> assert.equal( <del> getTextOf(rootElement.querySelector('p.posts-index')), <del> 'postsIndex', <del> 'The posts/index template was rendered' <del> ); <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-footer')), <del> 'postsFooter', <del> 'The posts/footer template was rendered' <del> ); <del> <del> return this.visit('/users'); <del> }) <del> .then(() => { <del> assert.ok(true, '/users has been handled'); <del> assert.equal( <del> rootElement.querySelector('div.posts-menu'), <del> null, <del> 'The posts/menu template was removed' <del> ); <del> assert.equal( <del> rootElement.querySelector('p.posts-index'), <del> null, <del> 'The posts/index template was removed' <del> ); <del> assert.equal( <del> rootElement.querySelector('div.posts-footer'), <del> null, <del> 'The posts/footer template was removed' <del> ); <del> }); <add> return this.visit('/nork'); <ide> } <ide> <del> ['@test Route supports clearing outlet explicitly'](assert) { <del> this.addTemplate('application', "{{outlet}}{{outlet 'modal'}}"); <del> this.addTemplate('posts', '{{outlet}}'); <del> this.addTemplate('users', 'users'); <del> this.addTemplate('posts.index', '<div class="posts-index">postsIndex {{outlet}}</div>'); <del> this.addTemplate('posts.modal', '<div class="posts-modal">postsModal</div>'); <del> this.addTemplate('posts.extra', '<div class="posts-extra">postsExtra</div>'); <add> ['@test `deactivate` event fires on the route'](assert) { <add> assert.expect(2); <add> <add> let eventFired = 0; <ide> <ide> this.router.map(function() { <del> this.route('posts', function() {}); <del> this.route('users', function() {}); <add> this.route('nork'); <add> this.route('dork'); <ide> }); <ide> <ide> this.add( <del> 'route:posts', <add> 'route:nork', <ide> Route.extend({ <del> actions: { <del> showModal() { <del> this.render('posts/modal', { <del> into: 'application', <del> outlet: 'modal', <del> }); <del> }, <del> hideModal() { <del> this.disconnectOutlet({ <del> outlet: 'modal', <del> parentView: 'application', <del> }); <del> }, <add> init() { <add> this._super(...arguments); <add> <add> this.on('deactivate', function() { <add> assert.equal(++eventFired, 1, 'deactivate event is fired once'); <add> }); <ide> }, <del> }) <del> ); <ide> <del> this.add( <del> 'route:posts.index', <del> Route.extend({ <del> actions: { <del> showExtra() { <del> this.render('posts/extra', { <del> into: 'posts/index', <del> }); <del> }, <del> hideExtra() { <del> this.disconnectOutlet({ parentView: 'posts/index' }); <del> }, <add> deactivate() { <add> assert.ok(true, 'deactivate hook is called'); <ide> }, <ide> }) <ide> ); <ide> <del> let rootElement = document.getElementById('qunit-fixture'); <del> <del> return this.visit('/posts') <del> .then(() => { <del> let router = this.applicationInstance.lookup('router:main'); <del> <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-index')), <del> 'postsIndex', <del> 'The posts/index template was rendered' <del> ); <del> run(() => router.send('showModal')); <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-modal')), <del> 'postsModal', <del> 'The posts/modal template was rendered' <del> ); <del> run(() => router.send('showExtra')); <del> <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-extra')), <del> 'postsExtra', <del> 'The posts/extra template was rendered' <del> ); <del> run(() => router.send('hideModal')); <del> <del> assert.equal( <del> rootElement.querySelector('div.posts-modal'), <del> null, <del> 'The posts/modal template was removed' <del> ); <del> run(() => router.send('hideExtra')); <del> <del> assert.equal( <del> rootElement.querySelector('div.posts-extra'), <del> null, <del> 'The posts/extra template was removed' <del> ); <del> run(function() { <del> router.send('showModal'); <del> }); <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-modal')), <del> 'postsModal', <del> 'The posts/modal template was rendered' <del> ); <del> run(function() { <del> router.send('showExtra'); <del> }); <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-extra')), <del> 'postsExtra', <del> 'The posts/extra template was rendered' <del> ); <del> return this.visit('/users'); <del> }) <del> .then(() => { <del> assert.equal( <del> rootElement.querySelector('div.posts-index'), <del> null, <del> 'The posts/index template was removed' <del> ); <del> assert.equal( <del> rootElement.querySelector('div.posts-modal'), <del> null, <del> 'The posts/modal template was removed' <del> ); <del> assert.equal( <del> rootElement.querySelector('div.posts-extra'), <del> null, <del> 'The posts/extra template was removed' <del> ); <del> }); <add> return this.visit('/nork').then(() => this.visit('/dork')); <ide> } <ide> <del> ['@test Route supports clearing outlet using string parameter'](assert) { <del> this.addTemplate('application', "{{outlet}}{{outlet 'modal'}}"); <del> this.addTemplate('posts', '{{outlet}}'); <del> this.addTemplate('users', 'users'); <del> this.addTemplate('posts.index', '<div class="posts-index">postsIndex {{outlet}}</div>'); <del> this.addTemplate('posts.modal', '<div class="posts-modal">postsModal</div>'); <add> ['@test Actions can be handled by inherited action handlers'](assert) { <add> assert.expect(4); <ide> <del> this.router.map(function() { <del> this.route('posts', function() {}); <del> this.route('users', function() {}); <add> let SuperRoute = Route.extend({ <add> actions: { <add> foo() { <add> assert.ok(true, 'foo'); <add> }, <add> bar(msg) { <add> assert.equal(msg, 'HELLO'); <add> }, <add> }, <add> }); <add> <add> let RouteMixin = Mixin.create({ <add> actions: { <add> bar(msg) { <add> assert.equal(msg, 'HELLO'); <add> this._super(msg); <add> }, <add> }, <ide> }); <ide> <ide> this.add( <del> 'route:posts', <del> Route.extend({ <add> 'route:home', <add> SuperRoute.extend(RouteMixin, { <ide> actions: { <del> showModal() { <del> this.render('posts/modal', { <del> into: 'application', <del> outlet: 'modal', <del> }); <del> }, <del> hideModal() { <del> this.disconnectOutlet('modal'); <add> baz() { <add> assert.ok(true, 'baz'); <ide> }, <ide> }, <ide> }) <ide> ); <ide> <del> let rootElement = document.getElementById('qunit-fixture'); <del> return this.visit('/posts') <del> .then(() => { <del> let router = this.applicationInstance.lookup('router:main'); <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-index')), <del> 'postsIndex', <del> 'The posts/index template was rendered' <del> ); <del> run(() => router.send('showModal')); <del> assert.equal( <del> getTextOf(rootElement.querySelector('div.posts-modal')), <del> 'postsModal', <del> 'The posts/modal template was rendered' <del> ); <del> run(() => router.send('hideModal')); <del> assert.equal( <del> rootElement.querySelector('div.posts-modal'), <del> null, <del> 'The posts/modal template was removed' <del> ); <del> return this.visit('/users'); <del> }) <del> .then(() => { <del> assert.equal( <del> rootElement.querySelector('div.posts-index'), <del> null, <del> 'The posts/index template was removed' <del> ); <del> assert.equal( <del> rootElement.querySelector('div.posts-modal'), <del> null, <del> 'The posts/modal template was removed' <del> ); <del> }); <del> } <add> this.addTemplate( <add> 'home', <add> ` <add> <a class="do-foo" {{action "foo"}}>Do foo</a> <add> <a class="do-bar-with-arg" {{action "bar" "HELLO"}}>Do bar with arg</a> <add> <a class="do-baz" {{action "baz"}}>Do bar</a> <add> ` <add> ); <ide> <del> ['@test Route silently fails when cleaning an outlet from an inactive view'](assert) { <del> assert.expect(1); // handleURL <add> return this.visit('/').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> rootElement.querySelector('.do-foo').click(); <add> rootElement.querySelector('.do-bar-with-arg').click(); <add> rootElement.querySelector('.do-baz').click(); <add> }); <add> } <ide> <del> this.addTemplate('application', '{{outlet}}'); <del> this.addTemplate('posts', "{{outlet 'modal'}}"); <del> this.addTemplate('modal', 'A Yo.'); <add> ['@test transitionTo returns Transition when passed a route name'](assert) { <add> assert.expect(1); <ide> <ide> this.router.map(function() { <del> this.route('posts'); <add> this.route('root', { path: '/' }); <add> this.route('bar'); <ide> }); <ide> <del> this.add( <del> 'route:posts', <del> Route.extend({ <del> actions: { <del> hideSelf() { <del> this.disconnectOutlet({ <del> outlet: 'main', <del> parentView: 'application', <del> }); <del> }, <del> showModal() { <del> this.render('modal', { into: 'posts', outlet: 'modal' }); <del> }, <del> hideModal() { <del> this.disconnectOutlet({ outlet: 'modal', parentView: 'posts' }); <del> }, <del> }, <del> }) <del> ); <del> <del> return this.visit('/posts').then(() => { <del> assert.ok(true, '/posts has been handled'); <add> return this.visit('/').then(() => { <ide> let router = this.applicationInstance.lookup('router:main'); <del> run(() => router.send('showModal')); <del> run(() => router.send('hideSelf')); <del> run(() => router.send('hideModal')); <add> let transition = run(() => router.transitionTo('bar')); <add> assert.equal(transition instanceof Transition, true); <ide> }); <ide> } <ide> <del> ['@test Router `willTransition` hook passes in cancellable transition'](assert) { <del> assert.expect(8); <del> this.router.reopen({ <del> willTransition(_, _2, transition) { <del> assert.ok(true, 'willTransition was called'); <del> if (transition.intent.url !== '/') { <del> transition.abort(); <del> } <del> }, <del> }); <add> ['@test transitionTo returns Transition when passed a url'](assert) { <add> assert.expect(1); <ide> <ide> this.router.map(function() { <del> this.route('nork'); <del> this.route('about'); <add> this.route('root', { path: '/' }); <add> this.route('bar', function() { <add> this.route('baz'); <add> }); <ide> }); <ide> <del> this.add( <del> 'route:loading', <del> Route.extend({ <del> activate() { <del> assert.ok(false, 'LoadingRoute was not entered'); <del> }, <del> }) <del> ); <del> <del> this.add( <del> 'route:nork', <del> Route.extend({ <del> activate() { <del> assert.ok(false, 'NorkRoute was not entered'); <del> }, <del> }) <del> ); <del> <del> this.add( <del> 'route:about', <del> Route.extend({ <del> activate() { <del> assert.ok(false, 'AboutRoute was not entered'); <del> }, <del> }) <del> ); <del> <del> let deprecation = /You attempted to override the "willTransition" method which is deprecated\./; <del> <del> return expectDeprecationAsync(() => { <del> return this.visit('/').then(() => { <del> this.handleURLAborts(assert, '/nork', deprecation); <del> this.handleURLAborts(assert, '/about', deprecation); <del> }); <del> }, deprecation); <del> } <del> <del> ['@test Aborting/redirecting the transition in `willTransition` prevents LoadingRoute from being entered']( <del> assert <del> ) { <del> assert.expect(5); <del> <del> this.router.map(function() { <del> this.route('index'); <del> this.route('nork'); <del> this.route('about'); <del> }); <del> <del> let redirect = false; <del> <del> this.add( <del> 'route:index', <del> Route.extend({ <del> actions: { <del> willTransition(transition) { <del> assert.ok(true, 'willTransition was called'); <del> if (redirect) { <del> // router.js won't refire `willTransition` for this redirect <del> this.transitionTo('about'); <del> } else { <del> transition.abort(); <del> } <del> }, <del> }, <del> }) <del> ); <del> <del> let deferred = null; <del> <del> this.add( <del> 'route:loading', <del> Route.extend({ <del> activate() { <del> assert.ok(deferred, 'LoadingRoute should be entered at this time'); <del> }, <del> deactivate() { <del> assert.ok(true, 'LoadingRoute was exited'); <del> }, <del> }) <del> ); <del> <del> this.add( <del> 'route:nork', <del> Route.extend({ <del> activate() { <del> assert.ok(true, 'NorkRoute was entered'); <del> }, <del> }) <del> ); <del> <del> this.add( <del> 'route:about', <del> Route.extend({ <del> activate() { <del> assert.ok(true, 'AboutRoute was entered'); <del> }, <del> model() { <del> if (deferred) { <del> return deferred.promise; <del> } <del> }, <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> let router = this.applicationInstance.lookup('router:main'); <del> // Attempted transitions out of index should abort. <del> run(router, 'transitionTo', 'nork'); <del> run(router, 'handleURL', '/nork'); <del> <del> // Attempted transitions out of index should redirect to about <del> redirect = true; <del> run(router, 'transitionTo', 'nork'); <del> run(router, 'transitionTo', 'index'); <del> <del> // Redirected transitions out of index to a route with a <del> // promise model should pause the transition and <del> // activate LoadingRoute <del> deferred = RSVP.defer(); <del> run(router, 'transitionTo', 'nork'); <del> run(deferred.resolve); <del> }); <del> } <del> <del> async ['@test `didTransition` event fires on the router'](assert) { <del> assert.expect(3); <del> <del> this.router.map(function() { <del> this.route('nork'); <del> }); <del> <del> await this.visit('/'); <del> <del> let router = this.applicationInstance.lookup('router:main'); <del> router.one('didTransition', function() { <del> assert.ok(true, 'didTransition fired on initial routing'); <del> }); <del> <del> await this.visit('/'); <del> <del> router.one('didTransition', function() { <del> assert.ok(true, 'didTransition fired on the router'); <del> assert.equal( <del> router.get('url'), <del> '/nork', <del> 'The url property is updated by the time didTransition fires' <del> ); <del> }); <del> <del> await this.visit('/nork'); <del> } <del> <del> ['@test `activate` event fires on the route'](assert) { <del> assert.expect(2); <del> <del> let eventFired = 0; <del> <del> this.router.map(function() { <del> this.route('nork'); <del> }); <del> <del> this.add( <del> 'route:nork', <del> Route.extend({ <del> init() { <del> this._super(...arguments); <del> <del> this.on('activate', function() { <del> assert.equal(++eventFired, 1, 'activate event is fired once'); <del> }); <del> }, <del> <del> activate() { <del> assert.ok(true, 'activate hook is called'); <del> }, <del> }) <del> ); <del> <del> return this.visit('/nork'); <del> } <del> <del> ['@test `deactivate` event fires on the route'](assert) { <del> assert.expect(2); <del> <del> let eventFired = 0; <del> <del> this.router.map(function() { <del> this.route('nork'); <del> this.route('dork'); <del> }); <del> <del> this.add( <del> 'route:nork', <del> Route.extend({ <del> init() { <del> this._super(...arguments); <del> <del> this.on('deactivate', function() { <del> assert.equal(++eventFired, 1, 'deactivate event is fired once'); <del> }); <del> }, <del> <del> deactivate() { <del> assert.ok(true, 'deactivate hook is called'); <del> }, <del> }) <del> ); <del> <del> return this.visit('/nork').then(() => this.visit('/dork')); <del> } <del> <del> ['@test Actions can be handled by inherited action handlers'](assert) { <del> assert.expect(4); <del> <del> let SuperRoute = Route.extend({ <del> actions: { <del> foo() { <del> assert.ok(true, 'foo'); <del> }, <del> bar(msg) { <del> assert.equal(msg, 'HELLO'); <del> }, <del> }, <del> }); <del> <del> let RouteMixin = Mixin.create({ <del> actions: { <del> bar(msg) { <del> assert.equal(msg, 'HELLO'); <del> this._super(msg); <del> }, <del> }, <del> }); <del> <del> this.add( <del> 'route:home', <del> SuperRoute.extend(RouteMixin, { <del> actions: { <del> baz() { <del> assert.ok(true, 'baz'); <del> }, <del> }, <del> }) <del> ); <del> <del> this.addTemplate( <del> 'home', <del> ` <del> <a class="do-foo" {{action "foo"}}>Do foo</a> <del> <a class="do-bar-with-arg" {{action "bar" "HELLO"}}>Do bar with arg</a> <del> <a class="do-baz" {{action "baz"}}>Do bar</a> <del> ` <del> ); <del> <del> return this.visit('/').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> rootElement.querySelector('.do-foo').click(); <del> rootElement.querySelector('.do-bar-with-arg').click(); <del> rootElement.querySelector('.do-baz').click(); <del> }); <del> } <del> <del> ['@test transitionTo returns Transition when passed a route name'](assert) { <del> assert.expect(1); <del> <del> this.router.map(function() { <del> this.route('root', { path: '/' }); <del> this.route('bar'); <del> }); <del> <del> return this.visit('/').then(() => { <del> let router = this.applicationInstance.lookup('router:main'); <del> let transition = run(() => router.transitionTo('bar')); <del> assert.equal(transition instanceof Transition, true); <del> }); <del> } <del> <del> ['@test transitionTo returns Transition when passed a url'](assert) { <del> assert.expect(1); <del> <del> this.router.map(function() { <del> this.route('root', { path: '/' }); <del> this.route('bar', function() { <del> this.route('baz'); <del> }); <del> }); <del> <del> return this.visit('/').then(() => { <del> let router = this.applicationInstance.lookup('router:main'); <del> let transition = run(() => router.transitionTo('/bar/baz')); <del> assert.equal(transition instanceof Transition, true); <del> }); <del> } <del> <del> ['@test currentRouteName is a property installed on ApplicationController that can be used in transitionTo']( <del> assert <del> ) { <del> assert.expect(36); <del> <del> this.router.map(function() { <del> this.route('index', { path: '/' }); <del> this.route('be', function() { <del> this.route('excellent', { resetNamespace: true }, function() { <del> this.route('to', { resetNamespace: true }, function() { <del> this.route('each', { resetNamespace: true }, function() { <del> this.route('other'); <del> }); <del> }); <del> }); <del> }); <del> }); <del> <del> return this.visit('/').then(() => { <del> let appController = this.applicationInstance.lookup('controller:application'); <del> let router = this.applicationInstance.lookup('router:main'); <del> <del> function transitionAndCheck(path, expectedPath, expectedRouteName) { <del> if (path) { <del> run(router, 'transitionTo', path); <del> } <del> expectDeprecation(() => { <del> assert.equal(appController.get('currentPath'), expectedPath); <del> assert.equal(appController.get('currentRouteName'), expectedRouteName); <del> }, 'Accessing `currentPath` on `controller:application` is deprecated, use the `currentPath` property on `service:router` instead.'); <del> } <del> <del> transitionAndCheck(null, 'index', 'index'); <del> transitionAndCheck('/be', 'be.index', 'be.index'); <del> transitionAndCheck('/be/excellent', 'be.excellent.index', 'excellent.index'); <del> transitionAndCheck('/be/excellent/to', 'be.excellent.to.index', 'to.index'); <del> transitionAndCheck('/be/excellent/to/each', 'be.excellent.to.each.index', 'each.index'); <del> transitionAndCheck( <del> '/be/excellent/to/each/other', <del> 'be.excellent.to.each.other', <del> 'each.other' <del> ); <del> <del> transitionAndCheck('index', 'index', 'index'); <del> transitionAndCheck('be', 'be.index', 'be.index'); <del> transitionAndCheck('excellent', 'be.excellent.index', 'excellent.index'); <del> transitionAndCheck('to.index', 'be.excellent.to.index', 'to.index'); <del> transitionAndCheck('each', 'be.excellent.to.each.index', 'each.index'); <del> transitionAndCheck('each.other', 'be.excellent.to.each.other', 'each.other'); <del> }); <del> } <del> <del> ['@test Specifying non-existent controller name in route#render throws'](assert) { <del> assert.expect(1); <del> <del> this.router.map(function() { <del> this.route('home', { path: '/' }); <del> }); <del> <del> this.add( <del> 'route:home', <del> Route.extend({ <del> renderTemplate() { <del> expectAssertion(() => { <del> this.render('homepage', { <del> controller: 'stefanpenneristhemanforme', <del> }); <del> }, "You passed `controller: 'stefanpenneristhemanforme'` into the `render` method, but no such controller could be found."); <del> }, <del> }) <del> ); <del> <del> return this.visit('/'); <del> } <del> <del> ["@test Redirecting with null model doesn't error out"](assert) { <del> this.router.map(function() { <del> this.route('home', { path: '/' }); <del> this.route('about', { path: '/about/:hurhurhur' }); <del> }); <del> <del> this.add( <del> 'route:about', <del> Route.extend({ <del> serialize: function(model) { <del> if (model === null) { <del> return { hurhurhur: 'TreeklesMcGeekles' }; <del> } <del> }, <del> }) <del> ); <del> <del> this.add( <del> 'route:home', <del> Route.extend({ <del> beforeModel() { <del> this.transitionTo('about', null); <del> }, <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> let router = this.applicationInstance.lookup('router:main'); <del> assert.equal(router.get('location.path'), '/about/TreeklesMcGeekles'); <del> }); <del> } <del> <del> async ['@test rejecting the model hooks promise with a non-error prints the `message` property']( <del> assert <del> ) { <del> assert.expect(5); <del> <del> let rejectedMessage = 'OMG!! SOOOOOO BAD!!!!'; <del> let rejectedStack = 'Yeah, buddy: stack gets printed too.'; <del> <del> this.router.map(function() { <del> this.route('yippie', { path: '/' }); <del> }); <del> <del> console.error = function(initialMessage, errorMessage, errorStack) { <del> assert.equal( <del> initialMessage, <del> 'Error while processing route: yippie', <del> 'a message with the current route name is printed' <del> ); <del> assert.equal( <del> errorMessage, <del> rejectedMessage, <del> "the rejected reason's message property is logged" <del> ); <del> assert.equal(errorStack, rejectedStack, "the rejected reason's stack property is logged"); <del> }; <del> <del> this.add( <del> 'route:yippie', <del> Route.extend({ <del> model() { <del> return RSVP.reject({ <del> message: rejectedMessage, <del> stack: rejectedStack, <del> }); <del> }, <del> }) <del> ); <del> <del> await assert.rejects( <del> this.visit('/'), <del> function(err) { <del> assert.equal(err.message, rejectedMessage); <del> return true; <del> }, <del> 'expected an exception' <del> ); <del> } <del> <del> async ['@test rejecting the model hooks promise with an error with `errorThrown` property prints `errorThrown.message` property']( <del> assert <del> ) { <del> assert.expect(5); <del> let rejectedMessage = 'OMG!! SOOOOOO BAD!!!!'; <del> let rejectedStack = 'Yeah, buddy: stack gets printed too.'; <del> <del> this.router.map(function() { <del> this.route('yippie', { path: '/' }); <del> }); <del> <del> console.error = function(initialMessage, errorMessage, errorStack) { <del> assert.equal( <del> initialMessage, <del> 'Error while processing route: yippie', <del> 'a message with the current route name is printed' <del> ); <del> assert.equal( <del> errorMessage, <del> rejectedMessage, <del> "the rejected reason's message property is logged" <del> ); <del> assert.equal(errorStack, rejectedStack, "the rejected reason's stack property is logged"); <del> }; <del> <del> this.add( <del> 'route:yippie', <del> Route.extend({ <del> model() { <del> return RSVP.reject({ <del> errorThrown: { message: rejectedMessage, stack: rejectedStack }, <del> }); <del> }, <del> }) <del> ); <del> <del> await assert.rejects( <del> this.visit('/'), <del> function({ errorThrown: err }) { <del> assert.equal(err.message, rejectedMessage); <del> return true; <del> }, <del> 'expected an exception' <del> ); <del> } <del> <del> async ['@test rejecting the model hooks promise with no reason still logs error'](assert) { <del> assert.expect(2); <del> this.router.map(function() { <del> this.route('wowzers', { path: '/' }); <del> }); <del> <del> console.error = function(initialMessage) { <del> assert.equal( <del> initialMessage, <del> 'Error while processing route: wowzers', <del> 'a message with the current route name is printed' <del> ); <del> }; <del> <del> this.add( <del> 'route:wowzers', <del> Route.extend({ <del> model() { <del> return RSVP.reject(); <del> }, <del> }) <del> ); <del> <del> await assert.rejects(this.visit('/')); <del> } <del> <del> async ['@test rejecting the model hooks promise with a string shows a good error'](assert) { <del> assert.expect(3); <del> let rejectedMessage = 'Supercalifragilisticexpialidocious'; <del> <del> this.router.map(function() { <del> this.route('yondo', { path: '/' }); <del> }); <del> <del> console.error = function(initialMessage, errorMessage) { <del> assert.equal( <del> initialMessage, <del> 'Error while processing route: yondo', <del> 'a message with the current route name is printed' <del> ); <del> assert.equal( <del> errorMessage, <del> rejectedMessage, <del> "the rejected reason's message property is logged" <del> ); <del> }; <del> <del> this.add( <del> 'route:yondo', <del> Route.extend({ <del> model() { <del> return RSVP.reject(rejectedMessage); <del> }, <del> }) <del> ); <del> <del> await assert.rejects(this.visit('/'), new RegExp(rejectedMessage), 'expected an exception'); <del> } <del> <del> ["@test willLeave, willChangeContext, willChangeModel actions don't fire unless feature flag enabled"]( <del> assert <del> ) { <del> assert.expect(1); <del> <del> this.router.map(function() { <del> this.route('about'); <del> }); <del> <del> function shouldNotFire() { <del> assert.ok(false, "this action shouldn't have been received"); <del> } <del> <del> this.add( <del> 'route:index', <del> Route.extend({ <del> actions: { <del> willChangeModel: shouldNotFire, <del> willChangeContext: shouldNotFire, <del> willLeave: shouldNotFire, <del> }, <del> }) <del> ); <del> <del> this.add( <del> 'route:about', <del> Route.extend({ <del> setupController() { <del> assert.ok(true, 'about route was entered'); <del> }, <del> }) <del> ); <del> <del> return this.visit('/about'); <del> } <del> <del> async ['@test Errors in transitionTo within redirect hook are logged'](assert) { <del> assert.expect(4); <del> let actual = []; <del> <del> this.router.map(function() { <del> this.route('yondo', { path: '/' }); <del> this.route('stink-bomb'); <del> }); <del> <del> this.add( <del> 'route:yondo', <del> Route.extend({ <del> redirect() { <del> this.transitionTo('stink-bomb', { something: 'goes boom' }); <del> }, <del> }) <del> ); <del> <del> console.error = function() { <del> // push the arguments onto an array so we can detect if the error gets logged twice <del> actual.push(arguments); <del> }; <del> <del> await assert.rejects(this.visit('/'), /More context objects were passed/); <del> <del> assert.equal(actual.length, 1, 'the error is only logged once'); <del> assert.equal(actual[0][0], 'Error while processing route: yondo', 'source route is printed'); <del> assert.ok( <del> actual[0][1].match( <del> /More context objects were passed than there are dynamic segments for the route: stink-bomb/ <del> ), <del> 'the error is printed' <del> ); <del> } <del> <del> ['@test Errors in transition show error template if available'](assert) { <del> this.addTemplate('error', "<div id='error'>Error!</div>"); <del> <del> this.router.map(function() { <del> this.route('yondo', { path: '/' }); <del> this.route('stink-bomb'); <del> }); <del> <del> this.add( <del> 'route:yondo', <del> Route.extend({ <del> redirect() { <del> this.transitionTo('stink-bomb', { something: 'goes boom' }); <del> }, <del> }) <del> ); <del> console.error = () => {}; <del> <ide> return this.visit('/').then(() => { <del> let rootElement = document.querySelector('#qunit-fixture'); <del> assert.equal( <del> rootElement.querySelectorAll('#error').length, <del> 1, <del> 'Error template was rendered.' <del> ); <add> let router = this.applicationInstance.lookup('router:main'); <add> let transition = run(() => router.transitionTo('/bar/baz')); <add> assert.equal(transition instanceof Transition, true); <ide> }); <ide> } <ide> <del> ['@test Route#resetController gets fired when changing models and exiting routes'](assert) { <del> assert.expect(4); <add> ['@test currentRouteName is a property installed on ApplicationController that can be used in transitionTo']( <add> assert <add> ) { <add> assert.expect(36); <ide> <ide> this.router.map(function() { <del> this.route('a', function() { <del> this.route('b', { path: '/b/:id', resetNamespace: true }, function() {}); <del> this.route('c', { path: '/c/:id', resetNamespace: true }, function() {}); <add> this.route('index', { path: '/' }); <add> this.route('be', function() { <add> this.route('excellent', { resetNamespace: true }, function() { <add> this.route('to', { resetNamespace: true }, function() { <add> this.route('each', { resetNamespace: true }, function() { <add> this.route('other'); <add> }); <add> }); <add> }); <ide> }); <del> this.route('out'); <ide> }); <ide> <del> let calls = []; <del> <del> let SpyRoute = Route.extend({ <del> setupController(/* controller, model, transition */) { <del> calls.push(['setup', this.routeName]); <del> }, <add> return this.visit('/').then(() => { <add> let appController = this.applicationInstance.lookup('controller:application'); <add> let router = this.applicationInstance.lookup('router:main'); <ide> <del> resetController(/* controller */) { <del> calls.push(['reset', this.routeName]); <del> }, <del> }); <add> function transitionAndCheck(path, expectedPath, expectedRouteName) { <add> if (path) { <add> run(router, 'transitionTo', path); <add> } <add> expectDeprecation(() => { <add> assert.equal(appController.get('currentPath'), expectedPath); <add> assert.equal(appController.get('currentRouteName'), expectedRouteName); <add> }, 'Accessing `currentPath` on `controller:application` is deprecated, use the `currentPath` property on `service:router` instead.'); <add> } <ide> <del> this.add('route:a', SpyRoute.extend()); <del> this.add('route:b', SpyRoute.extend()); <del> this.add('route:c', SpyRoute.extend()); <del> this.add('route:out', SpyRoute.extend()); <add> transitionAndCheck(null, 'index', 'index'); <add> transitionAndCheck('/be', 'be.index', 'be.index'); <add> transitionAndCheck('/be/excellent', 'be.excellent.index', 'excellent.index'); <add> transitionAndCheck('/be/excellent/to', 'be.excellent.to.index', 'to.index'); <add> transitionAndCheck('/be/excellent/to/each', 'be.excellent.to.each.index', 'each.index'); <add> transitionAndCheck( <add> '/be/excellent/to/each/other', <add> 'be.excellent.to.each.other', <add> 'each.other' <add> ); <ide> <del> let router; <del> return this.visit('/') <del> .then(() => { <del> router = this.applicationInstance.lookup('router:main'); <del> assert.deepEqual(calls, []); <del> return run(router, 'transitionTo', 'b', 'b-1'); <del> }) <del> .then(() => { <del> assert.deepEqual(calls, [['setup', 'a'], ['setup', 'b']]); <del> calls.length = 0; <del> return run(router, 'transitionTo', 'c', 'c-1'); <del> }) <del> .then(() => { <del> assert.deepEqual(calls, [['reset', 'b'], ['setup', 'c']]); <del> calls.length = 0; <del> return run(router, 'transitionTo', 'out'); <del> }) <del> .then(() => { <del> assert.deepEqual(calls, [['reset', 'c'], ['reset', 'a'], ['setup', 'out']]); <del> }); <add> transitionAndCheck('index', 'index', 'index'); <add> transitionAndCheck('be', 'be.index', 'be.index'); <add> transitionAndCheck('excellent', 'be.excellent.index', 'excellent.index'); <add> transitionAndCheck('to.index', 'be.excellent.to.index', 'to.index'); <add> transitionAndCheck('each', 'be.excellent.to.each.index', 'each.index'); <add> transitionAndCheck('each.other', 'be.excellent.to.each.other', 'each.other'); <add> }); <ide> } <ide> <del> async ['@test Exception during initialization of non-initial route is not swallowed'](assert) { <add> ["@test Redirecting with null model doesn't error out"](assert) { <ide> this.router.map(function() { <del> this.route('boom'); <add> this.route('home', { path: '/' }); <add> this.route('about', { path: '/about/:hurhurhur' }); <ide> }); <add> <ide> this.add( <del> 'route:boom', <add> 'route:about', <ide> Route.extend({ <del> init() { <del> throw new Error('boom!'); <add> serialize: function(model) { <add> if (model === null) { <add> return { hurhurhur: 'TreeklesMcGeekles' }; <add> } <ide> }, <ide> }) <ide> ); <ide> <del> await assert.rejects(this.visit('/boom'), /\bboom\b/); <del> } <del> <del> async ['@test Exception during initialization of initial route is not swallowed'](assert) { <del> this.router.map(function() { <del> this.route('boom', { path: '/' }); <del> }); <ide> this.add( <del> 'route:boom', <add> 'route:home', <ide> Route.extend({ <del> init() { <del> throw new Error('boom!'); <add> beforeModel() { <add> this.transitionTo('about', null); <ide> }, <ide> }) <ide> ); <ide> <del> await assert.rejects(this.visit('/'), /\bboom\b/); <del> } <del> <del> ['@test {{outlet}} works when created after initial render'](assert) { <del> this.addTemplate('sample', 'Hi{{#if showTheThing}}{{outlet}}{{/if}}Bye'); <del> this.addTemplate('sample.inner', 'Yay'); <del> this.addTemplate('sample.inner2', 'Boo'); <del> this.router.map(function() { <del> this.route('sample', { path: '/' }, function() { <del> this.route('inner', { path: '/' }); <del> this.route('inner2', { path: '/2' }); <del> }); <add> return this.visit('/').then(() => { <add> let router = this.applicationInstance.lookup('router:main'); <add> assert.equal(router.get('location.path'), '/about/TreeklesMcGeekles'); <ide> }); <add> } <ide> <del> let rootElement; <del> return this.visit('/') <del> .then(() => { <del> rootElement = document.getElementById('qunit-fixture'); <del> assert.equal(rootElement.textContent.trim(), 'HiBye', 'initial render'); <del> <del> run(() => this.applicationInstance.lookup('controller:sample').set('showTheThing', true)); <add> async ['@test rejecting the model hooks promise with a non-error prints the `message` property']( <add> assert <add> ) { <add> assert.expect(5); <ide> <del> assert.equal(rootElement.textContent.trim(), 'HiYayBye', 'second render'); <del> return this.visit('/2'); <del> }) <del> .then(() => { <del> assert.equal(rootElement.textContent.trim(), 'HiBooBye', 'third render'); <del> }); <del> } <add> let rejectedMessage = 'OMG!! SOOOOOO BAD!!!!'; <add> let rejectedStack = 'Yeah, buddy: stack gets printed too.'; <ide> <del> ['@test Can render into a named outlet at the top level'](assert) { <del> this.addTemplate('application', 'A-{{outlet}}-B-{{outlet "other"}}-C'); <del> this.addTemplate('modal', 'Hello world'); <del> this.addTemplate('index', 'The index'); <ide> this.router.map(function() { <del> this.route('index', { path: '/' }); <add> this.route('yippie', { path: '/' }); <ide> }); <add> <add> console.error = function(initialMessage, errorMessage, errorStack) { <add> assert.equal( <add> initialMessage, <add> 'Error while processing route: yippie', <add> 'a message with the current route name is printed' <add> ); <add> assert.equal( <add> errorMessage, <add> rejectedMessage, <add> "the rejected reason's message property is logged" <add> ); <add> assert.equal(errorStack, rejectedStack, "the rejected reason's stack property is logged"); <add> }; <add> <ide> this.add( <del> 'route:application', <add> 'route:yippie', <ide> Route.extend({ <del> renderTemplate() { <del> this.render(); <del> this.render('modal', { <del> into: 'application', <del> outlet: 'other', <add> model() { <add> return RSVP.reject({ <add> message: rejectedMessage, <add> stack: rejectedStack, <ide> }); <ide> }, <ide> }) <ide> ); <ide> <del> return this.visit('/').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> rootElement.textContent.trim(), <del> 'A-The index-B-Hello world-C', <del> 'initial render' <del> ); <del> }); <add> await assert.rejects( <add> this.visit('/'), <add> function(err) { <add> assert.equal(err.message, rejectedMessage); <add> return true; <add> }, <add> 'expected an exception' <add> ); <ide> } <ide> <del> ['@test Can disconnect a named outlet at the top level'](assert) { <del> this.addTemplate('application', 'A-{{outlet}}-B-{{outlet "other"}}-C'); <del> this.addTemplate('modal', 'Hello world'); <del> this.addTemplate('index', 'The index'); <add> async ['@test rejecting the model hooks promise with an error with `errorThrown` property prints `errorThrown.message` property']( <add> assert <add> ) { <add> assert.expect(5); <add> let rejectedMessage = 'OMG!! SOOOOOO BAD!!!!'; <add> let rejectedStack = 'Yeah, buddy: stack gets printed too.'; <add> <ide> this.router.map(function() { <del> this.route('index', { path: '/' }); <add> this.route('yippie', { path: '/' }); <ide> }); <add> <add> console.error = function(initialMessage, errorMessage, errorStack) { <add> assert.equal( <add> initialMessage, <add> 'Error while processing route: yippie', <add> 'a message with the current route name is printed' <add> ); <add> assert.equal( <add> errorMessage, <add> rejectedMessage, <add> "the rejected reason's message property is logged" <add> ); <add> assert.equal(errorStack, rejectedStack, "the rejected reason's stack property is logged"); <add> }; <add> <ide> this.add( <del> 'route:application', <add> 'route:yippie', <ide> Route.extend({ <del> renderTemplate() { <del> this.render(); <del> this.render('modal', { <del> into: 'application', <del> outlet: 'other', <add> model() { <add> return RSVP.reject({ <add> errorThrown: { message: rejectedMessage, stack: rejectedStack }, <ide> }); <ide> }, <del> actions: { <del> banish() { <del> this.disconnectOutlet({ <del> parentView: 'application', <del> outlet: 'other', <del> }); <del> }, <del> }, <ide> }) <ide> ); <ide> <del> return this.visit('/').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> rootElement.textContent.trim(), <del> 'A-The index-B-Hello world-C', <del> 'initial render' <del> ); <del> <del> run(this.applicationInstance.lookup('router:main'), 'send', 'banish'); <del> <del> assert.equal(rootElement.textContent.trim(), 'A-The index-B--C', 'second render'); <del> }); <add> await assert.rejects( <add> this.visit('/'), <add> function({ errorThrown: err }) { <add> assert.equal(err.message, rejectedMessage); <add> return true; <add> }, <add> 'expected an exception' <add> ); <ide> } <ide> <del> ['@test Can render into a named outlet at the top level, with empty main outlet'](assert) { <del> this.addTemplate('application', 'A-{{outlet}}-B-{{outlet "other"}}-C'); <del> this.addTemplate('modal', 'Hello world'); <del> <add> async ['@test rejecting the model hooks promise with no reason still logs error'](assert) { <add> assert.expect(2); <ide> this.router.map(function() { <del> this.route('hasNoTemplate', { path: '/' }); <add> this.route('wowzers', { path: '/' }); <ide> }); <ide> <add> console.error = function(initialMessage) { <add> assert.equal( <add> initialMessage, <add> 'Error while processing route: wowzers', <add> 'a message with the current route name is printed' <add> ); <add> }; <add> <ide> this.add( <del> 'route:application', <add> 'route:wowzers', <ide> Route.extend({ <del> renderTemplate() { <del> this.render(); <del> this.render('modal', { <del> into: 'application', <del> outlet: 'other', <del> }); <add> model() { <add> return RSVP.reject(); <ide> }, <ide> }) <ide> ); <ide> <del> return this.visit('/').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal(rootElement.textContent.trim(), 'A--B-Hello world-C', 'initial render'); <del> }); <add> await assert.rejects(this.visit('/')); <ide> } <ide> <del> ['@test Can render into a named outlet at the top level, later'](assert) { <del> this.addTemplate('application', 'A-{{outlet}}-B-{{outlet "other"}}-C'); <del> this.addTemplate('modal', 'Hello world'); <del> this.addTemplate('index', 'The index'); <add> async ['@test rejecting the model hooks promise with a string shows a good error'](assert) { <add> assert.expect(3); <add> let rejectedMessage = 'Supercalifragilisticexpialidocious'; <add> <ide> this.router.map(function() { <del> this.route('index', { path: '/' }); <add> this.route('yondo', { path: '/' }); <ide> }); <add> <add> console.error = function(initialMessage, errorMessage) { <add> assert.equal( <add> initialMessage, <add> 'Error while processing route: yondo', <add> 'a message with the current route name is printed' <add> ); <add> assert.equal( <add> errorMessage, <add> rejectedMessage, <add> "the rejected reason's message property is logged" <add> ); <add> }; <add> <ide> this.add( <del> 'route:application', <add> 'route:yondo', <ide> Route.extend({ <del> actions: { <del> launch() { <del> this.render('modal', { <del> into: 'application', <del> outlet: 'other', <del> }); <del> }, <add> model() { <add> return RSVP.reject(rejectedMessage); <ide> }, <ide> }) <ide> ); <ide> <del> return this.visit('/').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal(rootElement.textContent.trim(), 'A-The index-B--C', 'initial render'); <del> run(this.applicationInstance.lookup('router:main'), 'send', 'launch'); <del> assert.equal( <del> rootElement.textContent.trim(), <del> 'A-The index-B-Hello world-C', <del> 'second render' <del> ); <del> }); <add> await assert.rejects(this.visit('/'), new RegExp(rejectedMessage), 'expected an exception'); <ide> } <ide> <del> ["@test Can render routes with no 'main' outlet and their children"](assert) { <del> this.addTemplate('application', '<div id="application">{{outlet "app"}}</div>'); <del> this.addTemplate( <del> 'app', <del> '<div id="app-common">{{outlet "common"}}</div><div id="app-sub">{{outlet "sub"}}</div>' <del> ); <del> this.addTemplate('common', '<div id="common"></div>'); <del> this.addTemplate('sub', '<div id="sub"></div>'); <add> ["@test willLeave, willChangeContext, willChangeModel actions don't fire unless feature flag enabled"]( <add> assert <add> ) { <add> assert.expect(1); <ide> <ide> this.router.map(function() { <del> this.route('app', { path: '/app' }, function() { <del> this.route('sub', { path: '/sub', resetNamespace: true }); <del> }); <add> this.route('about'); <ide> }); <ide> <del> this.add( <del> 'route:app', <del> Route.extend({ <del> renderTemplate() { <del> this.render('app', { <del> outlet: 'app', <del> into: 'application', <del> }); <del> this.render('common', { <del> outlet: 'common', <del> into: 'app', <del> }); <del> }, <del> }) <del> ); <add> function shouldNotFire() { <add> assert.ok(false, "this action shouldn't have been received"); <add> } <ide> <ide> this.add( <del> 'route:sub', <add> 'route:index', <ide> Route.extend({ <del> renderTemplate() { <del> this.render('sub', { <del> outlet: 'sub', <del> into: 'app', <del> }); <add> actions: { <add> willChangeModel: shouldNotFire, <add> willChangeContext: shouldNotFire, <add> willLeave: shouldNotFire, <ide> }, <ide> }) <ide> ); <ide> <del> let rootElement; <del> return this.visit('/app') <del> .then(() => { <del> rootElement = document.getElementById('qunit-fixture'); <del> assert.equal( <del> rootElement.querySelectorAll('#app-common #common').length, <del> 1, <del> 'Finds common while viewing /app' <del> ); <del> return this.visit('/app/sub'); <del> }) <del> .then(() => { <del> assert.equal( <del> rootElement.querySelectorAll('#app-common #common').length, <del> 1, <del> 'Finds common while viewing /app/sub' <del> ); <del> assert.equal( <del> rootElement.querySelectorAll('#app-sub #sub').length, <del> 1, <del> 'Finds sub while viewing /app/sub' <del> ); <del> }); <del> } <del> <del> ['@test Tolerates stacked renders'](assert) { <del> this.addTemplate('application', '{{outlet}}{{outlet "modal"}}'); <del> this.addTemplate('index', 'hi'); <del> this.addTemplate('layer', 'layer'); <del> this.router.map(function() { <del> this.route('index', { path: '/' }); <del> }); <ide> this.add( <del> 'route:application', <add> 'route:about', <ide> Route.extend({ <del> actions: { <del> openLayer() { <del> this.render('layer', { <del> into: 'application', <del> outlet: 'modal', <del> }); <del> }, <del> close() { <del> this.disconnectOutlet({ <del> outlet: 'modal', <del> parentView: 'application', <del> }); <del> }, <add> setupController() { <add> assert.ok(true, 'about route was entered'); <ide> }, <ide> }) <ide> ); <ide> <del> return this.visit('/').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> let router = this.applicationInstance.lookup('router:main'); <del> assert.equal(rootElement.textContent.trim(), 'hi'); <del> run(router, 'send', 'openLayer'); <del> assert.equal(rootElement.textContent.trim(), 'hilayer'); <del> run(router, 'send', 'openLayer'); <del> assert.equal(rootElement.textContent.trim(), 'hilayer'); <del> run(router, 'send', 'close'); <del> assert.equal(rootElement.textContent.trim(), 'hi'); <del> }); <add> return this.visit('/about'); <ide> } <ide> <del> ['@test Renders child into parent with non-default template name'](assert) { <del> this.addTemplate('application', '<div class="a">{{outlet}}</div>'); <del> this.addTemplate('exports.root', '<div class="b">{{outlet}}</div>'); <del> this.addTemplate('exports.index', '<div class="c"></div>'); <add> async ['@test Errors in transitionTo within redirect hook are logged'](assert) { <add> assert.expect(4); <add> let actual = []; <ide> <ide> this.router.map(function() { <del> this.route('root', function() {}); <add> this.route('yondo', { path: '/' }); <add> this.route('stink-bomb'); <ide> }); <ide> <ide> this.add( <del> 'route:root', <add> 'route:yondo', <ide> Route.extend({ <del> renderTemplate() { <del> this.render('exports/root'); <add> redirect() { <add> this.transitionTo('stink-bomb', { something: 'goes boom' }); <ide> }, <ide> }) <ide> ); <ide> <del> this.add( <del> 'route:root.index', <del> Route.extend({ <del> renderTemplate() { <del> this.render('exports/index'); <del> }, <del> }) <del> ); <add> console.error = function() { <add> // push the arguments onto an array so we can detect if the error gets logged twice <add> actual.push(arguments); <add> }; <ide> <del> return this.visit('/root').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> assert.equal(rootElement.querySelectorAll('.a .b .c').length, 1); <del> }); <add> await assert.rejects(this.visit('/'), /More context objects were passed/); <add> <add> assert.equal(actual.length, 1, 'the error is only logged once'); <add> assert.equal(actual[0][0], 'Error while processing route: yondo', 'source route is printed'); <add> assert.ok( <add> actual[0][1].match( <add> /More context objects were passed than there are dynamic segments for the route: stink-bomb/ <add> ), <add> 'the error is printed' <add> ); <ide> } <ide> <del> ["@test Allows any route to disconnectOutlet another route's templates"](assert) { <del> this.addTemplate('application', '{{outlet}}{{outlet "modal"}}'); <del> this.addTemplate('index', 'hi'); <del> this.addTemplate('layer', 'layer'); <add> ['@test Errors in transition show error template if available'](assert) { <add> this.addTemplate('error', "<div id='error'>Error!</div>"); <add> <ide> this.router.map(function() { <del> this.route('index', { path: '/' }); <add> this.route('yondo', { path: '/' }); <add> this.route('stink-bomb'); <ide> }); <add> <ide> this.add( <del> 'route:application', <del> Route.extend({ <del> actions: { <del> openLayer() { <del> this.render('layer', { <del> into: 'application', <del> outlet: 'modal', <del> }); <del> }, <del> }, <del> }) <del> ); <del> this.add( <del> 'route:index', <add> 'route:yondo', <ide> Route.extend({ <del> actions: { <del> close() { <del> this.disconnectOutlet({ <del> parentView: 'application', <del> outlet: 'modal', <del> }); <del> }, <add> redirect() { <add> this.transitionTo('stink-bomb', { something: 'goes boom' }); <ide> }, <ide> }) <ide> ); <add> console.error = () => {}; <ide> <ide> return this.visit('/').then(() => { <del> let rootElement = document.getElementById('qunit-fixture'); <del> let router = this.applicationInstance.lookup('router:main'); <del> assert.equal(rootElement.textContent.trim(), 'hi'); <del> run(router, 'send', 'openLayer'); <del> assert.equal(rootElement.textContent.trim(), 'hilayer'); <del> run(router, 'send', 'close'); <del> assert.equal(rootElement.textContent.trim(), 'hi'); <add> let rootElement = document.querySelector('#qunit-fixture'); <add> assert.equal( <add> rootElement.querySelectorAll('#error').length, <add> 1, <add> 'Error template was rendered.' <add> ); <ide> }); <ide> } <ide> <del> ['@test Components inside an outlet have their didInsertElement hook invoked when the route is displayed']( <del> assert <del> ) { <del> this.addTemplate( <del> 'index', <del> '{{#if showFirst}}{{my-component}}{{else}}{{other-component}}{{/if}}' <del> ); <del> <del> let myComponentCounter = 0; <del> let otherComponentCounter = 0; <del> let indexController; <add> ['@test Route#resetController gets fired when changing models and exiting routes'](assert) { <add> assert.expect(4); <ide> <ide> this.router.map(function() { <del> this.route('index', { path: '/' }); <add> this.route('a', function() { <add> this.route('b', { path: '/b/:id', resetNamespace: true }, function() {}); <add> this.route('c', { path: '/c/:id', resetNamespace: true }, function() {}); <add> }); <add> this.route('out'); <ide> }); <ide> <del> this.add( <del> 'controller:index', <del> Controller.extend({ <del> showFirst: true, <add> let calls = []; <add> <add> let SpyRoute = Route.extend({ <add> setupController(/* controller, model, transition */) { <add> calls.push(['setup', this.routeName]); <add> }, <add> <add> resetController(/* controller */) { <add> calls.push(['reset', this.routeName]); <add> }, <add> }); <add> <add> this.add('route:a', SpyRoute.extend()); <add> this.add('route:b', SpyRoute.extend()); <add> this.add('route:c', SpyRoute.extend()); <add> this.add('route:out', SpyRoute.extend()); <add> <add> let router; <add> return this.visit('/') <add> .then(() => { <add> router = this.applicationInstance.lookup('router:main'); <add> assert.deepEqual(calls, []); <add> return run(router, 'transitionTo', 'b', 'b-1'); <ide> }) <del> ); <add> .then(() => { <add> assert.deepEqual(calls, [['setup', 'a'], ['setup', 'b']]); <add> calls.length = 0; <add> return run(router, 'transitionTo', 'c', 'c-1'); <add> }) <add> .then(() => { <add> assert.deepEqual(calls, [['reset', 'b'], ['setup', 'c']]); <add> calls.length = 0; <add> return run(router, 'transitionTo', 'out'); <add> }) <add> .then(() => { <add> assert.deepEqual(calls, [['reset', 'c'], ['reset', 'a'], ['setup', 'out']]); <add> }); <add> } <ide> <add> async ['@test Exception during initialization of non-initial route is not swallowed'](assert) { <add> this.router.map(function() { <add> this.route('boom'); <add> }); <ide> this.add( <del> 'route:index', <add> 'route:boom', <ide> Route.extend({ <del> setupController(controller) { <del> indexController = controller; <add> init() { <add> throw new Error('boom!'); <ide> }, <ide> }) <ide> ); <ide> <del> this.add( <del> 'component:my-component', <del> Component.extend({ <del> didInsertElement() { <del> myComponentCounter++; <del> }, <del> }) <del> ); <add> await assert.rejects(this.visit('/boom'), /\bboom\b/); <add> } <ide> <add> async ['@test Exception during initialization of initial route is not swallowed'](assert) { <add> this.router.map(function() { <add> this.route('boom', { path: '/' }); <add> }); <ide> this.add( <del> 'component:other-component', <del> Component.extend({ <del> didInsertElement() { <del> otherComponentCounter++; <add> 'route:boom', <add> Route.extend({ <add> init() { <add> throw new Error('boom!'); <ide> }, <ide> }) <ide> ); <ide> <del> return this.visit('/').then(() => { <del> assert.strictEqual( <del> myComponentCounter, <del> 1, <del> 'didInsertElement invoked on displayed component' <del> ); <del> assert.strictEqual( <del> otherComponentCounter, <del> 0, <del> 'didInsertElement not invoked on displayed component' <del> ); <del> <del> run(() => indexController.set('showFirst', false)); <del> <del> assert.strictEqual( <del> myComponentCounter, <del> 1, <del> 'didInsertElement not invoked on displayed component' <del> ); <del> assert.strictEqual( <del> otherComponentCounter, <del> 1, <del> 'didInsertElement invoked on displayed component' <del> ); <del> }); <add> await assert.rejects(this.visit('/'), /\bboom\b/); <ide> } <ide> <ide> async ['@test Doesnt swallow exception thrown from willTransition'](assert) { <ide> moduleFor( <ide> ); <ide> } <ide> <del> ['@test Exception if outlet name is undefined in render and disconnectOutlet']() { <del> this.add( <del> 'route:application', <del> Route.extend({ <del> actions: { <del> showModal() { <del> this.render({ <del> outlet: undefined, <del> parentView: 'application', <del> }); <del> }, <del> hideModal() { <del> this.disconnectOutlet({ <del> outlet: undefined, <del> parentView: 'application', <del> }); <del> }, <del> }, <del> }) <del> ); <del> <del> return this.visit('/').then(() => { <del> let router = this.applicationInstance.lookup('router:main'); <del> expectAssertion(() => { <del> run(() => router.send('showModal')); <del> }, /You passed undefined as the outlet name/); <del> <del> expectAssertion(() => { <del> run(() => router.send('hideModal')); <del> }, /You passed undefined as the outlet name/); <del> }); <del> } <del> <ide> ['@test Route serializers work for Engines'](assert) { <ide> assert.expect(2); <ide> <ide><path>packages/ember/tests/routing/model_loading_test.js <ide> import { Route } from '@ember/-internals/routing'; <ide> import Controller from '@ember/controller'; <ide> import { Object as EmberObject, A as emberA } from '@ember/-internals/runtime'; <del>import { <del> moduleFor, <del> ApplicationTestCase, <del> getTextOf, <del>} from 'internal-test-helpers'; <add>import { moduleFor, ApplicationTestCase, getTextOf } from 'internal-test-helpers'; <ide> import { run } from '@ember/runloop'; <ide> import { computed, set } from '@ember/-internals/metal'; <ide> <ide><path>packages/ember/tests/routing/template_rendering_test.js <add>/* eslint-disable no-console */ <add>import { Route } from '@ember/-internals/routing'; <add>import Controller from '@ember/controller'; <add>import { Object as EmberObject, A as emberA } from '@ember/-internals/runtime'; <add>import { moduleFor, ApplicationTestCase, getTextOf, runTask } from 'internal-test-helpers'; <add>import { run } from '@ember/runloop'; <add>import { Component } from '@ember/-internals/glimmer'; <add> <add>let originalConsoleError; <add> <add>moduleFor( <add> 'Route - template rendering', <add> class extends ApplicationTestCase { <add> constructor() { <add> super(...arguments); <add> this.addTemplate('home', '<h3 class="hours">Hours</h3>'); <add> this.addTemplate('camelot', '<section id="camelot"><h3>Is a silly place</h3></section>'); <add> this.addTemplate('homepage', '<h3 id="troll">Megatroll</h3><p>{{this.name}}</p>'); <add> <add> this.router.map(function() { <add> this.route('home', { path: '/' }); <add> }); <add> <add> originalConsoleError = console.error; <add> } <add> <add> teardown() { <add> super.teardown(); <add> console.error = originalConsoleError; <add> } <add> <add> handleURLAborts(assert, path, deprecated) { <add> run(() => { <add> let router = this.applicationInstance.lookup('router:main'); <add> let result; <add> <add> if (deprecated !== undefined) { <add> expectDeprecation(() => { <add> result = router.handleURL(path); <add> }); <add> } else { <add> result = router.handleURL(path); <add> } <add> <add> result.then( <add> function() { <add> assert.ok(false, 'url: `' + path + '` was NOT to be handled'); <add> }, <add> function(reason) { <add> assert.ok( <add> reason && reason.message === 'TransitionAborted', <add> 'url: `' + path + '` was to be aborted' <add> ); <add> } <add> ); <add> }); <add> } <add> <add> get currentPath() { <add> let currentPath; <add> expectDeprecation(() => { <add> currentPath = this.applicationInstance.lookup('controller:application').get('currentPath'); <add> }, 'Accessing `currentPath` on `controller:application` is deprecated, use the `currentPath` property on `service:router` instead.'); <add> return currentPath; <add> } <add> <add> async ['@test warn on URLs not included in the route set'](assert) { <add> await this.visit('/'); <add> <add> await assert.rejects(this.visit('/what-is-this-i-dont-even'), /\/what-is-this-i-dont-even/); <add> } <add> <add> [`@test The Homepage with explicit template name in renderTemplate`](assert) { <add> this.add( <add> 'route:home', <add> Route.extend({ <add> renderTemplate() { <add> this.render('homepage'); <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let text = this.$('#troll').text(); <add> assert.equal(text, 'Megatroll', 'the homepage template was rendered'); <add> }); <add> } <add> <add> async [`@test an alternate template will pull in an alternate controller`](assert) { <add> this.add( <add> 'route:home', <add> Route.extend({ <add> renderTemplate() { <add> this.render('homepage'); <add> }, <add> }) <add> ); <add> this.add( <add> 'controller:homepage', <add> Controller.extend({ <add> init() { <add> this._super(...arguments); <add> this.name = 'Comes from homepage'; <add> }, <add> }) <add> ); <add> <add> await this.visit('/'); <add> <add> assert.equal(this.$('p').text(), 'Comes from homepage', 'the homepage template was rendered'); <add> } <add> <add> async [`@test An alternate template will pull in an alternate controller instead of controllerName`]( <add> assert <add> ) { <add> this.add( <add> 'route:home', <add> Route.extend({ <add> controllerName: 'foo', <add> renderTemplate() { <add> this.render('homepage'); <add> }, <add> }) <add> ); <add> this.add( <add> 'controller:foo', <add> Controller.extend({ <add> init() { <add> this._super(...arguments); <add> this.name = 'Comes from foo'; <add> }, <add> }) <add> ); <add> this.add( <add> 'controller:homepage', <add> Controller.extend({ <add> init() { <add> this._super(...arguments); <add> this.name = 'Comes from homepage'; <add> }, <add> }) <add> ); <add> <add> await this.visit('/'); <add> <add> assert.equal(this.$('p').text(), 'Comes from homepage', 'the homepage template was rendered'); <add> } <add> <add> async [`@test The template will pull in an alternate controller via key/value`](assert) { <add> this.router.map(function() { <add> this.route('homepage', { path: '/' }); <add> }); <add> <add> this.add( <add> 'route:homepage', <add> Route.extend({ <add> renderTemplate() { <add> this.render({ controller: 'home' }); <add> }, <add> }) <add> ); <add> this.add( <add> 'controller:home', <add> Controller.extend({ <add> init() { <add> this._super(...arguments); <add> this.name = 'Comes from home.'; <add> }, <add> }) <add> ); <add> <add> await this.visit('/'); <add> <add> assert.equal( <add> this.$('p').text(), <add> 'Comes from home.', <add> 'the homepage template was rendered from data from the HomeController' <add> ); <add> } <add> <add> async [`@test The Homepage with explicit template name in renderTemplate and controller`]( <add> assert <add> ) { <add> this.add( <add> 'controller:home', <add> Controller.extend({ <add> init() { <add> this._super(...arguments); <add> this.name = 'YES I AM HOME'; <add> }, <add> }) <add> ); <add> this.add( <add> 'route:home', <add> Route.extend({ <add> renderTemplate() { <add> this.render('homepage'); <add> }, <add> }) <add> ); <add> <add> await this.visit('/'); <add> <add> assert.equal(this.$('p').text(), 'YES I AM HOME', 'The homepage template was rendered'); <add> } <add> <add> [`@feature(!EMBER_ROUTING_MODEL_ARG) Model passed via renderTemplate model is set as controller's model`]( <add> assert <add> ) { <add> this.addTemplate('bio', '<p>{{this.model.name}}</p>'); <add> this.add( <add> 'route:home', <add> Route.extend({ <add> renderTemplate() { <add> this.render('bio', { <add> model: { name: 'emberjs' }, <add> }); <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let text = this.$('p').text(); <add> <add> assert.equal(text, 'emberjs', `Passed model was set as controller's model`); <add> }); <add> } <add> <add> async [`@feature(EMBER_ROUTING_MODEL_ARG) Model passed via renderTemplate model is set as controller's model`]( <add> assert <add> ) { <add> this.addTemplate( <add> 'bio', <add> '<p>Model: {{@model.name}}</p><p>Controller: {{this.model.name}}</p>' <add> ); <add> this.add( <add> 'route:home', <add> Route.extend({ <add> renderTemplate() { <add> this.render('bio', { <add> model: { name: 'emberjs' }, <add> }); <add> }, <add> }) <add> ); <add> <add> await this.visit('/'); <add> <add> let text = this.$('p').text(); <add> <add> assert.ok( <add> text.indexOf('Model: emberjs') > -1, <add> 'Passed model was available as the `@model` argument' <add> ); <add> <add> assert.ok( <add> text.indexOf('Controller: emberjs') > -1, <add> "Passed model was set as controller's `model` property" <add> ); <add> } <add> <add> ['@test render uses templateName from route'](assert) { <add> this.addTemplate('the_real_home_template', '<p>THIS IS THE REAL HOME</p>'); <add> this.add( <add> 'route:home', <add> Route.extend({ <add> templateName: 'the_real_home_template', <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let text = this.$('p').text(); <add> <add> assert.equal(text, 'THIS IS THE REAL HOME', 'the homepage template was rendered'); <add> }); <add> } <add> <add> ['@test defining templateName allows other templates to be rendered'](assert) { <add> this.addTemplate('alert', `<div class='alert-box'>Invader!</div>`); <add> this.addTemplate('the_real_home_template', `<p>THIS IS THE REAL HOME</p>{{outlet 'alert'}}`); <add> this.add( <add> 'route:home', <add> Route.extend({ <add> templateName: 'the_real_home_template', <add> actions: { <add> showAlert() { <add> this.render('alert', { <add> into: 'home', <add> outlet: 'alert', <add> }); <add> }, <add> }, <add> }) <add> ); <add> <add> return this.visit('/') <add> .then(() => { <add> let text = this.$('p').text(); <add> assert.equal(text, 'THIS IS THE REAL HOME', 'the homepage template was rendered'); <add> <add> return runTask(() => this.appRouter.send('showAlert')); <add> }) <add> .then(() => { <add> let text = this.$('.alert-box').text(); <add> <add> assert.equal(text, 'Invader!', 'Template for alert was rendered into the outlet'); <add> }); <add> } <add> <add> ['@test templateName is still used when calling render with no name and options'](assert) { <add> this.addTemplate('alert', `<div class='alert-box'>Invader!</div>`); <add> this.addTemplate('home', `<p>THIS IS THE REAL HOME</p>{{outlet 'alert'}}`); <add> <add> this.add( <add> 'route:home', <add> Route.extend({ <add> templateName: 'alert', <add> renderTemplate() { <add> this.render({}); <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let text = this.$('.alert-box').text(); <add> <add> assert.equal(text, 'Invader!', 'default templateName was rendered into outlet'); <add> }); <add> } <add> <add> ['@test Generated names can be customized when providing routes with dot notation'](assert) { <add> assert.expect(4); <add> <add> this.addTemplate('index', '<div>Index</div>'); <add> this.addTemplate('application', "<h1>Home</h1><div class='main'>{{outlet}}</div>"); <add> this.addTemplate('foo', "<div class='middle'>{{outlet}}</div>"); <add> this.addTemplate('bar', "<div class='bottom'>{{outlet}}</div>"); <add> this.addTemplate('bar.baz', '<p>{{name}}Bottom!</p>'); <add> <add> this.router.map(function() { <add> this.route('foo', { path: '/top' }, function() { <add> this.route('bar', { path: '/middle', resetNamespace: true }, function() { <add> this.route('baz', { path: '/bottom' }); <add> }); <add> }); <add> }); <add> <add> this.add( <add> 'route:foo', <add> Route.extend({ <add> renderTemplate() { <add> assert.ok(true, 'FooBarRoute was called'); <add> return this._super(...arguments); <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'route:bar.baz', <add> Route.extend({ <add> renderTemplate() { <add> assert.ok(true, 'BarBazRoute was called'); <add> return this._super(...arguments); <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'controller:bar', <add> Controller.extend({ <add> name: 'Bar', <add> }) <add> ); <add> <add> this.add( <add> 'controller:bar.baz', <add> Controller.extend({ <add> name: 'BarBaz', <add> }) <add> ); <add> <add> return this.visit('/top/middle/bottom').then(() => { <add> assert.ok(true, '/top/middle/bottom has been handled'); <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> getTextOf(rootElement.querySelector('.main .middle .bottom p')), <add> 'BarBazBottom!', <add> 'The templates were rendered into their appropriate parents' <add> ); <add> }); <add> } <add> <add> ["@test Child routes render into their parent route's template by default"](assert) { <add> this.addTemplate('index', '<div>Index</div>'); <add> this.addTemplate('application', "<h1>Home</h1><div class='main'>{{outlet}}</div>"); <add> this.addTemplate('top', "<div class='middle'>{{outlet}}</div>"); <add> this.addTemplate('middle', "<div class='bottom'>{{outlet}}</div>"); <add> this.addTemplate('middle.bottom', '<p>Bottom!</p>'); <add> <add> this.router.map(function() { <add> this.route('top', function() { <add> this.route('middle', { resetNamespace: true }, function() { <add> this.route('bottom'); <add> }); <add> }); <add> }); <add> <add> return this.visit('/top/middle/bottom').then(() => { <add> assert.ok(true, '/top/middle/bottom has been handled'); <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> getTextOf(rootElement.querySelector('.main .middle .bottom p')), <add> 'Bottom!', <add> 'The templates were rendered into their appropriate parents' <add> ); <add> }); <add> } <add> <add> ['@test Child routes render into specified template'](assert) { <add> this.addTemplate('index', '<div>Index</div>'); <add> this.addTemplate('application', "<h1>Home</h1><div class='main'>{{outlet}}</div>"); <add> this.addTemplate('top', "<div class='middle'>{{outlet}}</div>"); <add> this.addTemplate('middle', "<div class='bottom'>{{outlet}}</div>"); <add> this.addTemplate('middle.bottom', '<p>Bottom!</p>'); <add> <add> this.router.map(function() { <add> this.route('top', function() { <add> this.route('middle', { resetNamespace: true }, function() { <add> this.route('bottom'); <add> }); <add> }); <add> }); <add> <add> this.add( <add> 'route:middle.bottom', <add> Route.extend({ <add> renderTemplate() { <add> this.render('middle/bottom', { into: 'top' }); <add> }, <add> }) <add> ); <add> <add> return this.visit('/top/middle/bottom').then(() => { <add> assert.ok(true, '/top/middle/bottom has been handled'); <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> rootElement.querySelectorAll('.main .middle .bottom p').length, <add> 0, <add> 'should not render into the middle template' <add> ); <add> assert.equal( <add> getTextOf(rootElement.querySelector('.main .middle > p')), <add> 'Bottom!', <add> 'The template was rendered into the top template' <add> ); <add> }); <add> } <add> <add> ['@test Rendering into specified template with slash notation'](assert) { <add> this.addTemplate('person.profile', 'profile {{outlet}}'); <add> this.addTemplate('person.details', 'details!'); <add> <add> this.router.map(function() { <add> this.route('home', { path: '/' }); <add> }); <add> <add> this.add( <add> 'route:home', <add> Route.extend({ <add> renderTemplate() { <add> this.render('person/profile'); <add> this.render('person/details', { into: 'person/profile' }); <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> rootElement.textContent.trim(), <add> 'profile details!', <add> 'The templates were rendered' <add> ); <add> }); <add> } <add> <add> ['@test Only use route rendered into main outlet for default into property on child'](assert) { <add> this.addTemplate('application', "{{outlet 'menu'}}{{outlet}}"); <add> this.addTemplate('posts', '{{outlet}}'); <add> this.addTemplate('posts.index', '<p class="posts-index">postsIndex</p>'); <add> this.addTemplate('posts.menu', '<div class="posts-menu">postsMenu</div>'); <add> <add> this.router.map(function() { <add> this.route('posts', function() {}); <add> }); <add> <add> this.add( <add> 'route:posts', <add> Route.extend({ <add> renderTemplate() { <add> this.render(); <add> this.render('posts/menu', { <add> into: 'application', <add> outlet: 'menu', <add> }); <add> }, <add> }) <add> ); <add> <add> return this.visit('/posts').then(() => { <add> assert.ok(true, '/posts has been handled'); <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-menu')), <add> 'postsMenu', <add> 'The posts/menu template was rendered' <add> ); <add> assert.equal( <add> getTextOf(rootElement.querySelector('p.posts-index')), <add> 'postsIndex', <add> 'The posts/index template was rendered' <add> ); <add> }); <add> } <add> <add> ['@test Application template does not duplicate when re-rendered'](assert) { <add> this.addTemplate('application', '<h3 class="render-once">I render once</h3>{{outlet}}'); <add> <add> this.router.map(function() { <add> this.route('posts'); <add> }); <add> <add> this.add( <add> 'route:application', <add> Route.extend({ <add> model() { <add> return emberA(); <add> }, <add> }) <add> ); <add> <add> return this.visit('/posts').then(() => { <add> assert.ok(true, '/posts has been handled'); <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal(getTextOf(rootElement.querySelector('h3.render-once')), 'I render once'); <add> }); <add> } <add> <add> ['@test Child routes should render inside the application template if the application template causes a redirect']( <add> assert <add> ) { <add> this.addTemplate('application', '<h3>App</h3> {{outlet}}'); <add> this.addTemplate('posts', 'posts'); <add> <add> this.router.map(function() { <add> this.route('posts'); <add> this.route('photos'); <add> }); <add> <add> this.add( <add> 'route:application', <add> Route.extend({ <add> afterModel() { <add> this.transitionTo('posts'); <add> }, <add> }) <add> ); <add> <add> return this.visit('/posts').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal(rootElement.textContent.trim(), 'App posts'); <add> }); <add> } <add> <add> ["@feature(!EMBER_ROUTING_MODEL_ARG) The template is not re-rendered when the route's context changes"]( <add> assert <add> ) { <add> this.router.map(function() { <add> this.route('page', { path: '/page/:name' }); <add> }); <add> <add> this.add( <add> 'route:page', <add> Route.extend({ <add> model(params) { <add> return EmberObject.create({ name: params.name }); <add> }, <add> }) <add> ); <add> <add> let insertionCount = 0; <add> this.add( <add> 'component:foo-bar', <add> Component.extend({ <add> didInsertElement() { <add> insertionCount += 1; <add> }, <add> }) <add> ); <add> <add> this.addTemplate('page', '<p>{{this.model.name}}{{foo-bar}}</p>'); <add> <add> let rootElement = document.getElementById('qunit-fixture'); <add> return this.visit('/page/first') <add> .then(() => { <add> assert.ok(true, '/page/first has been handled'); <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'first'); <add> assert.equal(insertionCount, 1); <add> return this.visit('/page/second'); <add> }) <add> .then(() => { <add> assert.ok(true, '/page/second has been handled'); <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'second'); <add> assert.equal(insertionCount, 1, 'view should have inserted only once'); <add> let router = this.applicationInstance.lookup('router:main'); <add> return run(() => router.transitionTo('page', EmberObject.create({ name: 'third' }))); <add> }) <add> .then(() => { <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'third'); <add> assert.equal(insertionCount, 1, 'view should still have inserted only once'); <add> }); <add> } <add> <add> async ["@feature(EMBER_ROUTING_MODEL_ARG) The template is not re-rendered when the route's model changes"]( <add> assert <add> ) { <add> this.router.map(function() { <add> this.route('page', { path: '/page/:name' }); <add> }); <add> <add> this.add( <add> 'route:page', <add> Route.extend({ <add> model(params) { <add> return EmberObject.create({ name: params.name }); <add> }, <add> }) <add> ); <add> <add> let insertionCount = 0; <add> this.add( <add> 'component:foo-bar', <add> Component.extend({ <add> didInsertElement() { <add> insertionCount += 1; <add> }, <add> }) <add> ); <add> <add> this.addTemplate('page', '<p>{{@model.name}}{{foo-bar}}</p>'); <add> <add> let rootElement = document.getElementById('qunit-fixture'); <add> <add> await this.visit('/page/first'); <add> <add> assert.ok(true, '/page/first has been handled'); <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'first'); <add> assert.equal(insertionCount, 1); <add> <add> await this.visit('/page/second'); <add> <add> assert.ok(true, '/page/second has been handled'); <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'second'); <add> assert.equal(insertionCount, 1, 'view should have inserted only once'); <add> let router = this.applicationInstance.lookup('router:main'); <add> <add> await run(() => router.transitionTo('page', EmberObject.create({ name: 'third' }))); <add> <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'third'); <add> assert.equal(insertionCount, 1, 'view should still have inserted only once'); <add> } <add> <add> ['@test The template is not re-rendered when two routes present the exact same template & controller']( <add> assert <add> ) { <add> this.router.map(function() { <add> this.route('first'); <add> this.route('second'); <add> this.route('third'); <add> this.route('fourth'); <add> }); <add> <add> // Note add a component to test insertion <add> <add> let insertionCount = 0; <add> this.add( <add> 'component:x-input', <add> Component.extend({ <add> didInsertElement() { <add> insertionCount += 1; <add> }, <add> }) <add> ); <add> <add> let SharedRoute = Route.extend({ <add> setupController() { <add> this.controllerFor('shared').set('message', 'This is the ' + this.routeName + ' message'); <add> }, <add> <add> renderTemplate() { <add> this.render('shared', { controller: 'shared' }); <add> }, <add> }); <add> <add> this.add('route:shared', SharedRoute); <add> this.add('route:first', SharedRoute.extend()); <add> this.add('route:second', SharedRoute.extend()); <add> this.add('route:third', SharedRoute.extend()); <add> this.add('route:fourth', SharedRoute.extend()); <add> <add> this.add('controller:shared', Controller.extend()); <add> <add> this.addTemplate('shared', '<p>{{message}}{{x-input}}</p>'); <add> <add> let rootElement = document.getElementById('qunit-fixture'); <add> return this.visit('/first') <add> .then(() => { <add> assert.ok(true, '/first has been handled'); <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'This is the first message'); <add> assert.equal(insertionCount, 1, 'expected one assertion'); <add> return this.visit('/second'); <add> }) <add> .then(() => { <add> assert.ok(true, '/second has been handled'); <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'This is the second message'); <add> assert.equal(insertionCount, 1, 'expected one assertion'); <add> return run(() => { <add> this.applicationInstance <add> .lookup('router:main') <add> .transitionTo('third') <add> .then( <add> function() { <add> assert.ok(true, 'expected transition'); <add> }, <add> function(reason) { <add> assert.ok(false, 'unexpected transition failure: ', QUnit.jsDump.parse(reason)); <add> } <add> ); <add> }); <add> }) <add> .then(() => { <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'This is the third message'); <add> assert.equal(insertionCount, 1, 'expected one assertion'); <add> return this.visit('fourth'); <add> }) <add> .then(() => { <add> assert.ok(true, '/fourth has been handled'); <add> assert.equal(insertionCount, 1, 'expected one assertion'); <add> assert.equal(getTextOf(rootElement.querySelector('p')), 'This is the fourth message'); <add> }); <add> } <add> <add> ['@test Route should tear down multiple outlets'](assert) { <add> this.addTemplate('application', "{{outlet 'menu'}}{{outlet}}{{outlet 'footer'}}"); <add> this.addTemplate('posts', '{{outlet}}'); <add> this.addTemplate('users', 'users'); <add> this.addTemplate('posts.index', '<p class="posts-index">postsIndex</p>'); <add> this.addTemplate('posts.menu', '<div class="posts-menu">postsMenu</div>'); <add> this.addTemplate('posts.footer', '<div class="posts-footer">postsFooter</div>'); <add> <add> this.router.map(function() { <add> this.route('posts', function() {}); <add> this.route('users', function() {}); <add> }); <add> <add> this.add( <add> 'route:posts', <add> Route.extend({ <add> renderTemplate() { <add> this.render('posts/menu', { <add> into: 'application', <add> outlet: 'menu', <add> }); <add> <add> this.render(); <add> <add> this.render('posts/footer', { <add> into: 'application', <add> outlet: 'footer', <add> }); <add> }, <add> }) <add> ); <add> <add> let rootElement = document.getElementById('qunit-fixture'); <add> return this.visit('/posts') <add> .then(() => { <add> assert.ok(true, '/posts has been handled'); <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-menu')), <add> 'postsMenu', <add> 'The posts/menu template was rendered' <add> ); <add> assert.equal( <add> getTextOf(rootElement.querySelector('p.posts-index')), <add> 'postsIndex', <add> 'The posts/index template was rendered' <add> ); <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-footer')), <add> 'postsFooter', <add> 'The posts/footer template was rendered' <add> ); <add> <add> return this.visit('/users'); <add> }) <add> .then(() => { <add> assert.ok(true, '/users has been handled'); <add> assert.equal( <add> rootElement.querySelector('div.posts-menu'), <add> null, <add> 'The posts/menu template was removed' <add> ); <add> assert.equal( <add> rootElement.querySelector('p.posts-index'), <add> null, <add> 'The posts/index template was removed' <add> ); <add> assert.equal( <add> rootElement.querySelector('div.posts-footer'), <add> null, <add> 'The posts/footer template was removed' <add> ); <add> }); <add> } <add> <add> ['@test Route supports clearing outlet explicitly'](assert) { <add> this.addTemplate('application', "{{outlet}}{{outlet 'modal'}}"); <add> this.addTemplate('posts', '{{outlet}}'); <add> this.addTemplate('users', 'users'); <add> this.addTemplate('posts.index', '<div class="posts-index">postsIndex {{outlet}}</div>'); <add> this.addTemplate('posts.modal', '<div class="posts-modal">postsModal</div>'); <add> this.addTemplate('posts.extra', '<div class="posts-extra">postsExtra</div>'); <add> <add> this.router.map(function() { <add> this.route('posts', function() {}); <add> this.route('users', function() {}); <add> }); <add> <add> this.add( <add> 'route:posts', <add> Route.extend({ <add> actions: { <add> showModal() { <add> this.render('posts/modal', { <add> into: 'application', <add> outlet: 'modal', <add> }); <add> }, <add> hideModal() { <add> this.disconnectOutlet({ <add> outlet: 'modal', <add> parentView: 'application', <add> }); <add> }, <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'route:posts.index', <add> Route.extend({ <add> actions: { <add> showExtra() { <add> this.render('posts/extra', { <add> into: 'posts/index', <add> }); <add> }, <add> hideExtra() { <add> this.disconnectOutlet({ parentView: 'posts/index' }); <add> }, <add> }, <add> }) <add> ); <add> <add> let rootElement = document.getElementById('qunit-fixture'); <add> <add> return this.visit('/posts') <add> .then(() => { <add> let router = this.applicationInstance.lookup('router:main'); <add> <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-index')), <add> 'postsIndex', <add> 'The posts/index template was rendered' <add> ); <add> run(() => router.send('showModal')); <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-modal')), <add> 'postsModal', <add> 'The posts/modal template was rendered' <add> ); <add> run(() => router.send('showExtra')); <add> <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-extra')), <add> 'postsExtra', <add> 'The posts/extra template was rendered' <add> ); <add> run(() => router.send('hideModal')); <add> <add> assert.equal( <add> rootElement.querySelector('div.posts-modal'), <add> null, <add> 'The posts/modal template was removed' <add> ); <add> run(() => router.send('hideExtra')); <add> <add> assert.equal( <add> rootElement.querySelector('div.posts-extra'), <add> null, <add> 'The posts/extra template was removed' <add> ); <add> run(function() { <add> router.send('showModal'); <add> }); <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-modal')), <add> 'postsModal', <add> 'The posts/modal template was rendered' <add> ); <add> run(function() { <add> router.send('showExtra'); <add> }); <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-extra')), <add> 'postsExtra', <add> 'The posts/extra template was rendered' <add> ); <add> return this.visit('/users'); <add> }) <add> .then(() => { <add> assert.equal( <add> rootElement.querySelector('div.posts-index'), <add> null, <add> 'The posts/index template was removed' <add> ); <add> assert.equal( <add> rootElement.querySelector('div.posts-modal'), <add> null, <add> 'The posts/modal template was removed' <add> ); <add> assert.equal( <add> rootElement.querySelector('div.posts-extra'), <add> null, <add> 'The posts/extra template was removed' <add> ); <add> }); <add> } <add> <add> ['@test Route supports clearing outlet using string parameter'](assert) { <add> this.addTemplate('application', "{{outlet}}{{outlet 'modal'}}"); <add> this.addTemplate('posts', '{{outlet}}'); <add> this.addTemplate('users', 'users'); <add> this.addTemplate('posts.index', '<div class="posts-index">postsIndex {{outlet}}</div>'); <add> this.addTemplate('posts.modal', '<div class="posts-modal">postsModal</div>'); <add> <add> this.router.map(function() { <add> this.route('posts', function() {}); <add> this.route('users', function() {}); <add> }); <add> <add> this.add( <add> 'route:posts', <add> Route.extend({ <add> actions: { <add> showModal() { <add> this.render('posts/modal', { <add> into: 'application', <add> outlet: 'modal', <add> }); <add> }, <add> hideModal() { <add> this.disconnectOutlet('modal'); <add> }, <add> }, <add> }) <add> ); <add> <add> let rootElement = document.getElementById('qunit-fixture'); <add> return this.visit('/posts') <add> .then(() => { <add> let router = this.applicationInstance.lookup('router:main'); <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-index')), <add> 'postsIndex', <add> 'The posts/index template was rendered' <add> ); <add> run(() => router.send('showModal')); <add> assert.equal( <add> getTextOf(rootElement.querySelector('div.posts-modal')), <add> 'postsModal', <add> 'The posts/modal template was rendered' <add> ); <add> run(() => router.send('hideModal')); <add> assert.equal( <add> rootElement.querySelector('div.posts-modal'), <add> null, <add> 'The posts/modal template was removed' <add> ); <add> return this.visit('/users'); <add> }) <add> .then(() => { <add> assert.equal( <add> rootElement.querySelector('div.posts-index'), <add> null, <add> 'The posts/index template was removed' <add> ); <add> assert.equal( <add> rootElement.querySelector('div.posts-modal'), <add> null, <add> 'The posts/modal template was removed' <add> ); <add> }); <add> } <add> <add> ['@test Route silently fails when cleaning an outlet from an inactive view'](assert) { <add> assert.expect(1); // handleURL <add> <add> this.addTemplate('application', '{{outlet}}'); <add> this.addTemplate('posts', "{{outlet 'modal'}}"); <add> this.addTemplate('modal', 'A Yo.'); <add> <add> this.router.map(function() { <add> this.route('posts'); <add> }); <add> <add> this.add( <add> 'route:posts', <add> Route.extend({ <add> actions: { <add> hideSelf() { <add> this.disconnectOutlet({ <add> outlet: 'main', <add> parentView: 'application', <add> }); <add> }, <add> showModal() { <add> this.render('modal', { into: 'posts', outlet: 'modal' }); <add> }, <add> hideModal() { <add> this.disconnectOutlet({ outlet: 'modal', parentView: 'posts' }); <add> }, <add> }, <add> }) <add> ); <add> <add> return this.visit('/posts').then(() => { <add> assert.ok(true, '/posts has been handled'); <add> let router = this.applicationInstance.lookup('router:main'); <add> run(() => router.send('showModal')); <add> run(() => router.send('hideSelf')); <add> run(() => router.send('hideModal')); <add> }); <add> } <add> <add> ['@test Specifying non-existent controller name in route#render throws'](assert) { <add> assert.expect(1); <add> <add> this.router.map(function() { <add> this.route('home', { path: '/' }); <add> }); <add> <add> this.add( <add> 'route:home', <add> Route.extend({ <add> renderTemplate() { <add> expectAssertion(() => { <add> this.render('homepage', { <add> controller: 'stefanpenneristhemanforme', <add> }); <add> }, "You passed `controller: 'stefanpenneristhemanforme'` into the `render` method, but no such controller could be found."); <add> }, <add> }) <add> ); <add> <add> return this.visit('/'); <add> } <add> <add> ['@test {{outlet}} works when created after initial render'](assert) { <add> this.addTemplate('sample', 'Hi{{#if showTheThing}}{{outlet}}{{/if}}Bye'); <add> this.addTemplate('sample.inner', 'Yay'); <add> this.addTemplate('sample.inner2', 'Boo'); <add> this.router.map(function() { <add> this.route('sample', { path: '/' }, function() { <add> this.route('inner', { path: '/' }); <add> this.route('inner2', { path: '/2' }); <add> }); <add> }); <add> <add> let rootElement; <add> return this.visit('/') <add> .then(() => { <add> rootElement = document.getElementById('qunit-fixture'); <add> assert.equal(rootElement.textContent.trim(), 'HiBye', 'initial render'); <add> <add> run(() => this.applicationInstance.lookup('controller:sample').set('showTheThing', true)); <add> <add> assert.equal(rootElement.textContent.trim(), 'HiYayBye', 'second render'); <add> return this.visit('/2'); <add> }) <add> .then(() => { <add> assert.equal(rootElement.textContent.trim(), 'HiBooBye', 'third render'); <add> }); <add> } <add> <add> ['@test Can render into a named outlet at the top level'](assert) { <add> this.addTemplate('application', 'A-{{outlet}}-B-{{outlet "other"}}-C'); <add> this.addTemplate('modal', 'Hello world'); <add> this.addTemplate('index', 'The index'); <add> this.router.map(function() { <add> this.route('index', { path: '/' }); <add> }); <add> this.add( <add> 'route:application', <add> Route.extend({ <add> renderTemplate() { <add> this.render(); <add> this.render('modal', { <add> into: 'application', <add> outlet: 'other', <add> }); <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> rootElement.textContent.trim(), <add> 'A-The index-B-Hello world-C', <add> 'initial render' <add> ); <add> }); <add> } <add> <add> ['@test Can disconnect a named outlet at the top level'](assert) { <add> this.addTemplate('application', 'A-{{outlet}}-B-{{outlet "other"}}-C'); <add> this.addTemplate('modal', 'Hello world'); <add> this.addTemplate('index', 'The index'); <add> this.router.map(function() { <add> this.route('index', { path: '/' }); <add> }); <add> this.add( <add> 'route:application', <add> Route.extend({ <add> renderTemplate() { <add> this.render(); <add> this.render('modal', { <add> into: 'application', <add> outlet: 'other', <add> }); <add> }, <add> actions: { <add> banish() { <add> this.disconnectOutlet({ <add> parentView: 'application', <add> outlet: 'other', <add> }); <add> }, <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> rootElement.textContent.trim(), <add> 'A-The index-B-Hello world-C', <add> 'initial render' <add> ); <add> <add> run(this.applicationInstance.lookup('router:main'), 'send', 'banish'); <add> <add> assert.equal(rootElement.textContent.trim(), 'A-The index-B--C', 'second render'); <add> }); <add> } <add> <add> ['@test Can render into a named outlet at the top level, with empty main outlet'](assert) { <add> this.addTemplate('application', 'A-{{outlet}}-B-{{outlet "other"}}-C'); <add> this.addTemplate('modal', 'Hello world'); <add> <add> this.router.map(function() { <add> this.route('hasNoTemplate', { path: '/' }); <add> }); <add> <add> this.add( <add> 'route:application', <add> Route.extend({ <add> renderTemplate() { <add> this.render(); <add> this.render('modal', { <add> into: 'application', <add> outlet: 'other', <add> }); <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal(rootElement.textContent.trim(), 'A--B-Hello world-C', 'initial render'); <add> }); <add> } <add> <add> ['@test Can render into a named outlet at the top level, later'](assert) { <add> this.addTemplate('application', 'A-{{outlet}}-B-{{outlet "other"}}-C'); <add> this.addTemplate('modal', 'Hello world'); <add> this.addTemplate('index', 'The index'); <add> this.router.map(function() { <add> this.route('index', { path: '/' }); <add> }); <add> this.add( <add> 'route:application', <add> Route.extend({ <add> actions: { <add> launch() { <add> this.render('modal', { <add> into: 'application', <add> outlet: 'other', <add> }); <add> }, <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal(rootElement.textContent.trim(), 'A-The index-B--C', 'initial render'); <add> run(this.applicationInstance.lookup('router:main'), 'send', 'launch'); <add> assert.equal( <add> rootElement.textContent.trim(), <add> 'A-The index-B-Hello world-C', <add> 'second render' <add> ); <add> }); <add> } <add> <add> ["@test Can render routes with no 'main' outlet and their children"](assert) { <add> this.addTemplate('application', '<div id="application">{{outlet "app"}}</div>'); <add> this.addTemplate( <add> 'app', <add> '<div id="app-common">{{outlet "common"}}</div><div id="app-sub">{{outlet "sub"}}</div>' <add> ); <add> this.addTemplate('common', '<div id="common"></div>'); <add> this.addTemplate('sub', '<div id="sub"></div>'); <add> <add> this.router.map(function() { <add> this.route('app', { path: '/app' }, function() { <add> this.route('sub', { path: '/sub', resetNamespace: true }); <add> }); <add> }); <add> <add> this.add( <add> 'route:app', <add> Route.extend({ <add> renderTemplate() { <add> this.render('app', { <add> outlet: 'app', <add> into: 'application', <add> }); <add> this.render('common', { <add> outlet: 'common', <add> into: 'app', <add> }); <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'route:sub', <add> Route.extend({ <add> renderTemplate() { <add> this.render('sub', { <add> outlet: 'sub', <add> into: 'app', <add> }); <add> }, <add> }) <add> ); <add> <add> let rootElement; <add> return this.visit('/app') <add> .then(() => { <add> rootElement = document.getElementById('qunit-fixture'); <add> assert.equal( <add> rootElement.querySelectorAll('#app-common #common').length, <add> 1, <add> 'Finds common while viewing /app' <add> ); <add> return this.visit('/app/sub'); <add> }) <add> .then(() => { <add> assert.equal( <add> rootElement.querySelectorAll('#app-common #common').length, <add> 1, <add> 'Finds common while viewing /app/sub' <add> ); <add> assert.equal( <add> rootElement.querySelectorAll('#app-sub #sub').length, <add> 1, <add> 'Finds sub while viewing /app/sub' <add> ); <add> }); <add> } <add> <add> ['@test Tolerates stacked renders'](assert) { <add> this.addTemplate('application', '{{outlet}}{{outlet "modal"}}'); <add> this.addTemplate('index', 'hi'); <add> this.addTemplate('layer', 'layer'); <add> this.router.map(function() { <add> this.route('index', { path: '/' }); <add> }); <add> this.add( <add> 'route:application', <add> Route.extend({ <add> actions: { <add> openLayer() { <add> this.render('layer', { <add> into: 'application', <add> outlet: 'modal', <add> }); <add> }, <add> close() { <add> this.disconnectOutlet({ <add> outlet: 'modal', <add> parentView: 'application', <add> }); <add> }, <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> let router = this.applicationInstance.lookup('router:main'); <add> assert.equal(rootElement.textContent.trim(), 'hi'); <add> run(router, 'send', 'openLayer'); <add> assert.equal(rootElement.textContent.trim(), 'hilayer'); <add> run(router, 'send', 'openLayer'); <add> assert.equal(rootElement.textContent.trim(), 'hilayer'); <add> run(router, 'send', 'close'); <add> assert.equal(rootElement.textContent.trim(), 'hi'); <add> }); <add> } <add> <add> ['@test Renders child into parent with non-default template name'](assert) { <add> this.addTemplate('application', '<div class="a">{{outlet}}</div>'); <add> this.addTemplate('exports.root', '<div class="b">{{outlet}}</div>'); <add> this.addTemplate('exports.index', '<div class="c"></div>'); <add> <add> this.router.map(function() { <add> this.route('root', function() {}); <add> }); <add> <add> this.add( <add> 'route:root', <add> Route.extend({ <add> renderTemplate() { <add> this.render('exports/root'); <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'route:root.index', <add> Route.extend({ <add> renderTemplate() { <add> this.render('exports/index'); <add> }, <add> }) <add> ); <add> <add> return this.visit('/root').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> assert.equal(rootElement.querySelectorAll('.a .b .c').length, 1); <add> }); <add> } <add> <add> ["@test Allows any route to disconnectOutlet another route's templates"](assert) { <add> this.addTemplate('application', '{{outlet}}{{outlet "modal"}}'); <add> this.addTemplate('index', 'hi'); <add> this.addTemplate('layer', 'layer'); <add> this.router.map(function() { <add> this.route('index', { path: '/' }); <add> }); <add> this.add( <add> 'route:application', <add> Route.extend({ <add> actions: { <add> openLayer() { <add> this.render('layer', { <add> into: 'application', <add> outlet: 'modal', <add> }); <add> }, <add> }, <add> }) <add> ); <add> this.add( <add> 'route:index', <add> Route.extend({ <add> actions: { <add> close() { <add> this.disconnectOutlet({ <add> parentView: 'application', <add> outlet: 'modal', <add> }); <add> }, <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let rootElement = document.getElementById('qunit-fixture'); <add> let router = this.applicationInstance.lookup('router:main'); <add> assert.equal(rootElement.textContent.trim(), 'hi'); <add> run(router, 'send', 'openLayer'); <add> assert.equal(rootElement.textContent.trim(), 'hilayer'); <add> run(router, 'send', 'close'); <add> assert.equal(rootElement.textContent.trim(), 'hi'); <add> }); <add> } <add> <add> ['@test Components inside an outlet have their didInsertElement hook invoked when the route is displayed']( <add> assert <add> ) { <add> this.addTemplate( <add> 'index', <add> '{{#if showFirst}}{{my-component}}{{else}}{{other-component}}{{/if}}' <add> ); <add> <add> let myComponentCounter = 0; <add> let otherComponentCounter = 0; <add> let indexController; <add> <add> this.router.map(function() { <add> this.route('index', { path: '/' }); <add> }); <add> <add> this.add( <add> 'controller:index', <add> Controller.extend({ <add> showFirst: true, <add> }) <add> ); <add> <add> this.add( <add> 'route:index', <add> Route.extend({ <add> setupController(controller) { <add> indexController = controller; <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'component:my-component', <add> Component.extend({ <add> didInsertElement() { <add> myComponentCounter++; <add> }, <add> }) <add> ); <add> <add> this.add( <add> 'component:other-component', <add> Component.extend({ <add> didInsertElement() { <add> otherComponentCounter++; <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> assert.strictEqual( <add> myComponentCounter, <add> 1, <add> 'didInsertElement invoked on displayed component' <add> ); <add> assert.strictEqual( <add> otherComponentCounter, <add> 0, <add> 'didInsertElement not invoked on displayed component' <add> ); <add> <add> run(() => indexController.set('showFirst', false)); <add> <add> assert.strictEqual( <add> myComponentCounter, <add> 1, <add> 'didInsertElement not invoked on displayed component' <add> ); <add> assert.strictEqual( <add> otherComponentCounter, <add> 1, <add> 'didInsertElement invoked on displayed component' <add> ); <add> }); <add> } <add> <add> ['@test Exception if outlet name is undefined in render and disconnectOutlet']() { <add> this.add( <add> 'route:application', <add> Route.extend({ <add> actions: { <add> showModal() { <add> this.render({ <add> outlet: undefined, <add> parentView: 'application', <add> }); <add> }, <add> hideModal() { <add> this.disconnectOutlet({ <add> outlet: undefined, <add> parentView: 'application', <add> }); <add> }, <add> }, <add> }) <add> ); <add> <add> return this.visit('/').then(() => { <add> let router = this.applicationInstance.lookup('router:main'); <add> expectAssertion(() => { <add> run(() => router.send('showModal')); <add> }, /You passed undefined as the outlet name/); <add> <add> expectAssertion(() => { <add> run(() => router.send('hideModal')); <add> }, /You passed undefined as the outlet name/); <add> }); <add> } <add> } <add>);
3
Python
Python
install iojs -> node compat symlink
72f1b348b021269f98783aee2f0e89500a20231c
<ide><path>tools/install.py <ide> def subdir_files(path, dest, action): <ide> action(files, subdir + '/') <ide> <ide> def files(action): <del> exeext = '.exe' if sys.platform == 'win32' else '' <add> is_windows = sys.platform == 'win32' <add> <add> exeext = '.exe' if is_windows else '' <ide> action(['out/Release/iojs' + exeext], 'bin/iojs' + exeext) <ide> <add> if not is_windows: <add> # Install iojs -> node compatibility symlink. <add> link_target = 'bin/node' <add> link_path = abspath(install_path, link_target) <add> if action == uninstall: <add> action([link_path], link_target) <add> elif action == install: <add> try_symlink('iojs', link_path) <add> else: <add> assert(0) # Unhandled action type. <add> <ide> if 'true' == variables.get('node_use_dtrace'): <ide> action(['out/Release/node.d'], 'lib/dtrace/node.d') <ide>
1
Python
Python
recognize c rtl used by py3.5 on win
965c565852b92006fa427118cfc4026135279790
<ide><path>numpy/distutils/misc_util.py <ide> def msvc_runtime_library(): <ide> "Return name of MSVC runtime library if Python was built with MSVC >= 7" <ide> ver = msvc_runtime_major () <ide> if ver: <del> return "msvcr%i" % ver <add> if ver < 140: <add> return "msvcr%i" % ver <add> else: <add> return "vcruntime%i" % ver <ide> else: <ide> return None <ide> <ide> def msvc_runtime_major(): <ide> 1400: 80, # MSVC 8 <ide> 1500: 90, # MSVC 9 (aka 2008) <ide> 1600: 100, # MSVC 10 (aka 2010) <add> 1900: 140, # MSVC 14 (aka 2015) <ide> }.get(msvc_runtime_version(), None) <ide> return major <ide>
1
Mixed
Ruby
remove deprecate `*_path` helpers in email views
d282125a18c1697a9b5bb775628a2db239142ac7
<ide><path>actionmailer/CHANGELOG.md <add>* Remove deprecate `*_path` helpers in email views. <add> <add> *Rafael Mendonça França* <add> <ide> * Remove deprecated `deliver` and `deliver!` methods. <ide> <ide> *claudiob* <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def merge_default_action!(params) <ide> # named routes. <ide> class NamedRouteCollection #:nodoc: <ide> include Enumerable <del> attr_reader :routes, :url_helpers_module <add> attr_reader :routes, :url_helpers_module, :path_helpers_module <ide> <ide> def initialize <ide> @routes = {} <ide> def length <ide> routes.length <ide> end <ide> <del> def path_helpers_module(warn = false) <del> if warn <del> mod = @path_helpers_module <del> helpers = @path_helpers <del> Module.new do <del> include mod <del> <del> helpers.each do |meth| <del> define_method(meth) do |*args, &block| <del> ActiveSupport::Deprecation.warn("The method `#{meth}` cannot be used here as a full URL is required. Use `#{meth.to_s.sub(/_path$/, '_url')}` instead") <del> super(*args, &block) <del> end <del> end <del> end <del> else <del> @path_helpers_module <del> end <del> end <del> <ide> class UrlHelper # :nodoc: <ide> def self.create(route, options, route_name, url_strategy) <ide> if optimize_helper?(route) <ide> def url_options; {}; end <ide> <ide> if supports_path <ide> path_helpers = routes.named_routes.path_helpers_module <del> else <del> path_helpers = routes.named_routes.path_helpers_module(true) <del> end <ide> <del> include path_helpers <del> extend path_helpers <add> include path_helpers <add> extend path_helpers <add> end <ide> <ide> # plus a singleton class method called _routes ... <ide> included do <ide><path>actionpack/test/routing/helper_test.rb <ide> def test_exception <ide> x.new.pond_duck_path Duck.new <ide> end <ide> end <del> <del> def test_path_deprecation <del> rs = ::ActionDispatch::Routing::RouteSet.new <del> rs.draw do <del> resources :ducks <del> end <del> <del> x = Class.new { <del> include rs.url_helpers(false) <del> } <del> assert_deprecated do <del> assert_equal '/ducks', x.new.ducks_path <del> end <del> end <ide> end <ide> end <ide> end <ide><path>railties/test/application/initializers/frameworks_test.rb <ide> def notify <ide> RUBY <ide> <ide> require "#{app_path}/config/environment" <del> assert Foo.method_defined?(:foo_path) <ide> assert Foo.method_defined?(:foo_url) <ide> assert Foo.method_defined?(:main_app) <ide> end <ide><path>railties/test/application/mailer_previews_test.rb <ide> def foo <ide> assert_match '<option selected value="?part=text%2Fplain">View as plain-text email</option>', last_response.body <ide> end <ide> <del> test "*_path helpers emit a deprecation" do <del> <del> app_file "config/routes.rb", <<-RUBY <del> Rails.application.routes.draw do <del> get 'foo', to: 'foo#index' <del> end <del> RUBY <del> <del> mailer 'notifier', <<-RUBY <del> class Notifier < ActionMailer::Base <del> default from: "from@example.com" <del> <del> def path_in_view <del> mail to: "to@example.org" <del> end <del> <del> def path_in_mailer <del> @url = foo_path <del> mail to: "to@example.org" <del> end <del> end <del> RUBY <del> <del> html_template 'notifier/path_in_view', "<%= link_to 'foo', foo_path %>" <del> <del> mailer_preview 'notifier', <<-RUBY <del> class NotifierPreview < ActionMailer::Preview <del> def path_in_view <del> Notifier.path_in_view <del> end <del> <del> def path_in_mailer <del> Notifier.path_in_mailer <del> end <del> end <del> RUBY <del> <del> app('development') <del> <del> assert_deprecated do <del> get "/rails/mailers/notifier/path_in_view.html" <del> assert_equal 200, last_response.status <del> end <del> <del> html_template 'notifier/path_in_mailer', "No ERB in here" <del> <del> assert_deprecated do <del> get "/rails/mailers/notifier/path_in_mailer.html" <del> assert_equal 200, last_response.status <del> end <del> end <del> <ide> private <ide> def build_app <ide> super <ide><path>railties/test/railties/engine_test.rb <ide> class MyMailer < ActionMailer::Base <ide> assert_equal "bukkits_", Bukkits.table_name_prefix <ide> assert_equal "bukkits", Bukkits::Engine.engine_name <ide> assert_equal Bukkits.railtie_namespace, Bukkits::Engine <del> assert ::Bukkits::MyMailer.method_defined?(:foo_path) <del> assert !::Bukkits::MyMailer.method_defined?(:bar_path) <add> assert ::Bukkits::MyMailer.method_defined?(:foo_url) <add> assert !::Bukkits::MyMailer.method_defined?(:bar_url) <ide> <ide> get("/bukkits/from_app") <ide> assert_equal "false", last_response.body
6
Java
Java
harmonize hint registration
58a2b7969901fbd703bc8ffed905b5d8a3c6d8d3
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java <ide> private CodeBlock generateMethodStatementForMethod(Method method, <ide> AccessVisibility visibility = AccessVisibility.forMember(method); <ide> if (visibility == AccessVisibility.PRIVATE <ide> || visibility == AccessVisibility.PROTECTED) { <del> hints.reflection().registerMethod(method); <add> hints.reflection().registerMethod(method, ExecutableMode.INVOKE); <ide> code.add(".resolveAndInvoke($L, $L)", REGISTERED_BEAN_PARAMETER, <ide> INSTANCE_PARAMETER); <ide> } <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGenerator.java <ide> private void addInitDestroyMethods(Builder code, <ide> private void addInitDestroyHint(Class<?> beanUserClass, String methodName) { <ide> Method method = ReflectionUtils.findMethod(beanUserClass, methodName); <ide> if (method != null) { <del> this.hints.reflection().registerMethod(method); <add> this.hints.reflection().registerMethod(method, ExecutableMode.INVOKE); <ide> } <ide> } <ide> <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGenerator.java <ide> private CodeBlock generateCodeForInaccessibleConstructor(String beanName, <ide> Class<?> beanClass, Constructor<?> constructor, boolean dependsOnBean) { <ide> <ide> this.generationContext.getRuntimeHints().reflection() <del> .registerConstructor(constructor); <add> .registerConstructor(constructor, ExecutableMode.INVOKE); <ide> GeneratedMethod generatedMethod = generateGetInstanceSupplierMethod(method -> { <ide> method.addJavadoc("Get the bean instance supplier for '$L'.", beanName); <ide> method.addModifiers(PRIVATE_STATIC); <ide> private CodeBlock generateCodeForInaccessibleFactoryMethod(String beanName, Clas <ide> Method factoryMethod, Class<?> declaringClass) { <ide> <ide> this.generationContext.getRuntimeHints().reflection() <del> .registerMethod(factoryMethod); <add> .registerMethod(factoryMethod, ExecutableMode.INVOKE); <ide> GeneratedMethod getInstanceMethod = generateGetInstanceSupplierMethod(method -> { <ide> method.addJavadoc("Get the bean instance supplier for '$L'.", beanName); <ide> method.addModifiers(PRIVATE_STATIC); <ide><path>spring-core-test/src/test/java/org/springframework/aot/agent/InstrumentedMethodTests.java <ide> void classGetConstructorsShouldNotMatchTypeReflectionHint() { <ide> <ide> @Test <ide> void classGetConstructorsShouldMatchConstructorReflectionHint() throws Exception { <del> hints.reflection().registerConstructor(String.class.getConstructor()); <add> hints.reflection().registerConstructor(String.class.getConstructor(), ExecutableMode.INVOKE); <ide> assertThatInvocationMatches(InstrumentedMethod.CLASS_GETCONSTRUCTORS, this.stringGetConstructors); <ide> } <ide> <ide> void classGetDeclaredConstructorsShouldNotMatchTypeReflectionHint() { <ide> <ide> @Test <ide> void classGetDeclaredConstructorsShouldMatchConstructorReflectionHint() throws Exception { <del> hints.reflection().registerConstructor(String.class.getConstructor()); <add> hints.reflection().registerConstructor(String.class.getConstructor(), ExecutableMode.INVOKE); <ide> assertThatInvocationMatches(InstrumentedMethod.CLASS_GETDECLAREDCONSTRUCTORS, this.stringGetDeclaredConstructors); <ide> } <ide> <ide> void classGetDeclaredMethodsShouldNotMatchTypeReflectionHint() { <ide> <ide> @Test <ide> void classGetDeclaredMethodsShouldMatchMethodReflectionHint() throws Exception { <del> hints.reflection().registerMethod(String.class.getMethod("toString")); <add> hints.reflection().registerMethod(String.class.getMethod("toString"), ExecutableMode.INVOKE); <ide> assertThatInvocationMatches(InstrumentedMethod.CLASS_GETDECLAREDMETHODS, this.stringGetScaleMethod); <ide> } <ide> <ide> void classGetMethodsShouldNotMatchTypeReflectionHint() { <ide> <ide> @Test <ide> void classGetMethodsShouldMatchMethodReflectionHint() throws Exception { <del> hints.reflection().registerMethod(String.class.getMethod("toString")); <add> hints.reflection().registerMethod(String.class.getMethod("toString"), ExecutableMode.INVOKE); <ide> assertThatInvocationMatches(InstrumentedMethod.CLASS_GETMETHODS, this.stringGetMethods); <ide> } <ide> <ide><path>spring-core/src/main/java/org/springframework/aot/hint/BindingReflectionHintsRegistrar.java <ide> private void registerKotlinSerializationHints(ReflectionHints hints, Class<?> cl <ide> Class<?> companionClass = ClassUtils.resolveClassName(companionClassName, null); <ide> Method serializerMethod = ClassUtils.getMethodIfAvailable(companionClass, "serializer"); <ide> if (serializerMethod != null) { <del> hints.registerMethod(serializerMethod); <add> hints.registerMethod(serializerMethod, ExecutableMode.INVOKE); <ide> } <ide> } <ide> } <ide><path>spring-core/src/main/java/org/springframework/aot/hint/ReflectionHints.java <ide> * Gather the need for reflection at runtime. <ide> * <ide> * @author Stephane Nicoll <add> * @author Phillip Webb <add> * @author Andy Wilkinson <ide> * @since 6.0 <ide> */ <ide> public class ReflectionHints { <ide> public TypeHint getTypeHint(Class<?> type) { <ide> * @param type the type to customize <ide> * @param typeHint a builder to further customize hints for that type <ide> * @return {@code this}, to facilitate method chaining <add> * @see #registerType(TypeReference, MemberCategory...) <ide> */ <ide> public ReflectionHints registerType(TypeReference type, Consumer<TypeHint.Builder> typeHint) { <ide> Builder builder = this.types.computeIfAbsent(type, TypeHint.Builder::new); <ide> public ReflectionHints registerType(TypeReference type, Consumer<TypeHint.Builde <ide> * @param memberCategories the member categories to apply <ide> * @return {@code this}, to facilitate method chaining <ide> */ <del> public ReflectionHints registerType(Class<?> type, MemberCategory... memberCategories) { <del> return registerType(TypeReference.of(type), memberCategories); <add> public ReflectionHints registerType(TypeReference type, MemberCategory... memberCategories) { <add> return registerType(type, TypeHint.builtWith(memberCategories)); <ide> } <ide> <ide> /** <del> * Register or customize reflection hints for the specified type <del> * using the specified {@link MemberCategory MemberCategories}. <add> * Register or customize reflection hints for the specified type. <ide> * @param type the type to customize <del> * @param memberCategories the member categories to apply <add> * @param typeHint a builder to further customize hints for that type <ide> * @return {@code this}, to facilitate method chaining <add> * @see #registerType(Class, MemberCategory...) <ide> */ <del> public ReflectionHints registerType(TypeReference type , MemberCategory... memberCategories) { <del> return registerType(type, TypeHint.builtWith(memberCategories)); <add> public ReflectionHints registerType(Class<?> type, Consumer<TypeHint.Builder> typeHint) { <add> return registerType(TypeReference.of(type), typeHint); <ide> } <ide> <ide> /** <del> * Register or customize reflection hints for the specified type. <add> * Register or customize reflection hints for the specified type <add> * using the specified {@link MemberCategory MemberCategories}. <ide> * @param type the type to customize <del> * @param typeHint a builder to further customize hints for that type <add> * @param memberCategories the member categories to apply <ide> * @return {@code this}, to facilitate method chaining <ide> */ <del> public ReflectionHints registerType(Class<?> type, Consumer<TypeHint.Builder> typeHint) { <del> return registerType(TypeReference.of(type), typeHint); <add> public ReflectionHints registerType(Class<?> type, MemberCategory... memberCategories) { <add> return registerType(TypeReference.of(type), memberCategories); <ide> } <ide> <ide> /** <ide> public ReflectionHints registerType(Class<?> type, Consumer<TypeHint.Builder> ty <ide> * @param typeName the type to customize <ide> * @param typeHint a builder to further customize hints for that type <ide> * @return {@code this}, to facilitate method chaining <add> * @see #registerTypeIfPresent(ClassLoader, String, MemberCategory...) <ide> */ <ide> public ReflectionHints registerTypeIfPresent(@Nullable ClassLoader classLoader, <ide> String typeName, Consumer<TypeHint.Builder> typeHint) { <ide> public ReflectionHints registerTypeIfPresent(@Nullable ClassLoader classLoader, <ide> return this; <ide> } <ide> <add> /** <add> * Register or customize reflection hints for the specified type if it <add> * is available using the specified {@link ClassLoader}. <add> * @param classLoader the classloader to use to check if the type is present <add> * @param typeName the type to customize <add> * @param memberCategories the member categories to apply <add> * @return {@code this}, to facilitate method chaining <add> */ <add> public ReflectionHints registerTypeIfPresent(@Nullable ClassLoader classLoader, <add> String typeName, MemberCategory... memberCategories) { <add> return registerTypeIfPresent(classLoader, typeName, TypeHint.builtWith(memberCategories)); <add> } <add> <ide> /** <ide> * Register or customize reflection hints for the types defined by the <ide> * specified list of {@link TypeReference type references}. The specified <ide> public ReflectionHints registerField(Field field) { <ide> * enabling {@link ExecutableMode#INVOKE}. <ide> * @param constructor the constructor that requires reflection <ide> * @return {@code this}, to facilitate method chaining <add> * @deprecated in favor of {@link #registerConstructor(Constructor, ExecutableMode)} <ide> */ <add> @Deprecated <ide> public ReflectionHints registerConstructor(Constructor<?> constructor) { <ide> return registerConstructor(constructor, ExecutableMode.INVOKE); <ide> } <ide> public ReflectionHints registerConstructor(Constructor<?> constructor) { <ide> * @return {@code this}, to facilitate method chaining <ide> */ <ide> public ReflectionHints registerConstructor(Constructor<?> constructor, ExecutableMode mode) { <del> return registerConstructor(constructor, ExecutableHint.builtWith(mode)); <add> return registerType(TypeReference.of(constructor.getDeclaringClass()), <add> typeHint -> typeHint.withConstructor(mapParameters(constructor), mode)); <ide> } <ide> <ide> /** <ide> * Register the need for reflection on the specified {@link Constructor}. <ide> * @param constructor the constructor that requires reflection <ide> * @param constructorHint a builder to further customize the hints of this <ide> * constructor <del> * @return {@code this}, to facilitate method chaining <add> * @return {@code this}, to facilitate method chaining` <add> * @deprecated in favor of {@link #registerConstructor(Constructor, ExecutableMode)} <ide> */ <add> @Deprecated <ide> public ReflectionHints registerConstructor(Constructor<?> constructor, Consumer<ExecutableHint.Builder> constructorHint) { <ide> return registerType(TypeReference.of(constructor.getDeclaringClass()), <ide> typeHint -> typeHint.withConstructor(mapParameters(constructor), constructorHint)); <ide> public ReflectionHints registerConstructor(Constructor<?> constructor, Consumer< <ide> * enabling {@link ExecutableMode#INVOKE}. <ide> * @param method the method that requires reflection <ide> * @return {@code this}, to facilitate method chaining <add> * @deprecated in favor of {@link #registerMethod(Method, ExecutableMode)} <ide> */ <add> @Deprecated <ide> public ReflectionHints registerMethod(Method method) { <ide> return registerMethod(method, ExecutableMode.INVOKE); <ide> } <ide> public ReflectionHints registerMethod(Method method) { <ide> * @return {@code this}, to facilitate method chaining <ide> */ <ide> public ReflectionHints registerMethod(Method method, ExecutableMode mode) { <del> return registerMethod(method, ExecutableHint.builtWith(mode)); <add> return registerType(TypeReference.of(method.getDeclaringClass()), <add> typeHint -> typeHint.withMethod(method.getName(), mapParameters(method), mode)); <ide> } <ide> <ide> /** <ide> * Register the need for reflection on the specified {@link Method}. <ide> * @param method the method that requires reflection <ide> * @param methodHint a builder to further customize the hints of this method <ide> * @return {@code this}, to facilitate method chaining <add> * @deprecated in favor of {@link #registerMethod(Method, ExecutableMode)} <ide> */ <add> @Deprecated <ide> public ReflectionHints registerMethod(Method method, Consumer<ExecutableHint.Builder> methodHint) { <ide> return registerType(TypeReference.of(method.getDeclaringClass()), <ide> typeHint -> typeHint.withMethod(method.getName(), mapParameters(method), methodHint)); <ide><path>spring-core/src/main/java/org/springframework/aot/hint/TypeHint.java <ide> * A hint that describes the need for reflection on a type. <ide> * <ide> * @author Stephane Nicoll <add> * @author Phillip Webb <add> * @author Andy Wilkinson <ide> * @since 6.0 <ide> */ <ide> public final class TypeHint implements ConditionalHint { <ide> public Builder withField(String name) { <ide> * parameter types, enabling {@link ExecutableMode#INVOKE}. <ide> * @param parameterTypes the parameter types of the constructor <ide> * @return {@code this}, to facilitate method chaining <add> * @deprecated in favor of {@link #withConstructor(List, ExecutableMode)} <ide> */ <add> @Deprecated <ide> public Builder withConstructor(List<TypeReference> parameterTypes) { <ide> return withConstructor(parameterTypes, ExecutableMode.INVOKE); <ide> } <ide> public Builder withConstructor(List<TypeReference> parameterTypes, ExecutableMod <ide> * @param constructorHint a builder to further customize the hints of this <ide> * constructor <ide> * @return {@code this}, to facilitate method chaining <add> * @deprecated in favor of {@link #withConstructor(List, ExecutableMode)} <ide> */ <del> public Builder withConstructor(List<TypeReference> parameterTypes, Consumer<ExecutableHint.Builder> constructorHint) { <add> @Deprecated <add> public Builder withConstructor(List<TypeReference> parameterTypes, <add> Consumer<ExecutableHint.Builder> constructorHint) { <ide> ExecutableKey key = new ExecutableKey("<init>", parameterTypes); <ide> ExecutableHint.Builder builder = this.constructors.computeIfAbsent(key, <ide> k -> ExecutableHint.ofConstructor(parameterTypes)); <ide> public Builder withConstructor(List<TypeReference> parameterTypes, Consumer<Exec <ide> * @param name the name of the method <ide> * @param parameterTypes the parameter types of the constructor <ide> * @return {@code this}, to facilitate method chaining <add> * @deprecated in favor of {@link #withMethod(String, List, ExecutableMode)} <ide> */ <add> @Deprecated <ide> public Builder withMethod(String name, List<TypeReference> parameterTypes) { <ide> return withMethod(name, parameterTypes, ExecutableMode.INVOKE); <ide> } <ide> public Builder withMethod(String name, List<TypeReference> parameterTypes, Execu <ide> * @param parameterTypes the parameter types of the constructor <ide> * @param methodHint a builder to further customize the hints of this method <ide> * @return {@code this}, to facilitate method chaining <add> * @deprecated in favor of {@link #withMethod(String, List, ExecutableMode)} <ide> */ <del> public Builder withMethod(String name, List<TypeReference> parameterTypes, Consumer<ExecutableHint.Builder> methodHint) { <add> @Deprecated <add> public Builder withMethod(String name, List<TypeReference> parameterTypes, <add> Consumer<ExecutableHint.Builder> methodHint) { <ide> ExecutableKey key = new ExecutableKey(name, parameterTypes); <ide> ExecutableHint.Builder builder = this.methods.computeIfAbsent(key, <ide> k -> ExecutableHint.ofMethod(name, parameterTypes)); <ide> public Builder withMethod(String name, List<TypeReference> parameterTypes, Consu <ide> * Adds the specified {@linkplain MemberCategory member categories}. <ide> * @param memberCategories the categories to apply <ide> * @return {@code this}, to facilitate method chaining <add> * @see TypeHint#builtWith(MemberCategory...) <ide> */ <ide> public Builder withMembers(MemberCategory... memberCategories) { <ide> this.memberCategories.addAll(Arrays.asList(memberCategories)); <ide><path>spring-core/src/main/java/org/springframework/aot/hint/annotation/SimpleReflectiveProcessor.java <ide> import java.lang.reflect.Field; <ide> import java.lang.reflect.Method; <ide> <add>import org.springframework.aot.hint.ExecutableMode; <ide> import org.springframework.aot.hint.ReflectionHints; <ide> <ide> /** <ide> protected void registerTypeHint(ReflectionHints hints, Class<?> type) { <ide> * @param constructor the constructor to process <ide> */ <ide> protected void registerConstructorHint(ReflectionHints hints, Constructor<?> constructor) { <del> hints.registerConstructor(constructor); <add> hints.registerConstructor(constructor, ExecutableMode.INVOKE); <ide> } <ide> <ide> /** <ide> protected void registerFieldHint(ReflectionHints hints, Field field) { <ide> * @param method the method to process <ide> */ <ide> protected void registerMethodHint(ReflectionHints hints, Method method) { <del> hints.registerMethod(method); <add> hints.registerMethod(method, ExecutableMode.INVOKE); <ide> } <ide> <ide> } <ide><path>spring-core/src/test/java/org/springframework/aot/hint/ReflectionHintsTests.java <ide> <ide> package org.springframework.aot.hint; <ide> <add>import java.lang.reflect.Constructor; <ide> import java.lang.reflect.Field; <ide> import java.lang.reflect.Method; <ide> import java.util.function.Consumer; <ide> void registerType() { <ide> <ide> @Test <ide> void registerTypeIfPresentRegistersExistingClass() { <del> this.reflectionHints.registerTypeIfPresent(null, String.class.getName(), <del> hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS)); <add> this.reflectionHints.registerTypeIfPresent(null, String.class.getName(), MemberCategory.DECLARED_FIELDS); <ide> assertThat(this.reflectionHints.typeHints()).singleElement().satisfies( <ide> typeWithMemberCategories(String.class, MemberCategory.DECLARED_FIELDS)); <ide> } <ide> private void assertTestTypeFieldHint(Consumer<FieldHint> fieldHint) { <ide> <ide> @Test <ide> void registerConstructor() { <del> this.reflectionHints.registerConstructor(TestType.class.getDeclaredConstructors()[0]); <del> assertTestTypeConstructorHint(constructorHint -> { <del> assertThat(constructorHint.getParameterTypes()).isEmpty(); <del> assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <del> }); <del> } <del> <del> @Test <del> void registerConstructorWithMode() { <ide> this.reflectionHints.registerConstructor( <ide> TestType.class.getDeclaredConstructors()[0], ExecutableMode.INTROSPECT); <ide> assertTestTypeConstructorHint(constructorHint -> { <ide> void registerConstructorWithMode() { <ide> } <ide> <ide> @Test <del> void registerConstructorWithEmptyCustomizerAppliesConsistentDefault() { <del> this.reflectionHints.registerConstructor(TestType.class.getDeclaredConstructors()[0], <del> constructorHint -> {}); <add> void registerConstructorTwiceUpdatesExistingEntry() { <add> Constructor<?> constructor = TestType.class.getDeclaredConstructors()[0]; <add> this.reflectionHints.registerConstructor(constructor, ExecutableMode.INTROSPECT); <add> this.reflectionHints.registerConstructor(constructor, ExecutableMode.INVOKE); <ide> assertTestTypeConstructorHint(constructorHint -> { <ide> assertThat(constructorHint.getParameterTypes()).isEmpty(); <ide> assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <ide> }); <ide> } <ide> <del> @Test <del> void registerConstructorWithCustomizerAppliesCustomization() { <del> this.reflectionHints.registerConstructor(TestType.class.getDeclaredConstructors()[0], <del> constructorHint -> constructorHint.withMode(ExecutableMode.INTROSPECT)); <del> assertTestTypeConstructorHint(constructorHint -> { <del> assertThat(constructorHint.getParameterTypes()).isEmpty(); <del> assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INTROSPECT); <del> }); <del> } <del> <ide> private void assertTestTypeConstructorHint(Consumer<ExecutableHint> constructorHint) { <ide> assertThat(this.reflectionHints.typeHints()).singleElement().satisfies(typeHint -> { <ide> assertThat(typeHint.getMemberCategories()).isEmpty(); <ide> private void assertTestTypeConstructorHint(Consumer<ExecutableHint> constructorH <ide> <ide> @Test <ide> void registerMethod() { <del> Method method = ReflectionUtils.findMethod(TestType.class, "setName", String.class); <del> assertThat(method).isNotNull(); <del> this.reflectionHints.registerMethod(method); <del> assertTestTypeMethodHints(methodHint -> { <del> assertThat(methodHint.getName()).isEqualTo("setName"); <del> assertThat(methodHint.getParameterTypes()).containsOnly(TypeReference.of(String.class)); <del> assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <del> }); <del> } <del> <del> @Test <del> void registerMethodWithMode() { <ide> Method method = ReflectionUtils.findMethod(TestType.class, "setName", String.class); <ide> assertThat(method).isNotNull(); <ide> this.reflectionHints.registerMethod(method, ExecutableMode.INTROSPECT); <ide> void registerMethodWithMode() { <ide> } <ide> <ide> @Test <del> void registerMethodWithEmptyCustomizerAppliesConsistentDefault() { <add> void registerMethodTwiceUpdatesExistingEntry() { <ide> Method method = ReflectionUtils.findMethod(TestType.class, "setName", String.class); <ide> assertThat(method).isNotNull(); <del> this.reflectionHints.registerMethod(method, methodHint -> {}); <add> this.reflectionHints.registerMethod(method, ExecutableMode.INTROSPECT); <add> this.reflectionHints.registerMethod(method, ExecutableMode.INVOKE); <ide> assertTestTypeMethodHints(methodHint -> { <ide> assertThat(methodHint.getName()).isEqualTo("setName"); <ide> assertThat(methodHint.getParameterTypes()).containsOnly(TypeReference.of(String.class)); <ide> assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <ide> }); <ide> } <ide> <del> @Test <del> void registerMethodWithCustomizerAppliesCustomization() { <del> Method method = ReflectionUtils.findMethod(TestType.class, "setName", String.class); <del> assertThat(method).isNotNull(); <del> this.reflectionHints.registerMethod(method, methodHint -> methodHint.withMode(ExecutableMode.INTROSPECT)); <del> assertTestTypeMethodHints(methodHint -> { <del> assertThat(methodHint.getName()).isEqualTo("setName"); <del> assertThat(methodHint.getParameterTypes()).containsOnly(TypeReference.of(String.class)); <del> assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INTROSPECT); <del> }); <del> } <del> <ide> private void assertTestTypeMethodHints(Consumer<ExecutableHint> methodHint) { <ide> assertThat(this.reflectionHints.typeHints()).singleElement().satisfies(typeHint -> { <ide> assertThat(typeHint.getType().getCanonicalName()).isEqualTo(TestType.class.getCanonicalName()); <ide><path>spring-core/src/test/java/org/springframework/aot/hint/TypeHintTests.java <ide> void assertFieldHint(Builder builder, Consumer<FieldHint> fieldHint) { <ide> <ide> @Test <ide> void createWithConstructor() { <del> List<TypeReference> parameterTypes = TypeReference.listOf(byte[].class, int.class); <del> assertConstructorHint(TypeHint.of(TypeReference.of(String.class)) <del> .withConstructor(parameterTypes), constructorHint -> { <del> assertThat(constructorHint.getParameterTypes()).containsOnlyOnceElementsOf(parameterTypes); <del> assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <del> }); <del> } <del> <del> @Test <del> void createWithConstructorAndMode() { <ide> List<TypeReference> parameterTypes = TypeReference.listOf(byte[].class, int.class); <ide> assertConstructorHint(TypeHint.of(TypeReference.of(String.class)) <ide> .withConstructor(parameterTypes, ExecutableMode.INTROSPECT), constructorHint -> { <ide> void createWithConstructorAndMode() { <ide> } <ide> <ide> @Test <del> void createWithConstructorAndEmptyCustomizerAppliesConsistentDefault() { <del> List<TypeReference> parameterTypes = TypeReference.listOf(byte[].class, int.class); <del> assertConstructorHint(TypeHint.of(TypeReference.of(String.class)) <del> .withConstructor(parameterTypes, constructorHint -> {}), constructorHint -> { <del> assertThat(constructorHint.getParameterTypes()).containsOnlyOnceElementsOf(parameterTypes); <del> assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <del> }); <del> } <del> <del> @Test <del> void createWithConstructorAndCustomizerAppliesCustomization() { <del> List<TypeReference> parameterTypes = TypeReference.listOf(byte[].class, int.class); <del> assertConstructorHint(TypeHint.of(TypeReference.of(String.class)) <del> .withConstructor(parameterTypes, constructorHint -> <del> constructorHint.withMode(ExecutableMode.INTROSPECT)), constructorHint -> { <del> assertThat(constructorHint.getParameterTypes()).containsOnlyOnceElementsOf(parameterTypes); <del> assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INTROSPECT); <del> }); <del> } <del> <del> @Test <del> void createConstructorReuseBuilder() { <add> void createWithConstructorWithSameConstructorUpdatesEntry() { <ide> List<TypeReference> parameterTypes = TypeReference.listOf(byte[].class, int.class); <ide> Builder builder = TypeHint.of(TypeReference.of(String.class)) <ide> .withConstructor(parameterTypes, ExecutableMode.INTROSPECT); <del> assertConstructorHint(builder.withConstructor(parameterTypes, constructorHint -> <del> constructorHint.withMode(ExecutableMode.INVOKE)), constructorHint -> { <add> assertConstructorHint(builder.withConstructor(parameterTypes, ExecutableMode.INVOKE), constructorHint -> { <ide> assertThat(constructorHint.getParameterTypes()).containsExactlyElementsOf(parameterTypes); <ide> assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <ide> }); <ide> } <ide> <ide> @Test <del> void createConstructorReuseBuilderAndApplyExecutableModePrecedence() { <add> void createWithConstructorAndSameConstructorAppliesExecutableModePrecedence() { <ide> List<TypeReference> parameterTypes = TypeReference.listOf(byte[].class, int.class); <del> Builder builder = TypeHint.of(TypeReference.of(String.class)).withConstructor(parameterTypes, <del> constructorHint -> constructorHint.withMode(ExecutableMode.INVOKE)); <del> assertConstructorHint(builder.withConstructor(parameterTypes, constructorHint -> <del> constructorHint.withMode(ExecutableMode.INTROSPECT)), constructorHint -> { <add> Builder builder = TypeHint.of(TypeReference.of(String.class)) <add> .withConstructor(parameterTypes, ExecutableMode.INVOKE); <add> assertConstructorHint(builder.withConstructor(parameterTypes, ExecutableMode.INTROSPECT), constructorHint -> { <ide> assertThat(constructorHint.getParameterTypes()).containsExactlyElementsOf(parameterTypes); <ide> assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <ide> }); <ide> void assertConstructorHint(Builder builder, Consumer<ExecutableHint> constructor <ide> <ide> @Test <ide> void createWithMethod() { <del> List<TypeReference> parameterTypes = List.of(TypeReference.of(char[].class)); <del> assertMethodHint(TypeHint.of(TypeReference.of(String.class)) <del> .withMethod("valueOf", parameterTypes), methodHint -> { <del> assertThat(methodHint.getName()).isEqualTo("valueOf"); <del> assertThat(methodHint.getParameterTypes()).containsExactlyElementsOf(parameterTypes); <del> assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <del> }); <del> } <del> <del> @Test <del> void createWithMethodAndMode() { <ide> List<TypeReference> parameterTypes = List.of(TypeReference.of(char[].class)); <ide> assertMethodHint(TypeHint.of(TypeReference.of(String.class)) <ide> .withMethod("valueOf", parameterTypes, ExecutableMode.INTROSPECT), methodHint -> { <ide> void createWithMethodAndMode() { <ide> } <ide> <ide> @Test <del> void createWithMethodAndEmptyCustomizerAppliesConsistentDefault() { <del> List<TypeReference> parameterTypes = List.of(TypeReference.of(char[].class)); <del> assertMethodHint(TypeHint.of(TypeReference.of(String.class)) <del> .withMethod("valueOf", parameterTypes, methodHint -> {}), methodHint -> { <del> assertThat(methodHint.getName()).isEqualTo("valueOf"); <del> assertThat(methodHint.getParameterTypes()).containsExactlyElementsOf(parameterTypes); <del> assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <del> }); <del> } <del> <del> @Test <del> void createWithMethodAndCustomizerAppliesCustomization() { <del> List<TypeReference> parameterTypes = List.of(TypeReference.of(char[].class)); <del> assertMethodHint(TypeHint.of(TypeReference.of(String.class)) <del> .withMethod("valueOf", parameterTypes, methodHint -> <del> methodHint.withMode(ExecutableMode.INTROSPECT)), methodHint -> { <del> assertThat(methodHint.getName()).isEqualTo("valueOf"); <del> assertThat(methodHint.getParameterTypes()).containsExactlyElementsOf(parameterTypes); <del> assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INTROSPECT); <del> }); <del> } <del> <del> <del> @Test <del> void createWithMethodReuseBuilder() { <add> void createWithMethodWithSameMethodUpdatesEntry() { <ide> List<TypeReference> parameterTypes = TypeReference.listOf(char[].class); <ide> Builder builder = TypeHint.of(TypeReference.of(String.class)) <ide> .withMethod("valueOf", parameterTypes, ExecutableMode.INTROSPECT); <del> assertMethodHint(builder.withMethod("valueOf", parameterTypes, <del> methodHint -> methodHint.withMode(ExecutableMode.INVOKE)), methodHint -> { <add> assertMethodHint(builder.withMethod("valueOf", parameterTypes, ExecutableMode.INVOKE), methodHint -> { <ide> assertThat(methodHint.getName()).isEqualTo("valueOf"); <ide> assertThat(methodHint.getParameterTypes()).containsExactlyElementsOf(parameterTypes); <ide> assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <ide> }); <ide> } <ide> <ide> @Test <del> void createWithMethodReuseBuilderAndApplyExecutableModePrecedence() { <add> void createWithMethodAndSameMethodAppliesExecutableModePrecedence() { <ide> List<TypeReference> parameterTypes = TypeReference.listOf(char[].class); <ide> Builder builder = TypeHint.of(TypeReference.of(String.class)) <ide> .withMethod("valueOf", parameterTypes, ExecutableMode.INVOKE); <del> assertMethodHint(builder.withMethod("valueOf", parameterTypes, <del> methodHint -> methodHint.withMode(ExecutableMode.INTROSPECT)), methodHint -> { <add> assertMethodHint(builder.withMethod("valueOf", parameterTypes, ExecutableMode.INTROSPECT), methodHint -> { <ide> assertThat(methodHint.getName()).isEqualTo("valueOf"); <ide> assertThat(methodHint.getParameterTypes()).containsExactlyElementsOf(parameterTypes); <ide> assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INVOKE); <ide><path>spring-core/src/test/java/org/springframework/aot/hint/predicate/ReflectionHintsPredicatesTests.java <ide> void reflectionOnAnyConstructorDoesNotMatchTypeReflection() { <ide> <ide> @Test <ide> void reflectionOnAnyConstructorMatchesConstructorReflection() { <del> runtimeHints.reflection().registerConstructor(publicConstructor); <add> runtimeHints.reflection().registerConstructor(publicConstructor, ExecutableMode.INVOKE); <ide> assertPredicateMatches(reflection.onType(SampleClass.class).withAnyConstructor()); <ide> } <ide> <ide> void reflectionOnAnyMethodDoesNotMatchTypeReflection() { <ide> <ide> @Test <ide> void reflectionOnAnyMethodMatchesMethodReflection() { <del> runtimeHints.reflection().registerMethod(publicMethod); <add> runtimeHints.reflection().registerMethod(publicMethod, ExecutableMode.INVOKE); <ide> assertPredicateMatches(reflection.onType(SampleClass.class).withAnyMethod()); <ide> } <ide> <ide><path>spring-core/src/test/java/org/springframework/aot/nativex/FileNativeConfigurationWriterTests.java <ide> void reflectionConfig() throws IOException, JSONException { <ide> .withField("DEFAULT_CHARSET") <ide> .withField("defaultCharset") <ide> .withConstructor(TypeReference.listOf(List.class, boolean.class, MimeType.class), ExecutableMode.INTROSPECT) <del> .withMethod("setDefaultCharset", TypeReference.listOf(Charset.class)) <add> .withMethod("setDefaultCharset", TypeReference.listOf(Charset.class), ExecutableMode.INVOKE) <ide> .withMethod("getDefaultCharset", Collections.emptyList(), ExecutableMode.INTROSPECT)); <ide> generator.write(hints); <ide> assertEquals(""" <ide><path>spring-core/src/test/java/org/springframework/aot/nativex/ReflectionHintsWriterTests.java <ide> void one() throws JSONException { <ide> .withField("DEFAULT_CHARSET") <ide> .withField("defaultCharset") <ide> .withConstructor(TypeReference.listOf(List.class, boolean.class, MimeType.class), ExecutableMode.INTROSPECT) <del> .withMethod("setDefaultCharset", List.of(TypeReference.of(Charset.class))) <add> .withMethod("setDefaultCharset", List.of(TypeReference.of(Charset.class)), ExecutableMode.INVOKE) <ide> .withMethod("getDefaultCharset", Collections.emptyList(), ExecutableMode.INTROSPECT)); <ide> assertEquals(""" <ide> [ <ide><path>spring-orm/src/main/java/org/springframework/orm/jpa/support/InjectionCodeGenerator.java <ide> import java.lang.reflect.Method; <ide> <ide> import org.springframework.aot.generate.AccessVisibility; <add>import org.springframework.aot.hint.ExecutableMode; <ide> import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.javapoet.CodeBlock; <ide> import org.springframework.util.Assert; <ide> private CodeBlock generateMethodInjectionCode(Method method, String instanceVari <ide> AccessVisibility visibility = AccessVisibility.forMember(method); <ide> if (visibility == AccessVisibility.PRIVATE <ide> || visibility == AccessVisibility.PROTECTED) { <del> this.hints.reflection().registerMethod(method); <add> this.hints.reflection().registerMethod(method, ExecutableMode.INVOKE); <ide> code.addStatement("$T method = $T.findMethod($T.class, $S, $T.class)", <ide> Method.class, ReflectionUtils.class, method.getDeclaringClass(), <ide> method.getName(), method.getParameterTypes()[0]);
14
Javascript
Javascript
use common/fixtures in test-https-agent
ce33cffbcb9370258a516b349aec4b8f772a342d
<ide><path>test/parallel/test-https-agent.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <add> <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <add>const fixtures = require('../common/fixtures'); <ide> const assert = require('assert'); <ide> const https = require('https'); <del>const fs = require('fs'); <ide> <ide> const options = { <del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`), <del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`) <add> key: fixtures.readKey('agent1-key.pem'), <add> cert: fixtures.readKey('agent1-cert.pem') <ide> }; <ide> <ide>
1
Java
Java
use stringbuilder for complex string concatenation
32b689a9947823427a01899d5a310c9435ee78d2
<ide><path>spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java <ide> protected Object getPropertyValue(PropertyTokenHolder tokens) throws BeansExcept <ide> "property path '" + propertyName + "': returned null"); <ide> } <ide> } <del> String indexedPropertyName = tokens.actualName; <add> StringBuilder indexedPropertyName = new StringBuilder(tokens.actualName); <ide> // apply indexes and map keys <ide> for (int i = 0; i < tokens.keys.length; i++) { <ide> String key = tokens.keys[i]; <ide> protected Object getPropertyValue(PropertyTokenHolder tokens) throws BeansExcept <ide> } <ide> else if (value.getClass().isArray()) { <ide> int index = Integer.parseInt(key); <del> value = growArrayIfNecessary(value, index, indexedPropertyName); <add> value = growArrayIfNecessary(value, index, indexedPropertyName.toString()); <ide> value = Array.get(value, index); <ide> } <ide> else if (value instanceof List) { <ide> int index = Integer.parseInt(key); <ide> List<Object> list = (List<Object>) value; <del> growCollectionIfNecessary(list, index, indexedPropertyName, ph, i + 1); <add> growCollectionIfNecessary(list, index, indexedPropertyName.toString(), ph, i + 1); <ide> value = list.get(index); <ide> } <ide> else if (value instanceof Set) { <ide> else if (value instanceof Map) { <ide> "Property referenced in indexed property path '" + propertyName + <ide> "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); <ide> } <del> indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX; <add> indexedPropertyName.append(PROPERTY_KEY_PREFIX).append(key).append(PROPERTY_KEY_SUFFIX); <ide> } <ide> } <ide> return value; <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataContext.java <ide> public Map<String, Object> matchInParameterValuesWithCallParameters(SqlParameter <ide> public String createCallString() { <ide> Assert.state(this.metaDataProvider != null, "No CallMetaDataProvider available"); <ide> <del> String callString; <add> StringBuilder callString; <ide> int parameterCount = 0; <ide> String catalogNameToUse; <ide> String schemaNameToUse; <ide> public String createCallString() { <ide> <ide> String procedureNameToUse = this.metaDataProvider.procedureNameToUse(getProcedureName()); <ide> if (isFunction() || isReturnValueRequired()) { <del> callString = "{? = call " + <del> (StringUtils.hasLength(catalogNameToUse) ? catalogNameToUse + "." : "") + <del> (StringUtils.hasLength(schemaNameToUse) ? schemaNameToUse + "." : "") + <del> procedureNameToUse + "("; <add> callString = new StringBuilder().append("{? = call "). <add> append(StringUtils.hasLength(catalogNameToUse) ? catalogNameToUse + "." : ""). <add> append(StringUtils.hasLength(schemaNameToUse) ? schemaNameToUse + "." : ""). <add> append(procedureNameToUse).append("("); <ide> parameterCount = -1; <ide> } <ide> else { <del> callString = "{call " + <del> (StringUtils.hasLength(catalogNameToUse) ? catalogNameToUse + "." : "") + <del> (StringUtils.hasLength(schemaNameToUse) ? schemaNameToUse + "." : "") + <del> procedureNameToUse + "("; <add> callString = new StringBuilder().append("{call "). <add> append(StringUtils.hasLength(catalogNameToUse) ? catalogNameToUse + "." : ""). <add> append(StringUtils.hasLength(schemaNameToUse) ? schemaNameToUse + "." : ""). <add> append(procedureNameToUse).append("("); <ide> } <ide> <ide> for (SqlParameter parameter : this.callParameters) { <ide> if (!(parameter.isResultsParameter())) { <ide> if (parameterCount > 0) { <del> callString += ", "; <add> callString.append(", "); <ide> } <ide> if (parameterCount >= 0) { <del> callString += createParameterBinding(parameter); <add> callString.append(createParameterBinding(parameter)); <ide> } <ide> parameterCount++; <ide> } <ide> } <del> callString += ")}"; <add> callString.append(")}"); <ide> <del> return callString; <add> return callString.toString(); <ide> } <ide> <ide> /**
2
Python
Python
expand tasks in mapped group at run time
31f34e992828cc6ce28b265f08fc25a392887707
<ide><path>airflow/models/abstractoperator.py <ide> from airflow.compat.functools import cache, cached_property <ide> from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException <add>from airflow.models.expandinput import NotFullyPopulated <ide> from airflow.models.taskmixin import DAGNode <ide> from airflow.utils.context import Context <ide> from airflow.utils.helpers import render_template_as_native, render_template_to_string <ide> from airflow.utils.log.logging_mixin import LoggingMixin <ide> from airflow.utils.mixins import ResolveMixin <ide> from airflow.utils.session import NEW_SESSION, provide_session <add>from airflow.utils.state import State, TaskInstanceState <ide> from airflow.utils.task_group import MappedTaskGroup <ide> from airflow.utils.trigger_rule import TriggerRule <ide> from airflow.utils.weight_rule import WeightRule <ide> def get_mapped_ti_count(self, run_id: str, *, session: Session) -> int: <ide> counts = (g.get_mapped_ti_count(run_id, session=session) for g in mapped_task_groups) <ide> return functools.reduce(operator.mul, counts) <ide> <add> def expand_mapped_task(self, run_id: str, *, session: Session) -> tuple[Sequence[TaskInstance], int]: <add> """Create the mapped task instances for mapped task. <add> <add> :raise NotMapped: If this task does not need expansion. <add> :return: The newly created mapped task instances (if any) in ascending <add> order by map index, and the maximum map index value. <add> """ <add> from sqlalchemy import func, or_ <add> <add> from airflow.models.baseoperator import BaseOperator <add> from airflow.models.mappedoperator import MappedOperator <add> from airflow.models.taskinstance import TaskInstance <add> from airflow.settings import task_instance_mutation_hook <add> <add> if not isinstance(self, (BaseOperator, MappedOperator)): <add> raise RuntimeError(f"cannot expand unrecognized operator type {type(self).__name__}") <add> <add> try: <add> total_length: int | None = self.get_mapped_ti_count(run_id, session=session) <add> except NotFullyPopulated as e: <add> # It's possible that the upstream tasks are not yet done, but we <add> # don't have upstream of upstreams in partial DAGs (possible in the <add> # mini-scheduler), so we ignore this exception. <add> if not self.dag or not self.dag.partial: <add> self.log.error( <add> "Cannot expand %r for run %s; missing upstream values: %s", <add> self, <add> run_id, <add> sorted(e.missing), <add> ) <add> total_length = None <add> <add> state: TaskInstanceState | None = None <add> unmapped_ti: TaskInstance | None = ( <add> session.query(TaskInstance) <add> .filter( <add> TaskInstance.dag_id == self.dag_id, <add> TaskInstance.task_id == self.task_id, <add> TaskInstance.run_id == run_id, <add> TaskInstance.map_index == -1, <add> or_(TaskInstance.state.in_(State.unfinished), TaskInstance.state.is_(None)), <add> ) <add> .one_or_none() <add> ) <add> <add> all_expanded_tis: list[TaskInstance] = [] <add> <add> if unmapped_ti: <add> # The unmapped task instance still exists and is unfinished, i.e. we <add> # haven't tried to run it before. <add> if total_length is None: <add> # If the DAG is partial, it's likely that the upstream tasks <add> # are not done yet, so the task can't fail yet. <add> if not self.dag or not self.dag.partial: <add> unmapped_ti.state = TaskInstanceState.UPSTREAM_FAILED <add> indexes_to_map: Iterable[int] = () <add> elif total_length < 1: <add> # If the upstream maps this to a zero-length value, simply mark <add> # the unmapped task instance as SKIPPED (if needed). <add> self.log.info( <add> "Marking %s as SKIPPED since the map has %d values to expand", <add> unmapped_ti, <add> total_length, <add> ) <add> unmapped_ti.state = TaskInstanceState.SKIPPED <add> indexes_to_map = () <add> else: <add> # Otherwise convert this into the first mapped index, and create <add> # TaskInstance for other indexes. <add> unmapped_ti.map_index = 0 <add> self.log.debug("Updated in place to become %s", unmapped_ti) <add> all_expanded_tis.append(unmapped_ti) <add> indexes_to_map = range(1, total_length) <add> state = unmapped_ti.state <add> elif not total_length: <add> # Nothing to fixup. <add> indexes_to_map = () <add> else: <add> # Only create "missing" ones. <add> current_max_mapping = ( <add> session.query(func.max(TaskInstance.map_index)) <add> .filter( <add> TaskInstance.dag_id == self.dag_id, <add> TaskInstance.task_id == self.task_id, <add> TaskInstance.run_id == run_id, <add> ) <add> .scalar() <add> ) <add> indexes_to_map = range(current_max_mapping + 1, total_length) <add> <add> for index in indexes_to_map: <add> # TODO: Make more efficient with bulk_insert_mappings/bulk_save_mappings. <add> ti = TaskInstance(self, run_id=run_id, map_index=index, state=state) <add> self.log.debug("Expanding TIs upserted %s", ti) <add> task_instance_mutation_hook(ti) <add> ti = session.merge(ti) <add> ti.refresh_from_task(self) # session.merge() loses task information. <add> all_expanded_tis.append(ti) <add> <add> # Coerce the None case to 0 -- these two are almost treated identically, <add> # except the unmapped ti (if exists) is marked to different states. <add> total_expanded_ti_count = total_length or 0 <add> <add> # Any (old) task instances with inapplicable indexes (>= the total <add> # number we need) are set to "REMOVED". <add> session.query(TaskInstance).filter( <add> TaskInstance.dag_id == self.dag_id, <add> TaskInstance.task_id == self.task_id, <add> TaskInstance.run_id == run_id, <add> TaskInstance.map_index >= total_expanded_ti_count, <add> ).update({TaskInstance.state: TaskInstanceState.REMOVED}) <add> <add> session.flush() <add> return all_expanded_tis, total_expanded_ti_count - 1 <add> <ide> def render_template_fields( <ide> self, <ide> context: Context, <ide><path>airflow/models/dagrun.py <ide> from airflow.models.abstractoperator import NotMapped <ide> from airflow.models.base import Base, StringID <ide> from airflow.models.expandinput import NotFullyPopulated <del>from airflow.models.mappedoperator import MappedOperator <ide> from airflow.models.taskinstance import TaskInstance as TI <ide> from airflow.models.tasklog import LogTemplate <ide> from airflow.stats import Stats <ide> def _get_ready_tis( <ide> finished_tis=finished_tis, <ide> ) <ide> <add> def _expand_mapped_task_if_needed(ti: TI) -> Iterable[TI] | None: <add> """Try to expand the ti, if needed. <add> <add> If the ti needs expansion, newly created task instances are <add> returned. The original ti is modified in-place and assigned the <add> ``map_index`` of 0. <add> <add> If the ti does not need expansion, either because the task is not <add> mapped, or has already been expanded, *None* is returned. <add> """ <add> if ti.map_index >= 0: # Already expanded, we're good. <add> return None <add> try: <add> expanded_tis, _ = ti.task.expand_mapped_task(self.run_id, session=session) <add> except NotMapped: # Not a mapped task, nothing needed. <add> return None <add> if expanded_tis: <add> assert expanded_tis[0] is ti <add> return expanded_tis[1:] <add> return () <add> <ide> # Check dependencies. <ide> expansion_happened = False <ide> for schedulable in itertools.chain(schedulable_tis, additional_tis): <ide> old_state = schedulable.state <ide> if not schedulable.are_dependencies_met(session=session, dep_context=dep_context): <ide> old_states[schedulable.key] = old_state <ide> continue <del> # If schedulable is from a mapped task, but not yet expanded, do it <del> # now. This is called in two places: First and ideally in the mini <del> # scheduler at the end of LocalTaskJob, and then as an "expansion of <del> # last resort" in the scheduler to ensure that the mapped task is <del> # correctly expanded before executed. <del> if schedulable.map_index < 0 and isinstance(schedulable.task, MappedOperator): <del> expanded_tis, _ = schedulable.task.expand_mapped_task(self.run_id, session=session) <del> if expanded_tis: <del> assert expanded_tis[0] is schedulable <del> additional_tis.extend(expanded_tis[1:]) <del> expansion_happened = True <add> # If schedulable is not yet expanded, try doing it now. This is <add> # called in two places: First and ideally in the mini scheduler at <add> # the end of LocalTaskJob, and then as an "expansion of last resort" <add> # in the scheduler to ensure that the mapped task is correctly <add> # expanded before executed. Also see _revise_map_indexes_if_mapped <add> # docstring for additional information. <add> if schedulable.map_index < 0: <add> new_tis = _expand_mapped_task_if_needed(schedulable) <add> if new_tis is not None: <add> additional_tis.extend(new_tis) <add> expansion_happened = True <ide> if schedulable.state in SCHEDULEABLE_STATES: <del> task = schedulable.task <del> if isinstance(task, MappedOperator): <del> # Ensure the task indexes are complete <del> created = self._revise_mapped_task_indexes(task, session=session) <del> ready_tis.extend(created) <add> ready_tis.extend(self._revise_map_indexes_if_mapped(schedulable.task, session=session)) <ide> ready_tis.append(schedulable) <ide> <ide> # Check if any ti changed state <ide> def _create_task_instances( <ide> # TODO[HA]: We probably need to savepoint this so we can keep the transaction alive. <ide> session.rollback() <ide> <del> def _revise_mapped_task_indexes(self, task: MappedOperator, session: Session) -> Iterable[TI]: <del> """Check if task increased or reduced in length and handle appropriately""" <add> def _revise_map_indexes_if_mapped(self, task: Operator, *, session: Session) -> Iterator[TI]: <add> """Check if task increased or reduced in length and handle appropriately. <add> <add> Task instances that do not already exist are created and returned if <add> possible. Expansion only happens if all upstreams are ready; otherwise <add> we delay expansion to the "last resort". See comments at the call site <add> for more details. <add> """ <ide> from airflow.settings import task_instance_mutation_hook <ide> <ide> try: <ide> total_length = task.get_mapped_ti_count(self.run_id, session=session) <del> except NotFullyPopulated: # Upstreams not ready, don't need to revise this yet. <del> return [] <add> except NotMapped: <add> return # Not a mapped task, don't need to do anything. <add> except NotFullyPopulated: <add> return # Upstreams not ready, don't need to revise this yet. <ide> <ide> query = session.query(TI.map_index).filter( <ide> TI.dag_id == self.dag_id, <ide> TI.task_id == task.task_id, <ide> TI.run_id == self.run_id, <ide> ) <ide> existing_indexes = {i for (i,) in query} <del> missing_indexes = set(range(total_length)).difference(existing_indexes) <add> <ide> removed_indexes = existing_indexes.difference(range(total_length)) <del> created_tis = [] <del> <del> if missing_indexes: <del> for index in missing_indexes: <del> ti = TI(task, run_id=self.run_id, map_index=index, state=None) <del> self.log.debug("Expanding TIs upserted %s", ti) <del> task_instance_mutation_hook(ti) <del> ti = session.merge(ti) <del> ti.refresh_from_task(task) <del> session.flush() <del> created_tis.append(ti) <del> elif removed_indexes: <add> if removed_indexes: <ide> session.query(TI).filter( <ide> TI.dag_id == self.dag_id, <ide> TI.task_id == task.task_id, <ide> TI.run_id == self.run_id, <ide> TI.map_index.in_(removed_indexes), <ide> ).update({TI.state: TaskInstanceState.REMOVED}) <ide> session.flush() <del> return created_tis <add> <add> for index in range(total_length): <add> if index in existing_indexes: <add> continue <add> ti = TI(task, run_id=self.run_id, map_index=index, state=None) <add> self.log.debug("Expanding TIs upserted %s", ti) <add> task_instance_mutation_hook(ti) <add> ti = session.merge(ti) <add> ti.refresh_from_task(task) <add> session.flush() <add> yield ti <ide> <ide> @staticmethod <ide> def get_run(session: Session, dag_id: str, execution_date: datetime) -> DagRun | None: <ide><path>airflow/models/expandinput.py <ide> if TYPE_CHECKING: <ide> from sqlalchemy.orm import Session <ide> <add> from airflow.models.operator import Operator <ide> from airflow.models.xcom_arg import XComArg <ide> <ide> ExpandInput = Union["DictOfListsExpandInput", "ListOfDictsExpandInput"] <ide> def get_task_map_length(self, run_id: str, *, session: Session) -> int | None: <ide> # This simply marks the value as un-expandable at parse-time. <ide> return None <ide> <add> def iter_references(self) -> Iterable[tuple[Operator, str]]: <add> yield from self._input.iter_references() <add> <ide> @provide_session <ide> def resolve(self, context: Context, *, session: Session = NEW_SESSION) -> Any: <ide> data, _ = self._input.resolve(context, session=session) <ide> def _find_index_for_this_field(index: int) -> int: <ide> return k, v <ide> raise IndexError(f"index {map_index} is over mapped length") <ide> <add> def iter_references(self) -> Iterable[tuple[Operator, str]]: <add> from airflow.models.xcom_arg import XComArg <add> <add> for x in self.value.values(): <add> if isinstance(x, XComArg): <add> yield from x.iter_references() <add> <ide> def resolve(self, context: Context, session: Session) -> tuple[Mapping[str, Any], set[int]]: <ide> data = {k: self._expand_mapped_field(k, v, context, session=session) for k, v in self.value.items()} <ide> literal_keys = {k for k, _ in self._iter_parse_time_resolved_kwargs()} <ide> def get_total_map_length(self, run_id: str, *, session: Session) -> int: <ide> raise NotFullyPopulated({"expand_kwargs() argument"}) <ide> return length <ide> <add> def iter_references(self) -> Iterable[tuple[Operator, str]]: <add> from airflow.models.xcom_arg import XComArg <add> <add> if isinstance(self.value, XComArg): <add> yield from self.value.iter_references() <add> else: <add> for x in self.value: <add> if isinstance(x, XComArg): <add> yield from x.iter_references() <add> <ide> def resolve(self, context: Context, session: Session) -> tuple[Mapping[str, Any], set[int]]: <ide> map_index = context["ti"].map_index <ide> if map_index < 0: <ide><path>airflow/models/mappedoperator.py <ide> <ide> import attr <ide> import pendulum <del>from sqlalchemy import func, or_ <ide> from sqlalchemy.orm.session import Session <ide> <ide> from airflow import settings <ide> DictOfListsExpandInput, <ide> ExpandInput, <ide> ListOfDictsExpandInput, <del> NotFullyPopulated, <ide> OperatorExpandArgument, <ide> OperatorExpandKwargsArgument, <ide> is_mappable, <ide> from airflow.utils.context import Context, context_update_for_unmapped <ide> from airflow.utils.helpers import is_container, prevent_duplicates <ide> from airflow.utils.operator_resources import Resources <del>from airflow.utils.state import State, TaskInstanceState <ide> from airflow.utils.trigger_rule import TriggerRule <ide> from airflow.utils.types import NOTSET <ide> <ide> from airflow.models.baseoperator import BaseOperator, BaseOperatorLink <ide> from airflow.models.dag import DAG <ide> from airflow.models.operator import Operator <del> from airflow.models.taskinstance import TaskInstance <ide> from airflow.models.xcom_arg import XComArg <ide> from airflow.utils.task_group import TaskGroup <ide> <ide> def _get_specified_expand_input(self) -> ExpandInput: <ide> """Input received from the expand call on the operator.""" <ide> return getattr(self, self._expand_input_attr) <ide> <del> def expand_mapped_task(self, run_id: str, *, session: Session) -> tuple[Sequence[TaskInstance], int]: <del> """Create the mapped task instances for mapped task. <del> <del> :return: The newly created mapped TaskInstances (if any) in ascending order by map index, and the <del> maximum map_index. <del> """ <del> from airflow.models.taskinstance import TaskInstance <del> from airflow.settings import task_instance_mutation_hook <del> <del> total_length: int | None <del> try: <del> total_length = self._get_specified_expand_input().get_total_map_length(run_id, session=session) <del> except NotFullyPopulated as e: <del> total_length = None <del> # partial dags comes from the mini scheduler. It's <del> # possible that the upstream tasks are not yet done, <del> # but we don't have upstream of upstreams in partial dags, <del> # so we ignore this exception. <del> if not self.dag or not self.dag.partial: <del> self.log.error( <del> "Cannot expand %r for run %s; missing upstream values: %s", <del> self, <del> run_id, <del> sorted(e.missing), <del> ) <del> <del> state: TaskInstanceState | None = None <del> unmapped_ti: TaskInstance | None = ( <del> session.query(TaskInstance) <del> .filter( <del> TaskInstance.dag_id == self.dag_id, <del> TaskInstance.task_id == self.task_id, <del> TaskInstance.run_id == run_id, <del> TaskInstance.map_index == -1, <del> or_(TaskInstance.state.in_(State.unfinished), TaskInstance.state.is_(None)), <del> ) <del> .one_or_none() <del> ) <del> <del> all_expanded_tis: list[TaskInstance] = [] <del> <del> if unmapped_ti: <del> # The unmapped task instance still exists and is unfinished, i.e. we <del> # haven't tried to run it before. <del> if total_length is None: <del> if self.dag and self.dag.partial: <del> # If the DAG is partial, it's likely that the upstream tasks <del> # are not done yet, so we do nothing <del> indexes_to_map: Iterable[int] = () <del> else: <del> # If the map length cannot be calculated (due to unavailable <del> # upstream sources), fail the unmapped task. <del> unmapped_ti.state = TaskInstanceState.UPSTREAM_FAILED <del> indexes_to_map = () <del> elif total_length < 1: <del> # If the upstream maps this to a zero-length value, simply mark <del> # the unmapped task instance as SKIPPED (if needed). <del> self.log.info( <del> "Marking %s as SKIPPED since the map has %d values to expand", <del> unmapped_ti, <del> total_length, <del> ) <del> unmapped_ti.state = TaskInstanceState.SKIPPED <del> indexes_to_map = () <del> else: <del> # Otherwise convert this into the first mapped index, and create <del> # TaskInstance for other indexes. <del> unmapped_ti.map_index = 0 <del> self.log.debug("Updated in place to become %s", unmapped_ti) <del> all_expanded_tis.append(unmapped_ti) <del> indexes_to_map = range(1, total_length) <del> state = unmapped_ti.state <del> elif not total_length: <del> # Nothing to fixup. <del> indexes_to_map = () <del> else: <del> # Only create "missing" ones. <del> current_max_mapping = ( <del> session.query(func.max(TaskInstance.map_index)) <del> .filter( <del> TaskInstance.dag_id == self.dag_id, <del> TaskInstance.task_id == self.task_id, <del> TaskInstance.run_id == run_id, <del> ) <del> .scalar() <del> ) <del> indexes_to_map = range(current_max_mapping + 1, total_length) <del> <del> for index in indexes_to_map: <del> # TODO: Make more efficient with bulk_insert_mappings/bulk_save_mappings. <del> ti = TaskInstance(self, run_id=run_id, map_index=index, state=state) <del> self.log.debug("Expanding TIs upserted %s", ti) <del> task_instance_mutation_hook(ti) <del> ti = session.merge(ti) <del> ti.refresh_from_task(self) # session.merge() loses task information. <del> all_expanded_tis.append(ti) <del> <del> # Coerce the None case to 0 -- these two are almost treated identically, <del> # except the unmapped ti (if exists) is marked to different states. <del> total_expanded_ti_count = total_length or 0 <del> <del> # Set to "REMOVED" any (old) TaskInstances with map indices greater <del> # than the current map value <del> session.query(TaskInstance).filter( <del> TaskInstance.dag_id == self.dag_id, <del> TaskInstance.task_id == self.task_id, <del> TaskInstance.run_id == run_id, <del> TaskInstance.map_index >= total_expanded_ti_count, <del> ).update({TaskInstance.state: TaskInstanceState.REMOVED}) <del> <del> session.flush() <del> return all_expanded_tis, total_expanded_ti_count - 1 <del> <ide> def prepare_for_execution(self) -> MappedOperator: <ide> # Since a mapped operator cannot be used for execution, and an unmapped <ide> # BaseOperator needs to be created later (see render_template_fields), <ide> def iter_mapped_dependencies(self) -> Iterator[Operator]: <ide> """Upstream dependencies that provide XComs used by this task for task mapping.""" <ide> from airflow.models.xcom_arg import XComArg <ide> <del> for ref in XComArg.iter_xcom_args(self._get_specified_expand_input()): <del> for operator, _ in ref.iter_references(): <del> yield operator <add> for operator, _ in XComArg.iter_xcom_references(self._get_specified_expand_input()): <add> yield operator <ide> <ide> @cache <ide> def get_parse_time_mapped_ti_count(self) -> int: <ide><path>airflow/models/param.py <ide> import json <ide> import logging <ide> import warnings <del>from typing import TYPE_CHECKING, Any, ItemsView, MutableMapping, ValuesView <add>from typing import TYPE_CHECKING, Any, ItemsView, Iterable, MutableMapping, ValuesView <ide> <ide> from airflow.exceptions import AirflowException, ParamValidationError, RemovedInAirflow3Warning <ide> from airflow.utils.context import Context <ide> def validate(self) -> dict[str, Any]: <ide> <ide> <ide> class DagParam(ResolveMixin): <del> """ <del> Class that represents a DAG run parameter & binds a simple Param object to a name within a DAG instance, <del> so that it can be resolved during the run time via ``{{ context }}`` dictionary. The ideal use case of <del> this class is to implicitly convert args passed to a method which is being decorated by ``@dag`` keyword. <add> """DAG run parameter reference. <add> <add> This binds a simple Param object to a name within a DAG instance, so that it <add> can be resolved during the runtime via the ``{{ context }}`` dictionary. The <add> ideal use case of this class is to implicitly convert args passed to a <add> method decorated by ``@dag``. <ide> <del> It can be used to parameterize your dags. You can overwrite its value by setting it on conf <del> when you trigger your DagRun. <add> It can be used to parameterize a DAG. You can overwrite its value by setting <add> it on conf when you trigger your DagRun. <ide> <del> This can also be used in templates by accessing ``{{context.params}}`` dictionary. <add> This can also be used in templates by accessing ``{{ context.params }}``. <ide> <ide> **Example**: <ide> <ide> def __init__(self, current_dag: DAG, name: str, default: Any = NOTSET): <ide> self._name = name <ide> self._default = default <ide> <add> def iter_references(self) -> Iterable[tuple[Operator, str]]: <add> return () <add> <ide> def resolve(self, context: Context) -> Any: <ide> """Pull DagParam value from DagRun context. This method is run during ``op.execute()``.""" <ide> with contextlib.suppress(KeyError): <ide><path>airflow/models/xcom_arg.py <ide> def __new__(cls, *args, **kwargs) -> XComArg: <ide> return super().__new__(cls) <ide> <ide> @staticmethod <del> def iter_xcom_args(arg: Any) -> Iterator[XComArg]: <del> """Return XComArg instances in an arbitrary value. <add> def iter_xcom_references(arg: Any) -> Iterator[tuple[Operator, str]]: <add> """Return XCom references in an arbitrary value. <ide> <ide> Recursively traverse ``arg`` and look for XComArg instances in any <ide> collection objects, and instances with ``template_fields`` set. <ide> """ <del> if isinstance(arg, XComArg): <del> yield arg <add> if isinstance(arg, ResolveMixin): <add> yield from arg.iter_references() <ide> elif isinstance(arg, (tuple, set, list)): <ide> for elem in arg: <del> yield from XComArg.iter_xcom_args(elem) <add> yield from XComArg.iter_xcom_references(elem) <ide> elif isinstance(arg, dict): <ide> for elem in arg.values(): <del> yield from XComArg.iter_xcom_args(elem) <add> yield from XComArg.iter_xcom_references(elem) <ide> elif isinstance(arg, AbstractOperator): <del> for elem in arg.template_fields: <del> yield from XComArg.iter_xcom_args(elem) <add> for attr in arg.template_fields: <add> yield from XComArg.iter_xcom_references(getattr(arg, attr)) <ide> <ide> @staticmethod <ide> def apply_upstream_relationship(op: Operator, arg: Any): <ide> def apply_upstream_relationship(op: Operator, arg: Any): <ide> collections objects and classes decorated with ``template_fields``), and <ide> sets the relationship to ``op`` on any found. <ide> """ <del> for ref in XComArg.iter_xcom_args(arg): <del> for operator, _ in ref.iter_references(): <del> op.set_upstream(operator) <add> for operator, _ in XComArg.iter_xcom_references(arg): <add> op.set_upstream(operator) <ide> <ide> @property <ide> def roots(self) -> list[DAGNode]: <ide> def _deserialize(cls, data: dict[str, Any], dag: DAG) -> XComArg: <ide> """ <ide> raise NotImplementedError() <ide> <del> def iter_references(self) -> Iterator[tuple[Operator, str]]: <del> """Iterate through (operator, key) references.""" <del> raise NotImplementedError() <del> <ide> def map(self, f: Callable[[Any], Any]) -> MapXComArg: <ide> return MapXComArg(self, [f]) <ide> <ide> def get_task_map_length(self, run_id: str, *, session: Session) -> int | None: <ide> def resolve(self, context: Context, session: Session = NEW_SESSION) -> Any: <ide> """Pull XCom value. <ide> <del> This should only be called during ``op.execute()`` in respectable context. <add> This should only be called during ``op.execute()`` with an appropriate <add> context (e.g. generated from ``TaskInstance.get_template_context()``). <add> Although the ``ResolveMixin`` parent mixin also has a ``resolve`` <add> protocol, this adds the optional ``session`` argument that some of the <add> subclasses need. <ide> <ide> :meta private: <ide> """ <ide><path>airflow/utils/mixins.py <ide> from airflow.configuration import conf <ide> from airflow.utils.context import Context <ide> <add>if typing.TYPE_CHECKING: <add> from airflow.models.operator import Operator <add> <ide> <ide> class MultiprocessingStartMethodMixin: <ide> """Convenience class to add support for different types of multiprocessing.""" <ide> def _get_multiprocessing_start_method(self) -> str: <ide> class ResolveMixin: <ide> """A runtime-resolved value.""" <ide> <add> def iter_references(self) -> typing.Iterable[tuple[Operator, str]]: <add> """Find underlying XCom references this contains. <add> <add> This is used by the DAG parser to recursively find task dependencies. <add> <add> :meta private: <add> """ <add> raise NotImplementedError <add> <ide> def resolve(self, context: Context) -> typing.Any: <add> """Resolve this value for runtime. <add> <add> :meta private: <add> """ <ide> raise NotImplementedError <ide><path>tests/models/test_dagrun.py <ide> def execute(self, context): <ide> ti.run() <ide> <ide> assert sorted(results) == expected <add> <add> <add>def test_mapped_task_group_expands(dag_maker, session): <add> with dag_maker(session=session): <add> <add> @task_group <add> def tg(x, y): <add> return MockOperator(task_id="task_2", arg1=x, arg2=y) <add> <add> task_1 = BaseOperator(task_id="task_1") <add> tg.expand(x=task_1.output, y=[1, 2, 3]) <add> <add> dr: DagRun = dag_maker.create_dagrun() <add> <add> # Not expanding task_2 yet since it depends on result from task_1. <add> decision = dr.task_instance_scheduling_decisions(session=session) <add> assert {(ti.task_id, ti.map_index, ti.state) for ti in decision.tis} == { <add> ("task_1", -1, None), <add> ("tg.task_2", -1, None), <add> } <add> <add> # Simulate task_1 execution to produce TaskMap. <add> (ti_1,) = decision.schedulable_tis <add> assert ti_1.task_id == "task_1" <add> ti_1.state = TaskInstanceState.SUCCESS <add> session.add(TaskMap.from_task_instance_xcom(ti_1, ["a", "b"])) <add> session.flush() <add> <add> # Now task_2 in mapped tagk group is expanded. <add> decision = dr.task_instance_scheduling_decisions(session=session) <add> assert {(ti.task_id, ti.map_index, ti.state) for ti in decision.schedulable_tis} == { <add> ("tg.task_2", 0, None), <add> ("tg.task_2", 1, None), <add> ("tg.task_2", 2, None), <add> ("tg.task_2", 3, None), <add> ("tg.task_2", 4, None), <add> ("tg.task_2", 5, None), <add> }
8
Go
Go
fix minor type
7724260224c69eeb948c75c247d4868256e5081a
<ide><path>registry/session.go <ide> func (r *Session) SearchRepositories(term string) (*SearchResults, error) { <ide> } <ide> defer res.Body.Close() <ide> if res.StatusCode != 200 { <del> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Unexepected status code %d", res.StatusCode), res) <add> return nil, utils.NewHTTPRequestError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res) <ide> } <ide> result := new(SearchResults) <ide> err = json.NewDecoder(res.Body).Decode(result)
1
Javascript
Javascript
fix broken link in blog page links
81864e1298223a0e2359df116eee80ad1bc843a6
<ide><path>website/core/BlogSidebar.js <ide> var BlogSidebar = React.createClass({ <ide> <div className="nav-docs-section"> <ide> <h3>Recent Posts</h3> <ide> <ul> <del> {MetadataBlog.files.map(function(post) { <add> {MetadataBlog.files.slice(0,10).map(function(post) { <ide> return ( <ide> <li key={post.path}> <ide> <a <ide><path>website/layout/BlogPageLayout.js <ide> var Site = require('Site'); <ide> <ide> var BlogPageLayout = React.createClass({ <ide> getPageURL: function(page) { <del> var url = '/jest/blog/'; <add> var url = '/react-native/blog/'; <ide> if (page > 0) { <ide> url += 'page' + (page + 1) + '/'; <ide> }
2
Ruby
Ruby
use arel to determine selection column
75ac9c4271df65b94b2a6862d87b1ec42f676efe
<ide><path>activerecord/lib/active_record/association_preload.rb <ide> def preload_belongs_to_association(records, reflection, preload_options={}) <ide> def find_associated_records(ids, reflection, preload_options) <ide> options = reflection.options <ide> table = reflection.klass.arel_table <del> table_name = reflection.klass.quoted_table_name <ide> <ide> conditions = [] <ide> <ide> def find_associated_records(ids, reflection, preload_options) <ide> conditions += append_conditions(reflection, preload_options) <ide> <ide> find_options = { <del> :select => preload_options[:select] || options[:select] || Arel.sql("#{table_name}.*"), <add> :select => preload_options[:select] || options[:select] || table[Arel.star], <ide> :include => preload_options[:include] || options[:include], <ide> :joins => options[:joins], <ide> :group => preload_options[:group] || options[:group],
1
Go
Go
reject null manifests
654f854faecb038cb5ff110e6705fe355f1c8159
<ide><path>daemon/images/image_exporter.go <ide> func (i *ImageService) ExportImage(names []string, outStream io.Writer) error { <ide> } <ide> <ide> // LoadImage uploads a set of images into the repository. This is the <del>// complement of ImageExport. The input stream is an uncompressed tar <add>// complement of ExportImage. The input stream is an uncompressed tar <ide> // ball containing images and metadata. <ide> func (i *ImageService) LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error { <ide> imageExporter := tarexport.NewTarExporter(i.imageStore, i.layerStores, i.referenceStore, i) <ide><path>image/tarexport/load.go <ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool) <ide> return err <ide> } <ide> <add> if err := validateManifest(manifest); err != nil { <add> return err <add> } <add> <ide> var parentLinks []parentLink <ide> var imageIDsStr string <ide> var imageRefCount int <ide> func checkCompatibleOS(imageOS string) error { <ide> <ide> return system.ValidatePlatform(p) <ide> } <add> <add>func validateManifest(manifest []manifestItem) error { <add> // a nil manifest usually indicates a bug, so don't just silently fail. <add> // if someone really needs to pass an empty manifest, they can pass []. <add> if manifest == nil { <add> return errors.New("invalid manifest, manifest cannot be null (but can be [])") <add> } <add> <add> return nil <add>} <ide><path>image/tarexport/load_test.go <add>package tarexport <add> <add>import ( <add> "testing" <add> <add> "gotest.tools/v3/assert" <add> is "gotest.tools/v3/assert/cmp" <add>) <add> <add>func TestValidateManifest(t *testing.T) { <add> cases := map[string]struct { <add> manifest []manifestItem <add> valid bool <add> errContains string <add> }{ <add> "nil": { <add> manifest: nil, <add> valid: false, <add> errContains: "manifest cannot be null", <add> }, <add> "non-nil": { <add> manifest: []manifestItem{}, <add> valid: true, <add> }, <add> } <add> <add> for name, tc := range cases { <add> t.Run(name, func(t *testing.T) { <add> err := validateManifest(tc.manifest) <add> if tc.valid { <add> assert.Check(t, is.Nil(err)) <add> } else { <add> assert.Check(t, is.ErrorContains(err, tc.errContains)) <add> } <add> }) <add> } <add>}
3
Go
Go
implement pullparent option with buildkit
7c1c8f1fe29c28ef62017d99a99eb1ec6be4513c
<ide><path>builder/builder-next/adapters/containerimage/pull.go <ide> import ( <ide> "golang.org/x/time/rate" <ide> ) <ide> <del>const preferLocal = true // FIXME: make this optional from the op <del> <ide> // SourceOpt is options for creating the image source <ide> type SourceOpt struct { <ide> SessionManager *session.Manager <ide> func (is *imageSource) resolveLocal(refStr string) ([]byte, error) { <ide> return img.RawJSON(), nil <ide> } <ide> <del>func (is *imageSource) ResolveImageConfig(ctx context.Context, ref string, opt gw.ResolveImageConfigOpt) (digest.Digest, []byte, error) { <del> if preferLocal { <del> dt, err := is.resolveLocal(ref) <del> if err == nil { <del> return "", dt, nil <del> } <del> } <del> <add>func (is *imageSource) resolveRemote(ctx context.Context, ref string, platform *ocispec.Platform) (digest.Digest, []byte, error) { <ide> type t struct { <ide> dgst digest.Digest <ide> dt []byte <ide> } <ide> res, err := is.g.Do(ctx, ref, func(ctx context.Context) (interface{}, error) { <del> dgst, dt, err := imageutil.Config(ctx, ref, is.getResolver(ctx), is.ContentStore, opt.Platform) <add> dgst, dt, err := imageutil.Config(ctx, ref, is.getResolver(ctx), is.ContentStore, platform) <ide> if err != nil { <ide> return nil, err <ide> } <ide> return &t{dgst: dgst, dt: dt}, nil <ide> }) <add> var typed *t <ide> if err != nil { <ide> return "", nil, err <ide> } <del> typed := res.(*t) <add> typed = res.(*t) <ide> return typed.dgst, typed.dt, nil <ide> } <ide> <add>func (is *imageSource) ResolveImageConfig(ctx context.Context, ref string, opt gw.ResolveImageConfigOpt) (digest.Digest, []byte, error) { <add> resolveMode, err := source.ParseImageResolveMode(opt.ResolveMode) <add> if err != nil { <add> return "", nil, err <add> } <add> switch resolveMode { <add> case source.ResolveModeForcePull: <add> dgst, dt, err := is.resolveRemote(ctx, ref, opt.Platform) <add> // TODO: pull should fallback to local in case of failure to allow offline behavior <add> // the fallback doesn't work currently <add> return dgst, dt, err <add> /* <add> if err == nil { <add> return dgst, dt, err <add> } <add> // fallback to local <add> dt, err = is.resolveLocal(ref) <add> return "", dt, err <add> */ <add> <add> case source.ResolveModeDefault: <add> // default == prefer local, but in the future could be smarter <add> fallthrough <add> case source.ResolveModePreferLocal: <add> dt, err := is.resolveLocal(ref) <add> if err == nil { <add> return "", dt, err <add> } <add> // fallback to remote <add> return is.resolveRemote(ctx, ref, opt.Platform) <add> } <add> // should never happen <add> return "", nil, fmt.Errorf("builder cannot resolve image %s: invalid mode %q", ref, opt.ResolveMode) <add>} <add> <ide> func (is *imageSource) Resolve(ctx context.Context, id source.Identifier) (source.SourceInstance, error) { <ide> imageIdentifier, ok := id.(*source.ImageIdentifier) <ide> if !ok { <ide> func (p *puller) resolveLocal() { <ide> } <ide> } <ide> <del> if preferLocal { <add> if p.src.ResolveMode == source.ResolveModeDefault || p.src.ResolveMode == source.ResolveModePreferLocal { <ide> dt, err := p.is.resolveLocal(p.src.Reference.String()) <ide> if err == nil { <ide> p.config = dt <ide> func (p *puller) resolve(ctx context.Context) error { <ide> resolveProgressDone(err) <ide> return <ide> } <del> <del> _, dt, err := p.is.ResolveImageConfig(ctx, ref.String(), gw.ResolveImageConfigOpt{Platform: &p.platform}) <add> _, dt, err := p.is.ResolveImageConfig(ctx, ref.String(), gw.ResolveImageConfigOpt{Platform: &p.platform, ResolveMode: resolveModeToString(p.src.ResolveMode)}) <ide> if err != nil { <ide> p.resolveErr = err <ide> resolveProgressDone(err) <ide> func cacheKeyFromConfig(dt []byte) digest.Digest { <ide> } <ide> return identity.ChainID(img.RootFS.DiffIDs) <ide> } <add> <add>// resolveModeToString is the equivalent of github.com/moby/buildkit/solver/llb.ResolveMode.String() <add>// FIXME: add String method on source.ResolveMode <add>func resolveModeToString(rm source.ResolveMode) string { <add> switch rm { <add> case source.ResolveModeDefault: <add> return "default" <add> case source.ResolveModeForcePull: <add> return "pull" <add> case source.ResolveModePreferLocal: <add> return "local" <add> } <add> return "" <add>} <ide><path>builder/builder-next/builder.go <ide> func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder. <ide> frontendAttrs["no-cache"] = "" <ide> } <ide> <add> if opt.Options.PullParent { <add> frontendAttrs["image-resolve-mode"] = "pull" <add> } else { <add> frontendAttrs["image-resolve-mode"] = "default" <add> } <add> <ide> if opt.Options.Platform != "" { <ide> // same as in newBuilder in builder/dockerfile.builder.go <ide> // TODO: remove once opt.Options.Platform is of type specs.Platform
2
Text
Text
update process.versions.modules documentation
f368eee19f3094510f3c410f0e01aa1cd2a5e82e
<ide><path>doc/api/process.md <ide> added: v0.2.0 <ide> * {Object} <ide> <ide> The `process.versions` property returns an object listing the version strings of <del>Node.js and its dependencies. <add>Node.js and its dependencies. In addition, `process.versions.modules` indicates <add>the current ABI version, which is increased whenever a C++ API changes. Node.js <add>will refuse to load native modules built for an older `modules` value. <ide> <ide> ```js <ide> console.log(process.versions);
1
PHP
PHP
check url as 'a' type record in dns instead 'mx'
ee347278e625b3d07cacc70ffa1747ee53542af3
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function validateActiveUrl($attribute, $value) <ide> { <ide> $url = str_replace(array('http://', 'https://', 'ftp://'), '', strtolower($value)); <ide> <del> return checkdnsrr($url); <add> return checkdnsrr($url, 'A'); <ide> } <ide> <ide> /**
1
Go
Go
remove some mkserverfromengine
fc2f998822699c0c7e22e4fc791d10c3b1ea1e53
<ide><path>integration/runtime_test.go <ide> func cleanup(eng *engine.Engine, t *testing.T) error { <ide> } <ide> for _, image := range images.Data { <ide> if image.Get("ID") != unitTestImageID { <del> mkServerFromEngine(eng, t).DeleteImage(image.Get("ID"), false) <add> eng.Job("image_delete", image.Get("ID")).Run() <ide> } <ide> } <ide> return nil <ide> func setupBaseImage() { <ide> if err := job.Run(); err != nil { <ide> log.Fatalf("Unable to create a runtime for tests: %s", err) <ide> } <del> srv := mkServerFromEngine(eng, log.New(os.Stderr, "", 0)) <ide> <add> job = eng.Job("inspect", unitTestImageName, "image") <add> img, _ := job.Stdout.AddEnv() <ide> // If the unit test is not found, try to download it. <del> if img, err := srv.ImageInspect(unitTestImageName); err != nil || img.ID != unitTestImageID { <add> if err := job.Run(); err != nil || img.Get("id") != unitTestImageID { <ide> // Retrieve the Image <ide> job = eng.Job("pull", unitTestImageName) <ide> job.Stdout.Add(utils.NopWriteCloser(os.Stdout)) <ide><path>integration/sorter_test.go <ide> package docker <ide> <ide> import ( <del> "github.com/dotcloud/docker" <add> "github.com/dotcloud/docker/engine" <ide> "testing" <ide> "time" <ide> ) <ide> <ide> func TestServerListOrderedImagesByCreationDate(t *testing.T) { <ide> eng := NewTestEngine(t) <ide> defer mkRuntimeFromEngine(eng, t).Nuke() <del> srv := mkServerFromEngine(eng, t) <ide> <del> if err := generateImage("", srv); err != nil { <add> if err := generateImage("", eng); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestServerListOrderedImagesByCreationDate(t *testing.T) { <ide> func TestServerListOrderedImagesByCreationDateAndTag(t *testing.T) { <ide> eng := NewTestEngine(t) <ide> defer mkRuntimeFromEngine(eng, t).Nuke() <del> srv := mkServerFromEngine(eng, t) <ide> <del> err := generateImage("bar", srv) <add> err := generateImage("bar", eng) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> time.Sleep(time.Second) <ide> <del> err = generateImage("zed", srv) <add> err = generateImage("zed", eng) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestServerListOrderedImagesByCreationDateAndTag(t *testing.T) { <ide> } <ide> } <ide> <del>func generateImage(name string, srv *docker.Server) error { <add>func generateImage(name string, eng *engine.Engine) error { <ide> archive, err := fakeTar() <ide> if err != nil { <ide> return err <ide> } <del> job := srv.Eng.Job("import", "-", "repo", name) <add> job := eng.Job("import", "-", "repo", name) <ide> job.Stdin.Add(archive) <ide> job.SetenvBool("json", true) <ide> return job.Run()
2
Go
Go
log start and end of filesystem creation
a489e685c0d17455463945316cfe366e4e65dca6
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func determineDefaultFS() string { <ide> return "ext4" <ide> } <ide> <del>func (devices *DeviceSet) createFilesystem(info *devInfo) error { <add>func (devices *DeviceSet) createFilesystem(info *devInfo) (err error) { <ide> devname := info.DevName() <ide> <ide> args := []string{} <ide> func (devices *DeviceSet) createFilesystem(info *devInfo) error { <ide> <ide> args = append(args, devname) <ide> <del> var err error <del> <ide> if devices.filesystem == "" { <ide> devices.filesystem = determineDefaultFS() <ide> } <ide> <add> logrus.Infof("devmapper: Creating filesystem %s on device %s", devices.filesystem, info.Name()) <add> defer func() { <add> if err != nil { <add> logrus.Infof("devmapper: Error while creating filesystem %s on device %s: %v", devices.filesystem, info.Name(), err) <add> } else { <add> logrus.Infof("devmapper: Successfully created filesystem %s on device %s", devices.filesystem, info.Name()) <add> } <add> }() <add> <ide> switch devices.filesystem { <ide> case "xfs": <ide> err = exec.Command("mkfs.xfs", args...).Run() <ide> func (devices *DeviceSet) createFilesystem(info *devInfo) error { <ide> default: <ide> err = fmt.Errorf("Unsupported filesystem type %s", devices.filesystem) <ide> } <del> if err != nil { <del> return err <del> } <del> <del> return nil <add> return <ide> } <ide> <ide> func (devices *DeviceSet) migrateOldMetaData() error {
1
Text
Text
add airflow users for optum
4338dbdc07d510251b0c826bf1edeb31c4f613af
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> 1. [OfferUp](https://offerupnow.com) <ide> 1. [OneFineStay](https://www.onefinestay.com) [[@slangwald](https://github.com/slangwald)] <ide> 1. [Open Knowledge International](https://okfn.org) [@vitorbaptista](https://github.com/vitorbaptista) <del>1. [Optum](https://www.optum.com/) - [UnitedHealthGroup](https://www.unitedhealthgroup.com/) [[@hiteshrd](https://github.com/hiteshrd)] <add>1. [Optum](https://www.optum.com/) - [UnitedHealthGroup](https://www.unitedhealthgroup.com/) [[@fhoda](https://github.com/fhoda), [@ianstanton](https://github.com/ianstanton), [@nilaybhatt](https://github.com/NilayBhatt),[@hiteshrd](https://github.com/hiteshrd)] <ide> 1. [Outcome Health](https://www.outcomehealth.com/) [[@mikethoun](https://github.com/mikethoun), [@rolandotribo](https://github.com/rolandotribo)] <ide> 1. [Overstock](https://www.github.com/overstock) [[@mhousley](https://github.com/mhousley) & [@mct0006](https://github.com/mct0006)] <ide> 1. [OVH](https://www.ovh.com) [[@ncrocfer](https://github.com/ncrocfer) & [@anthonyolea](https://github.com/anthonyolea)]
1
Text
Text
add 2 colab notebooks
3cc2c2a1509944797d6e0cd2def31706469df53a
<ide><path>notebooks/README.md <ide> Pull Request so it can be included under the Community notebooks. <ide> |:----------|:-------------|:-------------|------:| <ide> | [Train T5 on TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | How to train T5 on SQUAD with Transformers and Nlp | [Suraj Patil](https://github.com/patil-suraj) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) | <ide> | [Fine-tune T5 for Classification and Multiple Choice](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | How to fine-tune T5 for classification and multiple choice tasks using a text-to-text format with PyTorch Lightning | [Suraj Patil](https://github.com/patil-suraj) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | <del>| [Fine-tune DialoGPT on New Datasets and Languages](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | How to fine-tune the DialoGPT model on a new dataset for open-dialog conversational chatbots | [Nathan Cooper](https://github.com/ncoop57) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) <del>| [Long Sequence Modeling with Reformer](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | How to train on sequences as long as 500,000 tokens with Reformer | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) <add>| [Fine-tune DialoGPT on New Datasets and Languages](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | How to fine-tune the DialoGPT model on a new dataset for open-dialog conversational chatbots | [Nathan Cooper](https://github.com/ncoop57) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | <add>| [Long Sequence Modeling with Reformer](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | How to train on sequences as long as 500,000 tokens with Reformer | [Patrick von Platen](https://github.com/patrickvonplaten) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | <ide> | [Fine-tune BART for Summarization](https://github.com/ohmeow/ohmeow_website/blob/master/_notebooks/2020-05-23-text-generation-with-blurr.ipynb) | How to fine-tune BART for summarization with fastai using blurr | [Wayde Gilliam](https://ohmeow.com/) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/_notebooks/2020-05-23-text-generation-with-blurr.ipynb) | <add>| [Fine-tune a pre-trained Transformer on anyone's tweets](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | How to generate tweets in the style of your favorite Twitter account by fine-tune a GPT-2 model | [Boris Dayma](https://github.com/borisdayma) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | <add>| [A Step by Step Guide to Tracking Hugging Face Model Performance](https://colab.research.google.com/drive/1NEiqNPhiouu2pPwDAVeFoN4-vTYMz9F8) | A quick tutorial for training NLP models with HuggingFace and & visualizing their performance with Weights & Biases | [Jack Morris](https://github.com/jxmorris12) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1NEiqNPhiouu2pPwDAVeFoN4-vTYMz9F8) |
1
Javascript
Javascript
prevent undefined ref in completion
392c70a8273e270b9a0b1d04905138733a6efaff
<ide><path>lib/repl.js <ide> function complete(line, callback) { <ide> }); <ide> var flat = new ArrayStream(); // make a new "input" stream <ide> var magic = new REPLServer('', flat); // make a nested REPL <add> replMap.set(magic, replMap.get(this)); <ide> magic.context = magic.createContext(); <ide> flat.run(tmp); // eval the flattened code <ide> // all this is only profitable if the nested REPL <ide> // does not have a bufferedCommand <ide> if (!magic.bufferedCommand) { <del> replMap.set(magic, replMap.get(this)); <ide> return magic.complete(line, callback); <ide> } <ide> } <ide><path>test/parallel/test-repl-tab-complete-crash.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const repl = require('repl'); <ide> <del>var referenceErrorCount = 0; <del> <del>common.ArrayStream.prototype.write = function(msg) { <del> if (msg.startsWith('ReferenceError: ')) { <del> referenceErrorCount++; <del> } <del>}; <add>common.ArrayStream.prototype.write = function(msg) {}; <ide> <ide> const putIn = new common.ArrayStream(); <ide> const testMe = repl.start('', putIn); <ide> <ide> // https://github.com/nodejs/node/issues/3346 <del>// Tab-completion for an undefined variable inside a function should report a <del>// ReferenceError. <add>// Tab-completion should be empty <ide> putIn.run(['.clear']); <ide> putIn.run(['function () {']); <del>testMe.complete('arguments.'); <add>testMe.complete('arguments.', common.mustCall((err, completions) => { <add> assert.strictEqual(err, null); <add> assert.deepStrictEqual(completions, [[], 'arguments.']); <add>})); <ide> <del>process.on('exit', function() { <del> assert.strictEqual(referenceErrorCount, 1); <del>}); <add>putIn.run(['.clear']); <add>putIn.run(['function () {']); <add>putIn.run(['undef;']); <add>testMe.complete('undef.', common.mustCall((err, completions) => { <add> assert.strictEqual(err, null); <add> assert.deepStrictEqual(completions, [[], 'undef.']); <add>}));
2
Javascript
Javascript
add offscreen component type
ed01fdacceba20ffd004f0eae05ee07a6bb6a690
<ide><path>packages/react-reconciler/src/ReactFiber.new.js <ide> import { <ide> FundamentalComponent, <ide> ScopeComponent, <ide> Block, <add> OffscreenComponent, <ide> } from './ReactWorkTags'; <ide> import getComponentName from 'shared/getComponentName'; <ide> <ide> import { <ide> REACT_FUNDAMENTAL_TYPE, <ide> REACT_SCOPE_TYPE, <ide> REACT_BLOCK_TYPE, <add> REACT_OFFSCREEN_TYPE, <ide> } from 'shared/ReactSymbols'; <ide> <ide> export type {Fiber}; <ide> export function createFiberFromTypeAndProps( <ide> expirationTime, <ide> key, <ide> ); <add> case REACT_OFFSCREEN_TYPE: <add> return createFiberFromOffscreen( <add> pendingProps, <add> mode, <add> expirationTime, <add> key, <add> ); <ide> default: { <ide> if (typeof type === 'object' && type !== null) { <ide> switch (type.$$typeof) { <ide> export function createFiberFromSuspenseList( <ide> return fiber; <ide> } <ide> <add>export function createFiberFromOffscreen( <add> pendingProps: any, <add> mode: TypeOfMode, <add> expirationTime: ExpirationTimeOpaque, <add> key: null | string, <add>) { <add> const fiber = createFiber(OffscreenComponent, pendingProps, key, mode); <add> // TODO: The OffscreenComponent fiber shouldn't have a type. It has a tag. <add> // This needs to be fixed in getComponentName so that it relies on the tag <add> // instead. <add> if (__DEV__) { <add> fiber.type = REACT_OFFSCREEN_TYPE; <add> } <add> fiber.elementType = REACT_OFFSCREEN_TYPE; <add> fiber.expirationTime_opaque = expirationTime; <add> return fiber; <add>} <add> <ide> export function createFiberFromText( <ide> content: string, <ide> mode: TypeOfMode, <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.new.js <ide> import { <ide> FundamentalComponent, <ide> ScopeComponent, <ide> Block, <add> OffscreenComponent, <ide> } from './ReactWorkTags'; <ide> import { <ide> NoEffect, <ide> function updateSimpleMemoComponent( <ide> ); <ide> } <ide> <add>function updateOffscreenComponent( <add> current: Fiber | null, <add> workInProgress: Fiber, <add> renderExpirationTime: ExpirationTimeOpaque, <add>) { <add> const nextChildren = workInProgress.pendingProps; <add> reconcileChildren( <add> current, <add> workInProgress, <add> nextChildren, <add> renderExpirationTime, <add> ); <add> return workInProgress.child; <add>} <add> <ide> function updateFragment( <ide> current: Fiber | null, <ide> workInProgress: Fiber, <ide> function beginWork( <ide> renderExpirationTime, <ide> ); <ide> } <add> case OffscreenComponent: { <add> return updateOffscreenComponent( <add> current, <add> workInProgress, <add> renderExpirationTime, <add> ); <add> } <ide> case SimpleMemoComponent: { <ide> return updateSimpleMemoComponent( <ide> current, <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js <ide> import { <ide> FundamentalComponent, <ide> ScopeComponent, <ide> Block, <add> OffscreenComponent, <ide> } from './ReactWorkTags'; <ide> import {NoMode, BlockingMode} from './ReactTypeOfMode'; <ide> import {Ref, Update, NoEffect, DidCapture} from './ReactSideEffectTags'; <ide> function completeWork( <ide> return null; <ide> } <ide> break; <add> case OffscreenComponent: <add> return null; <ide> } <ide> invariant( <ide> false, <ide><path>packages/react-reconciler/src/ReactWorkTags.js <ide> export type WorkTag = <ide> | 19 <ide> | 20 <ide> | 21 <del> | 22; <add> | 22 <add> | 23; <ide> <ide> export const FunctionComponent = 0; <ide> export const ClassComponent = 1; <ide> export const SuspenseListComponent = 19; <ide> export const FundamentalComponent = 20; <ide> export const ScopeComponent = 21; <ide> export const Block = 22; <add>export const OffscreenComponent = 23; <ide><path>packages/shared/ReactSymbols.js <ide> export let REACT_RESPONDER_TYPE = 0xead6; <ide> export let REACT_SCOPE_TYPE = 0xead7; <ide> export let REACT_OPAQUE_ID_TYPE = 0xeae0; <ide> export let REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; <add>export let REACT_OFFSCREEN_TYPE = 0xeae2; <ide> <ide> if (typeof Symbol === 'function' && Symbol.for) { <ide> const symbolFor = Symbol.for; <ide> if (typeof Symbol === 'function' && Symbol.for) { <ide> REACT_SCOPE_TYPE = symbolFor('react.scope'); <ide> REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); <ide> REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); <add> REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); <ide> } <ide> <ide> const MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
5
Javascript
Javascript
add __non_webpack_require__ to api
8e44685ac1d258160b615396003a6cdd802f7951
<ide><path>lib/APIPlugin.js <ide> var REPLACEMENTS = { <ide> __webpack_public_path__: "__webpack_require__.p", <ide> __webpack_modules__: "__webpack_require__.m", <ide> __webpack_chunk_load__: "__webpack_require__.e", <add> __non_webpack_require__: "require", <ide> "require.onError": "__webpack_require__.onError", <ide> }; <ide> var REPLACEMENT_TYPES = {
1
Java
Java
fix package cycle in @enablespringconfigured
5327a7a37d25b67ee2ae7d1ead2a3db6847767c0
<add><path>spring-aspects/src/main/java/org/springframework/context/annotation/EnableSpringConfigured.java <del><path>spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/EnableSpringConfigured.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2012 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> * limitations under the License. <ide> */ <ide> <del>package org.springframework.beans.factory.aspectj; <add>package org.springframework.context.annotation; <ide> <ide> import java.lang.annotation.Documented; <ide> import java.lang.annotation.ElementType; <ide> import org.springframework.context.annotation.Import; <ide> <ide> /** <del> * Signals the current application context to apply dependency injection to non-managed <del> * classes that are instantiated outside of the Spring bean factory (typically classes <del> * annotated with the @{@link org.springframework.beans.factory.annotation.Configurable <add> * Signals the current application context to apply dependency injection to <add> * non-managed classes that are instantiated outside of the Spring bean factory <add> * (typically classes annotated with the @ <add> * {@link org.springframework.beans.factory.annotation.Configurable <ide> * Configurable} annotation). <ide> * <del> * <p>Similar to functionality found in Spring's {@code <context:spring-configured>} XML <del> * element. Often used in conjunction with {@link <del> * org.springframework.context.annotation.EnableLoadTimeWeaving @EnableLoadTimeWeaving}. <add> * <p>Similar to functionality found in Spring's <add> * {@code <context:spring-configured>} XML element. Often used in conjunction <add> * with {@link org.springframework.context.annotation.EnableLoadTimeWeaving <add> * @EnableLoadTimeWeaving}. <ide> * <ide> * @author Chris Beams <ide> * @since 3.1 <add><path>spring-aspects/src/main/java/org/springframework/context/annotation/SpringConfiguredConfiguration.java <del><path>spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/SpringConfiguredConfiguration.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2012 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> * limitations under the License. <ide> */ <ide> <del>package org.springframework.beans.factory.aspectj; <add>package org.springframework.context.annotation; <ide> <add>import org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect; <ide> import org.springframework.beans.factory.config.BeanDefinition; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <add><path>spring-aspects/src/test/java/org/springframework/context/annotation/AnnotationBeanConfigurerTests.java <del><path>spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerTests.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2012 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> * limitations under the License. <ide> */ <ide> <del>package org.springframework.beans.factory.aspectj; <add>package org.springframework.context.annotation; <ide> <add>import org.springframework.beans.factory.aspectj.AbstractBeanConfigurerTests; <ide> import org.springframework.context.ConfigurableApplicationContext; <del>import org.springframework.context.annotation.AnnotationConfigApplicationContext; <del>import org.springframework.context.annotation.Configuration; <del>import org.springframework.context.annotation.ImportResource; <ide> <ide> /** <ide> * Tests that @EnableSpringConfigured properly registers an <del> * {@link AnnotationBeanConfigurerAspect}, just as does {@code <context:spring-configured>} <add> * {@link org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect}, just <add> * as does {@code <context:spring-configured>} <ide> * <ide> * @author Chris Beams <ide> * @since 3.1
3
Python
Python
use faster password hasher in sqlite tests
0819957eda318205e17591dccd81482701eab25c
<ide><path>tests/test_sqlite.py <ide> } <ide> <ide> SECRET_KEY = "django_tests_secret_key" <add># To speed up tests under SQLite we use the MD5 hasher as the default one. <add># This should not be needed under other databases, as the relative speedup <add># is only marginal there. <add>PASSWORD_HASHERS = ( <add> 'django.contrib.auth.hashers.MD5PasswordHasher', <add>)
1
Python
Python
clarify the python versions that flask supports
7368a164c7506046a4a0b0ce2113c2aaa7800087
<ide><path>setup.py <ide> def hello(): <ide> 'License :: OSI Approved :: BSD License', <ide> 'Operating System :: OS Independent', <ide> 'Programming Language :: Python', <add> 'Programming Language :: Python :: 2', <add> 'Programming Language :: Python :: 2.6', <add> 'Programming Language :: Python :: 2.7', <ide> 'Programming Language :: Python :: 3', <add> 'Programming Language :: Python :: 3.3', <add> 'Programming Language :: Python :: 3.4', <add> 'Programming Language :: Python :: 3.5', <ide> 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', <ide> 'Topic :: Software Development :: Libraries :: Python Modules' <ide> ],
1
Text
Text
fix a typo in console documentation
d96075c4b6fa35cb1d1f5b6ecf66cf3de82d5d12
<ide><path>doc/api/console.md <ide> added: v0.1.104 <ide> * `message` {any} <ide> * `...args` {any} <ide> <del>Prints to `stderr` the string `'Trace :'`, followed by the [`util.format()`][] <add>Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`][] <ide> formatted message and stack trace to the current position in the code. <ide> <ide> ```js
1
Python
Python
relax timetable clas validation
7d555d779dc83566d814a36946bd886c2e7468b3
<ide><path>airflow/serialization/serialized_objects.py <ide> def _encode_timetable(var: Timetable) -> Dict[str, Any]: <ide> """ <ide> timetable_class = type(var) <ide> importable_string = as_importable_string(timetable_class) <del> if _get_registered_timetable(importable_string) != timetable_class: <add> if _get_registered_timetable(importable_string) is None: <ide> raise _TimetableNotRegistered(importable_string) <ide> return {Encoding.TYPE: importable_string, Encoding.VAR: var.serialize()} <ide>
1
Text
Text
update proptypes documentation
ca02a068b87a36c727647af443a72ea7c92f46ca
<ide><path>docs/docs/05-reusable-components.md <ide> When designing interfaces, break down the common design elements (buttons, form <ide> <ide> ## Prop Validation <ide> <del>As your app grows it's helpful to ensure that your components are used correctly. We do this by allowing you to specify `propTypes`. `React.PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. When an invalid value is provided for a prop, an error will be thrown. Here is an example documenting the different validators provided: <add>As your app grows it's helpful to ensure that your components are used correctly. We do this by allowing you to specify `propTypes`. `React.PropTypes` exports a range of validators that can be used to make sure the data you receive is valid. When an invalid value is provided for a prop, a warning will be shown in the JavaScript console. Note that for performance reasons `propTypes` is only checked in development mode. Here is an example documenting the different validators provided: <ide> <ide> ```javascript <ide> React.createClass({ <ide> React.createClass({ <ide> // JS's instanceof operator. <ide> someClass: React.PropTypes.instanceOf(SomeClass), <ide> <del> // You can chain any of the above with isRequired to make sure an error is <del> // thrown if the prop isn't provided. <add> // You can chain any of the above with isRequired to make sure a warning is <add> // shown if the prop isn't provided. <ide> requiredFunc: React.PropTypes.func.isRequired <ide> <ide> // You can also specify a custom validator. <ide> customProp: function(props, propName, componentName) { <ide> if (!/matchme/.test(props[propName])) { <del> throw new Error('Validation failed!') <add> console.warn('Validation failed!'); <ide> } <ide> } <ide> },
1
Python
Python
add tests to encoder-decoder model
a88a0e4413d8de5ad235a211fb3b0326aadc5ce0
<ide><path>transformers/tests/modeling_common_test.py <ide> def ids_tensor(shape, vocab_size, rng=None, name=None): <ide> return torch.tensor(data=values, dtype=torch.long).view(shape).contiguous() <ide> <ide> <add>def floats_tensor(shape, scale=1.0, rng=None, name=None): <add> """Creates a random float32 tensor of the shape within the vocab size.""" <add> if rng is None: <add> rng = global_rng <add> <add> total_dims = 1 <add> for dim in shape: <add> total_dims *= dim <add> <add> values = [] <add> for _ in range(total_dims): <add> values.append(rng.random() * scale) <add> <add> return torch.tensor(data=values, dtype=torch.float).view(shape).contiguous() <add> <add> <ide> class ModelUtilsTest(unittest.TestCase): <ide> def test_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide><path>transformers/tests/modeling_encoder_decoder_test.py <add># coding=utf-8 <add># Copyright 2018 The Hugging Face Inc. Team <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add>import logging <add>import unittest <add>import pytest <add> <add>from transformers import is_torch_available <add> <add>if is_torch_available(): <add> from transformers import BertModel, BertForMaskedLM, Model2Model <add> from transformers.modeling_bert import BERT_PRETRAINED_MODEL_ARCHIVE_MAP <add>else: <add> pytestmark = pytest.mark.skip("Require Torch") <add> <add> <add>class EncoderDecoderModelTest(unittest.TestCase): <add> def test_model2model_from_pretrained(self): <add> logging.basicConfig(level=logging.INFO) <add> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> model = Model2Model.from_pretrained(model_name) <add> self.assertIsInstance(model.encoder, BertModel) <add> self.assertIsInstance(model.decoder, BertForMaskedLM) <add> self.assertEqual(model.decoder.config.is_decoder, True) <add> self.assertEqual(model.encoder.config.is_decoder, False) <add> <add> def test_model2model_from_pretrained_not_bert(self): <add> logging.basicConfig(level=logging.INFO) <add> with self.assertRaises(ValueError): <add> _ = Model2Model.from_pretrained('roberta') <add> <add> with self.assertRaises(ValueError): <add> _ = Model2Model.from_pretrained('distilbert') <add> <add> with self.assertRaises(ValueError): <add> _ = Model2Model.from_pretrained('does-not-exist') <add> <add> <add>if __name__ == "__main__": <add> unittest.main()
2
Ruby
Ruby
fix bug with parametrize when `locale` is passed
818437c3664039f7038364910fc4ac80450f36a2
<ide><path>activesupport/lib/active_support/inflector/transliterate.rb <ide> def transliterate(string, replacement = "?", locale: nil) <ide> # <ide> def parameterize(string, separator: "-", preserve_case: false, locale: nil) <ide> # Replace accented chars with their ASCII equivalents. <del> parameterized_string = transliterate(string, locale) <add> parameterized_string = transliterate(string, locale: locale) <ide> <ide> # Turn unwanted chars into the separator. <ide> parameterized_string.gsub!(/[^a-z0-9\-_]+/i, separator) <ide><path>activesupport/test/core_ext/string_ext_test.rb <ide> def test_string_parameterized_underscore_preserve_case <ide> end <ide> end <ide> <add> def test_parameterize_with_locale <add> word = "Fünf autos" <add> I18n.backend.store_translations(:de, i18n: { transliterate: { rule: { "ü" => "ue" } } }) <add> assert_equal("fuenf-autos", word.parameterize(locale: :de)) <add> end <add> <ide> def test_humanize <ide> UnderscoreToHuman.each do |underscore, human| <ide> assert_equal(human, underscore.humanize) <ide><path>activesupport/test/inflector_test.rb <ide> def test_parameterize_with_multi_character_separator <ide> end <ide> end <ide> <add> def test_parameterize_with_locale <add> word = "Fünf autos" <add> I18n.backend.store_translations(:de, i18n: { transliterate: { rule: { "ü" => "ue" } } }) <add> assert_equal("fuenf-autos", ActiveSupport::Inflector.parameterize(word, locale: :de)) <add> end <add> <ide> def test_classify <ide> ClassNameToTableName.each do |class_name, table_name| <ide> assert_equal(class_name, ActiveSupport::Inflector.classify(table_name)) <ide><path>activesupport/test/transliterate_test.rb <ide> def test_transliterate_should_work_with_custom_i18n_rules_and_uncomposed_utf8 <ide> I18n.locale = default_locale <ide> end <ide> <add> def test_transliterate_respects_the_locale_argument <add> char = [117, 776].pack("U*") # "ü" as ASCII "u" plus COMBINING DIAERESIS <add> I18n.backend.store_translations(:de, i18n: { transliterate: { rule: { "ü" => "ue" } } }) <add> assert_equal "ue", ActiveSupport::Inflector.transliterate(char, locale: :de) <add> end <add> <ide> def test_transliterate_should_allow_a_custom_replacement_char <ide> assert_equal "a*b", ActiveSupport::Inflector.transliterate("a索b", "*") <ide> end
4
Javascript
Javascript
handle editable region covering editor's top
3cfd80a8060d9f7189e6f171d1f9fa2dce41437a
<ide><path>client/src/templates/Challenges/classic/Editor.js <ide> class Editor extends Component { <ide> // the region it should cover instead. <ide> // TODO: DRY <ide> getLineAfterViewZone() { <del> return ( <del> this.data.model.getDecorationRange(this.data.startEditDecId) <del> .endLineNumber + 1 <del> ); <add> // TODO: abstract away the data, ids etc. <add> const range = this.data.model.getDecorationRange(this.data.startEditDecId); <add> // if the first decoration is missing, this implies the region reaches the <add> // start of the editor. <add> return range ? range.endLineNumber + 1 : 1; <ide> } <ide> <ide> getLineAfterEditableRegion() { <add> // TODO: handle the case that the editable region reaches the bottom of the <add> // editor <ide> return this.data.model.getDecorationRange(this.data.endEditDecId) <ide> .startLineNumber; <ide> } <ide> class Editor extends Component { <ide> return this._monaco.Range.lift(iRange); <ide> }; <ide> <add> // TODO: TESTS! <add> // Make 100% sure this is inclusive. <ide> getLinesBetweenRanges = (firstRange, secondRange) => { <ide> const startRange = this.translateRange(toLastLine(firstRange), 1); <ide> const endRange = this.translateRange( <ide> class Editor extends Component { <ide> const model = this.data.model; <ide> // TODO: this is a little low-level, but we should bail if there is no <ide> // editable region defined. <del> if (!this.data.startEditDecId || !this.data.endEditDecId) return null; <del> const firstRange = model.getDecorationRange(this.data.startEditDecId); <add> // NOTE: if a decoration is missing, there is still an editable region - it <add> // just extends to the edge of the editor. However, no decorations means no <add> // editable region. <add> if (!this.data.startEditDecId && !this.data.endEditDecId) return null; <add> const firstRange = this.data.startEditDecId <add> ? model.getDecorationRange(this.data.startEditDecId) <add> : this.getStartOfEditor(); <add> // TODO: handle the case that the editable region reaches the bottom of the <add> // editor <ide> const secondRange = model.getDecorationRange(this.data.endEditDecId); <ide> const { startLineNumber, endLineNumber } = this.getLinesBetweenRanges( <ide> firstRange, <ide> class Editor extends Component { <ide> return new this._monaco.Range(startLineNumber, 1, endLineNumber, endColumn); <ide> }; <ide> <add> // TODO: do this once after _monaco has been created. <add> getStartOfEditor = () => <add> this._monaco.Range.lift({ <add> startLineNumber: 1, <add> endLineNumber: 1, <add> startColumn: 1, <add> endColumn: 1 <add> }); <add> <ide> decorateForbiddenRanges(editableRegion) { <ide> const model = this.data.model; <ide> const forbiddenRanges = [ <del> [1, editableRegion[0]], <add> [0, editableRegion[0]], <ide> [editableRegion[1], model.getLineCount()] <ide> ]; <ide> <ide> const ranges = forbiddenRanges.map(positions => { <ide> return this.positionsToRange(model, positions); <ide> }); <ide> <del> // the first range should expand at the top <del> this.data.startEditDecId = this.highlightLines( <del> this._monaco.editor.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore, <del> model, <del> ranges[0] <del> ); <add> // if the forbidden range includes the top of the editor <add> // we simply don't add those decorations <add> if (forbiddenRanges[0][1] > 0) { <add> // the first range should expand at the top <add> this.data.startEditDecId = this.highlightLines( <add> this._monaco.editor.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore, <add> model, <add> ranges[0] <add> ); <ide> <del> this.highlightText( <del> this._monaco.editor.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore, <del> model, <del> ranges[0] <del> ); <add> this.highlightText( <add> this._monaco.editor.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore, <add> model, <add> ranges[0] <add> ); <add> } <ide> <add> // TODO: handle the case the region covers the bottom of the editor <ide> // the second range should expand at the bottom <ide> this.data.endEditDecId = this.highlightLines( <ide> this._monaco.editor.TrackedRangeStickiness.GrowsOnlyWhenTypingAfter, <ide> class Editor extends Component { <ide> // TODO: do the same for the description widget <ide> // this has to be handle differently, because we care about the END <ide> // of the zone, not the START <del> handleDescriptionZoneChange(this.data.startEditDecId); <add> // if the editable region includes the first line, the first decoration <add> // will be missing. <add> if (this.data.startEditDecId) { <add> handleDescriptionZoneChange(this.data.startEditDecId); <add> warnUser(this.data.startEditDecId); <add> } <ide> handleHintsZoneChange(this.data.endEditDecId); <del> warnUser(this.data.startEditDecId); <ide> warnUser(this.data.endEditDecId); <ide> }); <ide> } <ide> <ide> // creates a range covering all the lines in 'positions' <ide> // NOTE: positions is an array of [startLine, endLine] <ide> positionsToRange(model, [start, end]) { <add> console.log('positionsToRange', start, end); <ide> // start and end should always be defined, but if not: <ide> start = start || 1; <ide> end = end || model.getLineCount(); <ide> class Editor extends Component { <ide> document.getElementById('test-output').innerHTML = output[1]; <ide> } <ide> <del> if (this.data.startEditDecId) { <add> // if either id exists, the editable region exists <add> // TODO: add a layer of abstraction: we should be interacting with <add> // the editable region, not the ids <add> if (this.data.startEditDecId || this.data.endEditDecId) { <ide> this.updateOutputZone(); <ide> } <ide> }
1
PHP
PHP
update email class to use viewbuilder
cae86b689a1ab9ed758cc82b5f6e90665651a94e
<ide><path>src/Mailer/Email.php <ide> use Cake\Network\Http\FormData\Part; <ide> use Cake\Utility\Hash; <ide> use Cake\Utility\Text; <add>use Cake\View\ViewVarsTrait; <ide> use Closure; <ide> use Exception; <ide> use InvalidArgumentException; <ide> class Email implements JsonSerializable, Serializable <ide> { <ide> <ide> use StaticConfigTrait; <add> use ViewVarsTrait; <ide> <ide> /** <ide> * Line length - no should more - RFC 2822 - 2.1.1 <ide> class Email implements JsonSerializable, Serializable <ide> */ <ide> protected $_headers = []; <ide> <del> /** <del> * Layout for the View <del> * <del> * @var string <del> */ <del> protected $_layout = 'default'; <del> <del> /** <del> * Template for the view <del> * <del> * @var string <del> */ <del> protected $_template = ''; <del> <del> /** <del> * View for render <del> * <del> * @var string <del> */ <del> protected $_viewRender = 'Cake\View\View'; <del> <del> /** <del> * Vars to sent to render <del> * <del> * @var array <del> */ <del> protected $_viewVars = []; <del> <del> /** <del> * Theme for the View <del> * <del> * @var string <del> */ <del> protected $_theme = null; <del> <del> /** <del> * Helpers to be used in the render <del> * <del> * @var array <del> */ <del> protected $_helpers = ['Html']; <del> <ide> /** <ide> * Text message <ide> * <ide> public function __construct($config = null) <ide> $this->_domain = php_uname('n'); <ide> } <ide> <add> $this->viewBuilder() <add> ->className('Cake\View\View') <add> ->template('') <add> ->layout('default') <add> ->helpers(['Html']); <add> <ide> if ($config) { <ide> $this->profile($config); <ide> } <ide> public function template($template = false, $layout = false) <ide> { <ide> if ($template === false) { <ide> return [ <del> 'template' => $this->_template, <del> 'layout' => $this->_layout <add> 'template' => $this->viewBuilder()->template(), <add> 'layout' => $this->viewBuilder()->layout() <ide> ]; <ide> } <del> $this->_template = $template; <add> $this->viewBuilder()->template($template ?: ''); <ide> if ($layout !== false) { <del> $this->_layout = $layout; <add> $this->viewBuilder()->layout($layout ?: false); <ide> } <ide> return $this; <ide> } <ide> public function template($template = false, $layout = false) <ide> public function viewRender($viewClass = null) <ide> { <ide> if ($viewClass === null) { <del> return $this->_viewRender; <add> return $this->viewBuilder()->className(); <ide> } <del> $this->_viewRender = $viewClass; <add> $this->viewBuilder()->className($viewClass); <ide> return $this; <ide> } <ide> <ide> public function viewRender($viewClass = null) <ide> public function viewVars($viewVars = null) <ide> { <ide> if ($viewVars === null) { <del> return $this->_viewVars; <add> return $this->viewVars; <ide> } <del> $this->_viewVars = array_merge($this->_viewVars, (array)$viewVars); <add> $this->set((array)$viewVars); <ide> return $this; <ide> } <ide> <ide> public function viewVars($viewVars = null) <ide> public function theme($theme = null) <ide> { <ide> if ($theme === null) { <del> return $this->_theme; <add> return $this->viewBuilder()->theme(); <ide> } <del> $this->_theme = $theme; <add> $this->viewBuilder()->theme($theme); <ide> return $this; <ide> } <ide> <ide> public function theme($theme = null) <ide> public function helpers($helpers = null) <ide> { <ide> if ($helpers === null) { <del> return $this->_helpers; <add> return $this->viewBuilder()->helpers(); <ide> } <del> $this->_helpers = (array)$helpers; <add> $this->viewBuilder()->helpers((array)$helpers, false); <ide> return $this; <ide> } <ide> <ide> protected function _applyConfig($config) <ide> } <ide> unset($name); <ide> } <add> <ide> $this->_profile = array_merge($this->_profile, $config); <del> if (!empty($config['charset'])) { <del> $this->charset = $config['charset']; <del> } <del> if (!empty($config['headerCharset'])) { <del> $this->headerCharset = $config['headerCharset']; <del> } <del> if (empty($this->headerCharset)) { <del> $this->headerCharset = $this->charset; <del> } <add> <ide> $simpleMethods = [ <del> 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', 'cc', 'bcc', <del> 'messageId', 'domain', 'subject', 'viewRender', 'viewVars', 'attachments', <del> 'transport', 'emailFormat', 'theme', 'helpers', 'emailPattern' <add> 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', <add> 'cc', 'bcc', 'messageId', 'domain', 'subject', 'attachments', <add> 'transport', 'emailFormat', 'emailPattern', 'charset', 'headerCharset' <ide> ]; <ide> foreach ($simpleMethods as $method) { <ide> if (isset($config[$method])) { <ide> $this->$method($config[$method]); <del> unset($config[$method]); <ide> } <ide> } <add> <add> if (empty($this->headerCharset)) { <add> $this->headerCharset = $this->charset; <add> } <ide> if (isset($config['headers'])) { <ide> $this->setHeaders($config['headers']); <del> unset($config['headers']); <ide> } <ide> <del> if (array_key_exists('template', $config)) { <del> $this->_template = $config['template']; <add> $viewBuilderMethods = [ <add> 'template', 'layout', 'theme' <add> ]; <add> foreach ($viewBuilderMethods as $method) { <add> if (array_key_exists($method, $config)) { <add> $this->viewBuilder()->$method($config[$method]); <add> } <add> } <add> <add> if (array_key_exists('helpers', $config)) { <add> $this->viewBuilder()->helpers($config['helpers'], false); <ide> } <del> if (array_key_exists('layout', $config)) { <del> $this->_layout = $config['layout']; <add> if (array_key_exists('viewRender', $config)) { <add> $this->viewBuilder()->className($config['viewRender']); <add> } <add> if (array_key_exists('viewVars', $config)) { <add> $this->set($config['viewVars']); <ide> } <ide> } <ide> <ide> public function reset() <ide> $this->_messageId = true; <ide> $this->_subject = ''; <ide> $this->_headers = []; <del> $this->_layout = 'default'; <del> $this->_template = ''; <del> $this->_viewRender = 'Cake\View\View'; <del> $this->_viewVars = []; <del> $this->_theme = null; <del> $this->_helpers = ['Html']; <ide> $this->_textMessage = ''; <ide> $this->_htmlMessage = ''; <ide> $this->_message = ''; <ide> public function reset() <ide> $this->_attachments = []; <ide> $this->_profile = []; <ide> $this->_emailPattern = self::EMAIL_PATTERN; <add> <add> $this->viewBuilder()->layout('default'); <add> $this->viewBuilder()->template(''); <add> $this->viewBuilder()->classname('Cake\View\View'); <add> $this->viewVars = []; <add> $this->viewBuilder()->theme(false); <add> $this->viewBuilder()->helpers(['Html'], false); <add> <ide> return $this; <ide> } <ide> <ide> protected function _renderTemplates($content) <ide> { <ide> $types = $this->_getTypes(); <ide> $rendered = []; <del> if (empty($this->_template)) { <add> if (empty($this->viewBuilder()->template())) { <ide> foreach ($types as $type) { <ide> $rendered[$type] = $this->_encodeString($content, $this->charset); <ide> } <ide> return $rendered; <ide> } <del> $viewClass = $this->_viewRender; <del> if ($viewClass === 'View') { <del> $viewClass = App::className('View', 'View'); <del> } else { <del> $viewClass = App::className($viewClass, 'View', 'View'); <del> } <del> <del> $View = new $viewClass(null); <del> $View->viewVars = $this->_viewVars; <del> $View->helpers = $this->_helpers; <del> <del> if ($this->_theme) { <del> $View->theme = $this->_theme; <del> } <ide> <add> $View = $this->createView(); <ide> $View->loadHelpers(); <ide> <del> list($templatePlugin) = pluginSplit($this->_template); <del> list($layoutPlugin) = pluginSplit($this->_layout); <add> list($templatePlugin) = pluginSplit($View->view()); <add> list($layoutPlugin) = pluginSplit($View->layout()); <ide> if ($templatePlugin) { <ide> $View->plugin = $templatePlugin; <ide> } elseif ($layoutPlugin) { <ide> protected function _renderTemplates($content) <ide> $View->set('content', $content); <ide> } <ide> <del> // Convert null to false, as View needs false to disable <del> // the layout. <del> if ($this->_layout === null) { <del> $this->_layout = false; <del> } <del> <ide> foreach ($types as $type) { <ide> $View->hasRendered = false; <del> $View->viewPath = $View->layoutPath = 'Email/' . $type; <add> $View->viewPath('Email/' . $type); <add> $View->layoutPath('Email/' . $type); <ide> <del> $render = $View->render($this->_template, $this->_layout); <add> $render = $View->render(); <ide> $render = str_replace(["\r\n", "\r"], "\n", $render); <ide> $rendered[$type] = $this->_encodeString($render, $this->charset); <ide> } <ide><path>src/View/ViewVarsTrait.php <ide> namespace Cake\View; <ide> <ide> use Cake\Core\App; <add>use Cake\Event\EventManagerTrait; <ide> use Cake\View\ViewBuilder; <ide> <ide> /** <ide> public function createView($viewClass = null) <ide> <ide> return $builder->build( <ide> $this->viewVars, <del> $this->request, <del> $this->response, <del> $this->eventManager(), <add> isset($this->request) ? $this->request : null, <add> isset($this->response) ? $this->response : null, <add> $this instanceof EventManagerTrait ? $this->eventManager() : null, <ide> $viewOptions <ide> ); <ide> } <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testTemplate() <ide> $this->assertSame($expected, $this->CakeEmail->template()); <ide> <ide> $this->CakeEmail->template('template', null); <del> $expected = ['template' => 'template', 'layout' => null]; <add> $expected = ['template' => 'template', 'layout' => false]; <ide> $this->assertSame($expected, $this->CakeEmail->template()); <ide> <ide> $this->CakeEmail->template(null, null); <del> $expected = ['template' => null, 'layout' => null]; <add> $expected = ['template' => '', 'layout' => false]; <ide> $this->assertSame($expected, $this->CakeEmail->template()); <ide> } <ide> <ide> public function testViewVars() <ide> $this->assertSame(['value' => 12345], $this->CakeEmail->viewVars()); <ide> <ide> $this->CakeEmail->viewVars(['name' => 'CakePHP']); <del> $this->assertSame(['value' => 12345, 'name' => 'CakePHP'], $this->CakeEmail->viewVars()); <add> $this->assertEquals(['value' => 12345, 'name' => 'CakePHP'], $this->CakeEmail->viewVars()); <ide> <ide> $this->CakeEmail->viewVars(['value' => 4567]); <ide> $this->assertSame(['value' => 4567, 'name' => 'CakePHP'], $this->CakeEmail->viewVars()); <ide> public function testDeliver() <ide> $this->assertSame($instance->to(), ['debug@cakephp.org' => 'debug@cakephp.org']); <ide> $this->assertSame($instance->subject(), 'Update ok'); <ide> $this->assertSame($instance->template(), ['template' => 'custom', 'layout' => 'custom_layout']); <del> $this->assertSame($instance->viewVars(), ['value' => 123, 'name' => 'CakePHP']); <add> $this->assertEquals($instance->viewVars(), ['value' => 123, 'name' => 'CakePHP']); <ide> $this->assertSame($instance->cc(), ['cake@cakephp.org' => 'Myself']); <ide> <ide> $configs = ['from' => 'root@cakephp.org', 'message' => 'Message from configs', 'transport' => 'debug']; <ide> public function testReset() <ide> <ide> $this->CakeEmail->reset(); <ide> $this->assertSame([], $this->CakeEmail->to()); <del> $this->assertNull($this->CakeEmail->theme()); <add> $this->assertFalse($this->CakeEmail->theme()); <ide> $this->assertSame(Email::EMAIL_PATTERN, $this->CakeEmail->emailPattern()); <ide> } <ide> <ide> public function testJsonSerialize() <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <add> debug(unserialize(serialize($this->CakeEmail))); <ide> $result = json_decode(json_encode(unserialize(serialize($this->CakeEmail))), true); <ide> $this->assertContains('test', $result['_viewVars']['exception']); <ide> unset($result['_viewVars']['exception']);
3
PHP
PHP
update typehint to be nullable
7d62f500a789416738a7181d5217d33ca096db04
<ide><path>app/Http/Middleware/TrustProxies.php <ide> class TrustProxies extends Middleware <ide> /** <ide> * The trusted proxies for this application. <ide> * <del> * @var array|string <add> * @var array|string|null <ide> */ <ide> protected $proxies; <ide>
1
Text
Text
fix default values for helm chart
874e497ff8b81121308018d02137361f66ae3c36
<ide><path>chart/README.md <ide> The following tables lists the configurable parameters of the Airflow chart and <ide> | `images.flower.repository` | Docker repository to pull image from. Update this to deploy a custom image | `~` | <ide> | `images.flower.tag` | Docker image tag to pull image from. Update this to deploy a new custom image tag | `~` | <ide> | `images.flower.pullPolicy` | PullPolicy for flower image | `IfNotPresent` | <del>| `images.statsd.repository` | Docker repository to pull image from. Update this to deploy a custom image | `astronomerinc/ap-statsd-exporter` | <del>| `images.statsd.tag` | Docker image tag to pull image from. Update this to deploy a new custom image tag | `~` | <add>| `images.statsd.repository` | Docker repository to pull image from. Update this to deploy a custom image | `apache/airflow` | <add>| `images.statsd.tag` | Docker image tag to pull image from. Update this to deploy a new custom image tag | `airflow-statsd-exporter-2020.09.05-v0.17.0` | <ide> | `images.statsd.pullPolicy` | PullPolicy for statsd-exporter image | `IfNotPresent` | <ide> | `images.redis.repository` | Docker repository to pull image from. Update this to deploy a custom image | `redis` | <ide> | `images.redis.tag` | Docker image tag to pull image from. Update this to deploy a new custom image tag | `6-buster` | <ide> | `images.redis.pullPolicy` | PullPolicy for redis image | `IfNotPresent` | <del>| `images.pgbouncer.repository` | Docker repository to pull image from. Update this to deploy a custom image | `astronomerinc/ap-pgbouncer` | <del>| `images.pgbouncer.tag` | Docker image tag to pull image from. Update this to deploy a new custom image tag | `~` | <add>| `images.pgbouncer.repository` | Docker repository to pull image from. Update this to deploy a custom image | `apache/airflow` | <add>| `images.pgbouncer.tag` | Docker image tag to pull image from. Update this to deploy a new custom image tag | `airflow-pgbouncer-2020.09.05-1.14.0` | <ide> | `images.pgbouncer.pullPolicy` | PullPolicy for pgbouncer image | `IfNotPresent` | <del>| `images.pgbouncerExporter.repository` | Docker repository to pull image from. Update this to deploy a custom image | `astronomerinc/ap-pgbouncer-exporter` | <del>| `images.pgbouncerExporter.tag` | Docker image tag to pull image from. Update this to deploy a new custom image tag | `~` | <add>| `images.pgbouncerExporter.repository` | Docker repository to pull image from. Update this to deploy a custom image | `apache/airflow` | <add>| `images.pgbouncerExporter.tag` | Docker image tag to pull image from. Update this to deploy a new custom image tag | `airflow-pgbouncer-exporter-2020.09.25-0.5.0` | <ide> | `images.pgbouncerExporter.pullPolicy` | PullPolicy for pgbouncer-exporter image | `IfNotPresent` | <ide> | `env` | Environment variables key/values to mount into Airflow pods | `[]` | <ide> | `secret` | Secret name/key pairs to mount into Airflow pods | `[]` |
1
Go
Go
add quota support to vfs graphdriver
7a1618ced359a3ac921d8a05903d62f544ff17d0
<ide><path>daemon/graphdriver/graphtest/graphtest_unix.go <ide> import ( <ide> "unsafe" <ide> <ide> "github.com/docker/docker/daemon/graphdriver" <add> "github.com/docker/docker/daemon/graphdriver/quota" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/go-units" <ide> "github.com/stretchr/testify/assert" <ide> func writeRandomFile(path string, size uint64) error { <ide> } <ide> <ide> // DriverTestSetQuota Create a driver and test setting quota. <del>func DriverTestSetQuota(t *testing.T, drivername string) { <add>func DriverTestSetQuota(t *testing.T, drivername string, required bool) { <ide> driver := GetDriver(t, drivername) <ide> defer PutDriver(t) <ide> <ide> createBase(t, driver, "Base") <ide> createOpts := &graphdriver.CreateOpts{} <ide> createOpts.StorageOpt = make(map[string]string, 1) <ide> createOpts.StorageOpt["size"] = "50M" <del> if err := driver.Create("zfsTest", "Base", createOpts); err != nil { <add> layerName := drivername + "Test" <add> if err := driver.CreateReadWrite(layerName, "Base", createOpts); err == quota.ErrQuotaNotSupported && !required { <add> t.Skipf("Quota not supported on underlying filesystem: %v", err) <add> } else if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> mountPath, err := driver.Get("zfsTest", "") <add> mountPath, err := driver.Get(layerName, "") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> quota := uint64(50 * units.MiB) <ide> <del> err = writeRandomFile(path.Join(mountPath.Path(), "file"), quota*2) <del> if pathError, ok := err.(*os.PathError); ok && pathError.Err != unix.EDQUOT { <del> t.Fatalf("expect write() to fail with %v, got %v", unix.EDQUOT, err) <add> // Try to write a file smaller than quota, and ensure it works <add> err = writeRandomFile(path.Join(mountPath.Path(), "smallfile"), quota/2) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.Remove(path.Join(mountPath.Path(), "smallfile")) <add> <add> // Try to write a file bigger than quota. We've already filled up half the quota, so hitting the limit should be easy <add> err = writeRandomFile(path.Join(mountPath.Path(), "bigfile"), quota) <add> if err == nil { <add> t.Fatalf("expected write to fail(), instead had success") <add> } <add> if pathError, ok := err.(*os.PathError); ok && pathError.Err != unix.EDQUOT && pathError.Err != unix.ENOSPC { <add> os.Remove(path.Join(mountPath.Path(), "bigfile")) <add> t.Fatalf("expect write() to fail with %v or %v, got %v", unix.EDQUOT, unix.ENOSPC, pathError.Err) <ide> } <ide> } <ide><path>daemon/graphdriver/quota/errors.go <add>package quota <add> <add>import "github.com/docker/docker/api/errdefs" <add> <add>var ( <add> _ errdefs.ErrNotImplemented = (*errQuotaNotSupported)(nil) <add>) <add> <add>// ErrQuotaNotSupported indicates if were found the FS didn't have projects quotas available <add>var ErrQuotaNotSupported = errQuotaNotSupported{} <add> <add>type errQuotaNotSupported struct { <add>} <add> <add>func (e errQuotaNotSupported) NotImplemented() {} <add> <add>func (e errQuotaNotSupported) Error() string { <add> return "Filesystem does not support, or has not enabled quotas" <add>} <ide><path>daemon/graphdriver/quota/projectquota.go <ide> import ( <ide> "path/filepath" <ide> "unsafe" <ide> <del> "errors" <del> <ide> "github.com/sirupsen/logrus" <ide> "golang.org/x/sys/unix" <ide> ) <ide> <del>// ErrQuotaNotSupported indicates if were found the FS does not have projects quotas available <del>var ErrQuotaNotSupported = errors.New("Filesystem does not support or has not enabled quotas") <del> <ide> // Quota limit params - currently we only control blocks hard limit <ide> type Quota struct { <ide> Size uint64 <ide><path>daemon/graphdriver/vfs/driver.go <ide> import ( <ide> "path/filepath" <ide> <ide> "github.com/docker/docker/daemon/graphdriver" <add> "github.com/docker/docker/daemon/graphdriver/quota" <ide> "github.com/docker/docker/pkg/chrootarchive" <ide> "github.com/docker/docker/pkg/containerfs" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/system" <add> units "github.com/docker/go-units" <ide> "github.com/opencontainers/selinux/go-selinux/label" <ide> ) <ide> <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> if err := idtools.MkdirAllAndChown(home, 0700, rootIDs); err != nil { <ide> return nil, err <ide> } <add> <add> if err := setupDriverQuota(d); err != nil { <add> return nil, err <add> } <add> <ide> return graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps), nil <ide> } <ide> <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> // In order to support layering, files are copied from the parent layer into the new layer. There is no copy-on-write support. <ide> // Driver must be wrapped in NaiveDiffDriver to be used as a graphdriver.Driver <ide> type Driver struct { <add> driverQuota <ide> home string <ide> idMappings *idtools.IDMappings <ide> } <ide> func (d *Driver) Cleanup() error { <ide> // CreateReadWrite creates a layer that is writable for use as a container <ide> // file system. <ide> func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error { <del> return d.Create(id, parent, opts) <add> var err error <add> var size int64 <add> <add> if opts != nil { <add> for key, val := range opts.StorageOpt { <add> switch key { <add> case "size": <add> if !d.quotaSupported() { <add> return quota.ErrQuotaNotSupported <add> } <add> if size, err = units.RAMInBytes(val); err != nil { <add> return err <add> } <add> default: <add> return fmt.Errorf("Storage opt %s not supported", key) <add> } <add> } <add> } <add> <add> return d.create(id, parent, uint64(size)) <ide> } <ide> <ide> // Create prepares the filesystem for the VFS driver and copies the directory for the given id under the parent. <ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { <ide> if opts != nil && len(opts.StorageOpt) != 0 { <del> return fmt.Errorf("--storage-opt is not supported for vfs") <add> return fmt.Errorf("--storage-opt is not supported for vfs on read-only layers") <ide> } <ide> <add> return d.create(id, parent, 0) <add>} <add> <add>func (d *Driver) create(id, parent string, size uint64) error { <ide> dir := d.dir(id) <ide> rootIDs := d.idMappings.RootPair() <ide> if err := idtools.MkdirAllAndChown(filepath.Dir(dir), 0700, rootIDs); err != nil { <ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { <ide> if err := idtools.MkdirAndChown(dir, 0755, rootIDs); err != nil { <ide> return err <ide> } <add> <add> if size != 0 { <add> if err := d.setupQuota(dir, size); err != nil { <add> return err <add> } <add> } <add> <ide> labelOpts := []string{"level:s0"} <ide> if _, mountLabel, err := label.InitLabels(labelOpts); err == nil { <ide> label.SetFileLabel(dir, mountLabel) <ide><path>daemon/graphdriver/vfs/quota_linux.go <add>// +build linux <add> <add>package vfs <add> <add>import "github.com/docker/docker/daemon/graphdriver/quota" <add> <add>type driverQuota struct { <add> quotaCtl *quota.Control <add>} <add> <add>func setupDriverQuota(driver *Driver) error { <add> if quotaCtl, err := quota.NewControl(driver.home); err == nil { <add> driver.quotaCtl = quotaCtl <add> } else if err != quota.ErrQuotaNotSupported { <add> return err <add> } <add> <add> return nil <add>} <add> <add>func (d *Driver) setupQuota(dir string, size uint64) error { <add> return d.quotaCtl.SetQuota(dir, quota.Quota{Size: size}) <add>} <add> <add>func (d *Driver) quotaSupported() bool { <add> return d.quotaCtl != nil <add>} <ide><path>daemon/graphdriver/vfs/quota_unsupported.go <add>// +build !linux <add> <add>package vfs <add> <add>import "github.com/docker/docker/daemon/graphdriver/quota" <add> <add>type driverQuota struct { <add>} <add> <add>func setupDriverQuota(driver *Driver) error { <add> return nil <add>} <add> <add>func (d *Driver) setupQuota(dir string, size uint64) error { <add> return quota.ErrQuotaNotSupported <add>} <add> <add>func (d *Driver) quotaSupported() bool { <add> return false <add>} <ide><path>daemon/graphdriver/vfs/vfs_test.go <ide> func TestVfsCreateSnap(t *testing.T) { <ide> graphtest.DriverTestCreateSnap(t, "vfs") <ide> } <ide> <add>func TestVfsSetQuota(t *testing.T) { <add> graphtest.DriverTestSetQuota(t, "vfs", false) <add>} <add> <ide> func TestVfsTeardown(t *testing.T) { <ide> graphtest.PutDriver(t) <ide> } <ide><path>daemon/graphdriver/zfs/zfs_test.go <ide> func TestZfsCreateSnap(t *testing.T) { <ide> } <ide> <ide> func TestZfsSetQuota(t *testing.T) { <del> graphtest.DriverTestSetQuota(t, "zfs") <add> graphtest.DriverTestSetQuota(t, "zfs", true) <ide> } <ide> <ide> func TestZfsTeardown(t *testing.T) {
8
Go
Go
move events to job
5cc6312bfc4e511784693d02b9bb8e8d9d1c04b0
<ide><path>api.go <ide> func getInfo(srv *Server, version float64, w http.ResponseWriter, r *http.Reques <ide> } <ide> <ide> func getEvents(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> sendEvent := func(wf *utils.WriteFlusher, event *utils.JSONMessage) error { <del> b, err := json.Marshal(event) <del> if err != nil { <del> return fmt.Errorf("JSON error") <del> } <del> _, err = wf.Write(b) <del> if err != nil { <del> // On error, evict the listener <del> utils.Errorf("%s", err) <del> srv.Lock() <del> delete(srv.listeners, r.RemoteAddr) <del> srv.Unlock() <del> return err <del> } <del> return nil <del> } <del> <ide> if err := parseForm(r); err != nil { <ide> return err <ide> } <del> listener := make(chan utils.JSONMessage) <del> srv.Lock() <del> srv.listeners[r.RemoteAddr] = listener <del> srv.Unlock() <del> since, err := strconv.ParseInt(r.Form.Get("since"), 10, 0) <del> if err != nil { <del> since = 0 <del> } <add> <ide> w.Header().Set("Content-Type", "application/json") <del> wf := utils.NewWriteFlusher(w) <del> wf.Flush() <del> if since != 0 { <del> // If since, send previous events that happened after the timestamp <del> for _, event := range srv.GetEvents() { <del> if event.Time >= since { <del> err := sendEvent(wf, &event) <del> if err != nil && err.Error() == "JSON error" { <del> continue <del> } <del> if err != nil { <del> return err <del> } <del> } <del> } <del> } <del> for event := range listener { <del> err := sendEvent(wf, &event) <del> if err != nil && err.Error() == "JSON error" { <del> continue <del> } <del> if err != nil { <del> return err <del> } <del> } <del> return nil <add> var job = srv.Eng.Job("events", r.RemoteAddr) <add> job.Stdout.Add(utils.NewWriteFlusher(w)) <add> job.Setenv("since", r.Form.Get("since")) <add> return job.Run() <ide> } <ide> <ide> func getImagesHistory(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide><path>server.go <ide> func jobInitApi(job *engine.Job) engine.Status { <ide> "import": srv.ImageImport, <ide> "image_delete": srv.ImageDelete, <ide> "inspect": srv.JobInspect, <add> "events": srv.Events, <ide> } { <ide> if err := job.Eng.Register(name, handler); err != nil { <ide> job.Error(err) <ide> func (srv *Server) ContainerKill(job *engine.Job) engine.Status { <ide> } <ide> return engine.StatusOK <ide> } <add>func (srv *Server) Events(job *engine.Job) engine.Status { <add> if len(job.Args) != 1 { <add> job.Errorf("Usage: %s FROM", job.Name) <add> return engine.StatusErr <add> } <add> <add> var ( <add> from = job.Args[0] <add> since = job.GetenvInt64("since") <add> ) <add> sendEvent := func(event *utils.JSONMessage) error { <add> b, err := json.Marshal(event) <add> if err != nil { <add> return fmt.Errorf("JSON error") <add> } <add> _, err = job.Stdout.Write(b) <add> if err != nil { <add> // On error, evict the listener <add> utils.Errorf("%s", err) <add> srv.Lock() <add> delete(srv.listeners, from) <add> srv.Unlock() <add> return err <add> } <add> return nil <add> } <add> <add> listener := make(chan utils.JSONMessage) <add> srv.Lock() <add> srv.listeners[from] = listener <add> srv.Unlock() <add> job.Stdout.Write(nil) // flush <add> if since != 0 { <add> // If since, send previous events that happened after the timestamp <add> for _, event := range srv.GetEvents() { <add> if event.Time >= since { <add> err := sendEvent(&event) <add> if err != nil && err.Error() == "JSON error" { <add> continue <add> } <add> if err != nil { <add> job.Error(err) <add> return engine.StatusErr <add> } <add> } <add> } <add> } <add> for event := range listener { <add> err := sendEvent(&event) <add> if err != nil && err.Error() == "JSON error" { <add> continue <add> } <add> if err != nil { <add> job.Error(err) <add> return engine.StatusErr <add> } <add> } <add> return engine.StatusOK <add>} <ide> <ide> func (srv *Server) ContainerExport(job *engine.Job) engine.Status { <ide> if len(job.Args) != 1 {
2
PHP
PHP
add property $_config to staticconfigtrait
9a0f88386ec906d6089a22aabd4b5ba0c1347750
<ide><path>src/Cache/Cache.php <ide> class Cache { <ide> */ <ide> protected static $_enabled = true; <ide> <del>/** <del> * Cache configuration. <del> * <del> * Keeps the permanent/default settings for each cache engine. <del> * These settings are used to reset the engines after temporary modification. <del> * <del> * @var array <del> */ <del> protected static $_config = []; <del> <ide> /** <ide> * Group to Config mapping <ide> * <ide><path>src/Core/StaticConfigTrait.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> */ <ide> trait StaticConfigTrait { <ide> <add>/** <add> * Configuration sets. <add> * <add> * @var array <add> */ <add> protected static $_config = []; <add> <ide> /** <ide> * This method can be used to define confguration adapters for an application <ide> * or read existing configuration. <ide><path>src/Datasource/ConnectionManager.php <ide> class ConnectionManager { <ide> config as protected _config; <ide> } <ide> <del>/** <del> * Holds a list of connection configurations <del> * <del> * @var array <del> */ <del> protected static $_config = []; <del> <ide> /** <ide> * A map of connection aliases. <ide> * <ide><path>src/Log/Log.php <ide> class Log { <ide> */ <ide> protected static $_dirtyConfig = false; <ide> <del>/** <del> * An array of configured loggers. <del> * <del> * @var array <del> */ <del> protected static $_config = []; <del> <ide> /** <ide> * LogEngineRegistry class <ide> * <ide><path>src/Network/Email/Email.php <ide> class Email { <ide> */ <ide> protected $_boundary = null; <ide> <del>/** <del> * Configuration profiles for use in instances. <del> * <del> * @var array <del> */ <del> protected static $_config = []; <del> <ide> /** <ide> * Configuration profiles for transports. <ide> *
5
Python
Python
apply parent dag permissions to subdags.
3e3c48a136902ac67efce938bd10930e653a8075
<ide><path>airflow/www/security.py <ide> def can_read_dag(self, dag_id, user=None) -> bool: <ide> """Determines whether a user has DAG read access.""" <ide> if not user: <ide> user = g.user <del> dag_resource_name = permissions.resource_name_for_dag(dag_id) <add> # To account for SubDags <add> root_dag_id = dag_id.split(".")[0] <add> dag_resource_name = permissions.resource_name_for_dag(root_dag_id) <ide> return self._has_access( <ide> user, permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG <ide> ) or self._has_access(user, permissions.ACTION_CAN_READ, dag_resource_name) <ide> def can_edit_dag(self, dag_id, user=None) -> bool: <ide> """Determines whether a user has DAG edit access.""" <ide> if not user: <ide> user = g.user <del> dag_resource_name = permissions.resource_name_for_dag(dag_id) <add> # To account for SubDags <add> root_dag_id = dag_id.split(".")[0] <add> dag_resource_name = permissions.resource_name_for_dag(root_dag_id) <ide> <ide> return self._has_access( <ide> user, permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG <ide> def has_access(self, action_name, resource_name, user=None) -> bool: <ide> <ide> has_access = self._has_access(user, action_name, resource_name) <ide> # FAB built-in view access method. Won't work for AllDag access. <del> <ide> if self.is_dag_resource(resource_name): <ide> if action_name == permissions.ACTION_CAN_READ: <ide> has_access |= self.can_read_dag(resource_name, user) <ide><path>tests/www/test_security.py <ide> def setUp(self): <ide> <ide> @classmethod <ide> def delete_roles(cls): <del> for role_name in ['team-a', 'MyRole1', 'MyRole5', 'Test_Role', 'MyRole3', 'MyRole2']: <add> for role_name in [ <add> 'team-a', <add> 'MyRole1', <add> 'MyRole5', <add> 'Test_Role', <add> 'MyRole3', <add> 'MyRole2', <add> 'dag_permission_role', <add> ]: <ide> api_connexion_utils.delete_role(cls.app, role_name) <ide> <ide> def expect_user_is_in_role(self, user, rolename): <ide> def assert_user_does_not_have_dag_perms(self, dag_id, perms, user=None): <ide> ), f"User should not have '{perm}' on DAG '{dag_id}'" <ide> <ide> def _has_dag_perm(self, perm, dag_id, user): <del> # if not user: <del> # user = self.user <ide> return self.security_manager.has_access(perm, permissions.resource_name_for_dag(dag_id), user) <ide> <ide> def _create_dag(self, dag_id): <ide> def test_prefixed_dag_id_is_deprecated(self): <ide> ), <ide> ): <ide> self.security_manager.prefixed_dag_id("hello") <add> <add> def test_parent_dag_access_applies_to_subdag(self): <add> username = 'dag_permission_user' <add> role_name = 'dag_permission_role' <add> parent_dag_name = "parent_dag" <add> with self.app.app_context(): <add> mock_roles = [ <add> { <add> 'role': role_name, <add> 'perms': [ <add> (permissions.ACTION_CAN_READ, f"DAG:{parent_dag_name}"), <add> (permissions.ACTION_CAN_EDIT, f"DAG:{parent_dag_name}"), <add> ], <add> } <add> ] <add> user = api_connexion_utils.create_user( <add> self.app, <add> username, <add> role_name, <add> ) <add> self.security_manager.bulk_sync_roles(mock_roles) <add> self.security_manager._sync_dag_view_permissions( <add> parent_dag_name, access_control={role_name: READ_WRITE} <add> ) <add> self.assert_user_has_dag_perms(perms=READ_WRITE, dag_id=parent_dag_name, user=user) <add> self.assert_user_has_dag_perms(perms=READ_WRITE, dag_id=parent_dag_name + ".subdag", user=user) <add> self.assert_user_has_dag_perms( <add> perms=READ_WRITE, dag_id=parent_dag_name + ".subdag.subsubdag", user=user <add> )
2
Go
Go
avoid flakiness of testlinkcontainers
daba67d67b2db2585ae9433fabec8bf309be11d8
<ide><path>libnetwork/drivers/bridge/bridge_test.go <ide> func getIPv4Data(t *testing.T, iface string) []driverapi.IPAMData { <ide> } <ide> <ide> func TestCreateFullOptions(t *testing.T) { <del> defer testutils.SetupTestOSContext(t)() <add> if !testutils.IsRunningInContainer() { <add> defer testutils.SetupTestOSContext(t)() <add> } <ide> d := newDriver() <ide> <ide> config := &configuration{ <ide> func TestQueryEndpointInfoHairpin(t *testing.T) { <ide> } <ide> <ide> func testQueryEndpointInfo(t *testing.T, ulPxyEnabled bool) { <del> defer testutils.SetupTestOSContext(t)() <del> <add> if !testutils.IsRunningInContainer() { <add> defer testutils.SetupTestOSContext(t)() <add> } <ide> d := newDriver() <ide> <ide> config := &configuration{ <ide><path>libnetwork/iptables/iptables.go <ide> func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) err <ide> "-j", c.Name} <ide> if !Exists(Nat, "PREROUTING", preroute...) && enable { <ide> if err := c.Prerouting(Append, preroute...); err != nil { <del> return fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err) <add> return fmt.Errorf("Failed to inject %s in PREROUTING chain: %s", c.Name, err) <ide> } <ide> } else if Exists(Nat, "PREROUTING", preroute...) && !enable { <ide> if err := c.Prerouting(Delete, preroute...); err != nil { <del> return fmt.Errorf("Failed to remove docker in PREROUTING chain: %s", err) <add> return fmt.Errorf("Failed to remove %s in PREROUTING chain: %s", c.Name, err) <ide> } <ide> } <ide> output := []string{ <ide> func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) err <ide> } <ide> if !Exists(Nat, "OUTPUT", output...) && enable { <ide> if err := c.Output(Append, output...); err != nil { <del> return fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err) <add> return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err) <ide> } <ide> } else if Exists(Nat, "OUTPUT", output...) && !enable { <ide> if err := c.Output(Delete, output...); err != nil { <del> return fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err) <add> return fmt.Errorf("Failed to inject %s in OUTPUT chain: %s", c.Name, err) <ide> } <ide> } <ide> case Filter:
2
Python
Python
get mtime in utc
4ff84d537aa386fde36182ed797a79e3b582be75
<ide><path>tests/test_helpers.py <ide> def index(): <ide> assert rv.status_code == 416 <ide> rv.close() <ide> <del> last_modified = datetime.datetime.fromtimestamp(os.path.getmtime( <add> last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime( <ide> os.path.join(app.root_path, 'static/index.html'))).replace( <ide> microsecond=0) <ide>
1
Javascript
Javascript
fix indentation and move a method definition
ec801ac13782f3f488915d682d6d2a73e2d76efd
<ide><path>src/ngResource/resource.js <ide> * @description <ide> */ <ide> <del> /** <add>/** <ide> * @ngdoc object <ide> * @name ngResource.$resource <ide> * @requires $http <ide> angular.module('ngResource', ['ng']). <ide> return $parse(path)(obj); <ide> }; <ide> <del> /** <del> * We need our custom mehtod because encodeURIComponent is too aggressive and doesn't follow <del> * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path <del> * segments: <del> * segment = *pchar <del> * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" <del> * pct-encoded = "%" HEXDIG HEXDIG <del> * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <del> * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" <del> * / "*" / "+" / "," / ";" / "=" <del> */ <del> function encodeUriSegment(val) { <del> return encodeUriQuery(val, true). <del> replace(/%26/gi, '&'). <del> replace(/%3D/gi, '='). <del> replace(/%2B/gi, '+'); <del> } <del> <del> <del> /** <del> * This method is intended for encoding *key* or *value* parts of query component. We need a custom <del> * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be <del> * encoded per http://tools.ietf.org/html/rfc3986: <del> * query = *( pchar / "/" / "?" ) <del> * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" <del> * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <del> * pct-encoded = "%" HEXDIG HEXDIG <del> * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" <del> * / "*" / "+" / "," / ";" / "=" <del> */ <del> function encodeUriQuery(val, pctEncodeSpaces) { <del> return encodeURIComponent(val). <del> replace(/%40/gi, '@'). <del> replace(/%3A/gi, ':'). <del> replace(/%24/g, '$'). <del> replace(/%2C/gi, ','). <del> replace((pctEncodeSpaces ? null : /%20/g), '+'); <del> } <del> <del> function Route(template, defaults) { <add> /** <add> * We need our custom mehtod because encodeURIComponent is too aggressive and doesn't follow <add> * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path <add> * segments: <add> * segment = *pchar <add> * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" <add> * pct-encoded = "%" HEXDIG HEXDIG <add> * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <add> * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" <add> * / "*" / "+" / "," / ";" / "=" <add> */ <add> function encodeUriSegment(val) { <add> return encodeUriQuery(val, true). <add> replace(/%26/gi, '&'). <add> replace(/%3D/gi, '='). <add> replace(/%2B/gi, '+'); <add> } <add> <add> <add> /** <add> * This method is intended for encoding *key* or *value* parts of query component. We need a custom <add> * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be <add> * encoded per http://tools.ietf.org/html/rfc3986: <add> * query = *( pchar / "/" / "?" ) <add> * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" <add> * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <add> * pct-encoded = "%" HEXDIG HEXDIG <add> * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" <add> * / "*" / "+" / "," / ";" / "=" <add> */ <add> function encodeUriQuery(val, pctEncodeSpaces) { <add> return encodeURIComponent(val). <add> replace(/%40/gi, '@'). <add> replace(/%3A/gi, ':'). <add> replace(/%24/g, '$'). <add> replace(/%2C/gi, ','). <add> replace((pctEncodeSpaces ? null : /%20/g), '+'); <add> } <add> <add> function Route(template, defaults) { <ide> this.template = template = template + '#'; <ide> this.defaults = defaults || {}; <ide> var urlParams = this.urlParams = {}; <ide> angular.module('ngResource', ['ng']). <ide> }; <ide> <ide> <del> Resource.bind = function(additionalParamDefaults){ <del> return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); <del> }; <del> <del> <ide> Resource.prototype['$' + name] = function(a1, a2, a3) { <ide> var params = extractParams(this), <ide> success = noop, <ide> angular.module('ngResource', ['ng']). <ide> Resource[name].call(this, params, data, success, error); <ide> }; <ide> }); <add> <add> Resource.bind = function(additionalParamDefaults){ <add> return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); <add> }; <add> <ide> return Resource; <ide> } <ide>
1
Ruby
Ruby
fix libffi detection on 12.3+ sdk
b3da8dbd24f61fdc5f319bf1a4253e86682a0bff
<ide><path>Library/Homebrew/test/os/mac/pkgconfig_spec.rb <ide> def pc_version(library) <ide> it "returns the correct version for libffi" do <ide> version = File.foreach("#{sdk}/usr/include/ffi/ffi.h") <ide> .lazy <del> .grep(/^\s*libffi (\S+) - Copyright /) { Regexp.last_match(1) } <add> .grep(/^\s*libffi (\S+)\s+- Copyright /) { Regexp.last_match(1) } <ide> .first <ide> <ide> skip "Cannot detect system libffi version." if version == "PyOBJC"
1
Java
Java
replace create with wrap in rsocketrequester
089fb5737d7b94310a4873d6f078ec7da45aec6d
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilder.java <ide> public Mono<RSocketRequester> connect(ClientTransport transport) { <ide> this.factoryConfigurers.forEach(configurer -> configurer.accept(factory)); <ide> <ide> return factory.transport(transport).start() <del> .map(rsocket -> RSocketRequester.create(rsocket, dataMimeType, strategies)); <add> .map(rsocket -> new DefaultRSocketRequester(rsocket, dataMimeType, strategies)); <ide> }); <ide> } <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/MessageHandlerAcceptor.java <ide> public RSocket apply(RSocket sendingRSocket) { <ide> } <ide> <ide> private MessagingRSocket createRSocket(RSocket rsocket) { <del> return new MessagingRSocket(this::handleMessage, rsocket, this.defaultDataMimeType, getRSocketStrategies()); <add> return new MessagingRSocket(this::handleMessage, <add> RSocketRequester.wrap(rsocket, this.defaultDataMimeType, getRSocketStrategies()), <add> this.defaultDataMimeType, <add> getRSocketStrategies().dataBufferFactory()); <ide> } <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/MessagingRSocket.java <ide> class MessagingRSocket extends AbstractRSocket { <ide> @Nullable <ide> private MimeType dataMimeType; <ide> <del> private final RSocketStrategies strategies; <add> private final DataBufferFactory bufferFactory; <ide> <ide> <del> MessagingRSocket(Function<Message<?>, Mono<Void>> handler, RSocket sendingRSocket, <del> @Nullable MimeType defaultDataMimeType, RSocketStrategies strategies) { <add> MessagingRSocket(Function<Message<?>, Mono<Void>> handler, RSocketRequester requester, <add> @Nullable MimeType defaultDataMimeType, DataBufferFactory bufferFactory) { <ide> <ide> Assert.notNull(handler, "'handler' is required"); <del> Assert.notNull(sendingRSocket, "'sendingRSocket' is required"); <add> Assert.notNull(requester, "'requester' is required"); <ide> this.handler = handler; <del> this.requester = RSocketRequester.create(sendingRSocket, defaultDataMimeType, strategies); <add> this.requester = requester; <ide> this.dataMimeType = defaultDataMimeType; <del> this.strategies = strategies; <add> this.bufferFactory = bufferFactory; <ide> } <ide> <ide> <ide> private String getDestination(Payload payload) { <ide> } <ide> <ide> private DataBuffer retainDataAndReleasePayload(Payload payload) { <del> return PayloadUtils.retainDataAndReleasePayload(payload, this.strategies.dataBufferFactory()); <add> return PayloadUtils.retainDataAndReleasePayload(payload, this.bufferFactory); <ide> } <ide> <ide> private MessageHeaders createHeaders(String destination, @Nullable MonoProcessor<?> replyMono) { <ide> private MessageHeaders createHeaders(String destination, @Nullable MonoProcessor <ide> if (replyMono != null) { <ide> headers.setHeader(RSocketPayloadReturnValueHandler.RESPONSE_HEADER, replyMono); <ide> } <del> DataBufferFactory bufferFactory = this.strategies.dataBufferFactory(); <del> headers.setHeader(HandlerMethodReturnValueHandler.DATA_BUFFER_FACTORY_HEADER, bufferFactory); <add> headers.setHeader(HandlerMethodReturnValueHandler.DATA_BUFFER_FACTORY_HEADER, this.bufferFactory); <ide> return headers.getMessageHeaders(); <ide> } <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java <ide> static RSocketRequester.Builder builder() { <ide> return new DefaultRSocketRequesterBuilder(); <ide> } <ide> <add> /** <add> * Wrap an existing {@link RSocket}. Typically used in a client or server <add> * responder to wrap the remote {@code RSocket}. <add> * @param rsocket the RSocket to wrap <add> * @param dataMimeType the data MimeType, obtained from the <add> * {@link io.rsocket.ConnectionSetupPayload} (server) or the <add> * {@link io.rsocket.RSocketFactory.ClientRSocketFactory} (client) <add> * @param strategies the strategies to use <add> * @return the created RSocketRequester <add> */ <add> static RSocketRequester wrap(RSocket rsocket, @Nullable MimeType dataMimeType, RSocketStrategies strategies) { <add> return new DefaultRSocketRequester(rsocket, dataMimeType, strategies); <add> } <add> <ide> /** <ide> * Create a new {@code RSocketRequester} from the given {@link RSocket} and <ide> * strategies for encoding and decoding request and response payloads. <ide> * @param rsocket the sending RSocket to use <ide> * @param dataMimeType the MimeType for data (from the SETUP frame) <ide> * @param strategies encoders, decoders, and others <ide> * @return the created RSocketRequester wrapper <add> * @deprecated use {@link #wrap(RSocket, MimeType, RSocketStrategies)} instead <ide> */ <add> @Deprecated <ide> static RSocketRequester create(RSocket rsocket, @Nullable MimeType dataMimeType, RSocketStrategies strategies) { <ide> return new DefaultRSocketRequester(rsocket, dataMimeType, strategies); <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java <ide> public void setUp() { <ide> .encoder(CharSequenceEncoder.allMimeTypes()) <ide> .build(); <ide> this.rsocket = new TestRSocket(); <del> this.requester = RSocketRequester.create(rsocket, MimeTypeUtils.TEXT_PLAIN, strategies); <add> this.requester = RSocketRequester.wrap(this.rsocket, MimeTypeUtils.TEXT_PLAIN, strategies); <ide> } <ide> <ide>
5
PHP
PHP
fix meridian tests failing around tz offset issues
4e6cb44dd39c169be9b690d9d617148ada9b2be9
<ide><path>src/View/Helper/FormHelper.php <ide> public function meridian($fieldName, array $options = []) <ide> $options = $this->_singleDatetime($options, 'meridian'); <ide> <ide> if (isset($options['val'])) { <add> $hour = date('H'); <ide> $options['val'] = [ <del> 'hour' => date('H'), <add> 'hour' => $hour, <ide> 'minute' => (int)$options['val'], <add> 'meridian' => $hour > 11 ? 'pm' : 'am', <ide> ]; <ide> } <ide> return $this->datetime($fieldName, $options); <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testMeridian() <ide> { <ide> extract($this->dateRegex); <ide> <del> $now = time(); <add> $now = new \DateTime(); <ide> $result = $this->Form->meridian('Model.field', ['value' => 'am']); <ide> $expected = [ <ide> ['select' => ['name' => 'Model[field][meridian]']], <ide> ['option' => ['value' => '']], <ide> '/option', <ide> $meridianRegex, <del> ['option' => ['value' => date('a', $now), 'selected' => 'selected']], <del> date('a', $now), <add> ['option' => ['value' => $now->format('a'), 'selected' => 'selected']], <add> $now->format('a'), <ide> '/option', <ide> '*/select' <ide> ];
2
Javascript
Javascript
add strict equalities in src/core/core.js
83a4c68df9ab8c9703d3da2c424db0b08926da2a
<ide><path>src/core/core.js <ide> var PDFDocument = (function PDFDocumentClosure() { <ide> var str = strBuf.join(''); <ide> stream.pos = pos; <ide> var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle); <del> if (index == -1) { <add> if (index === -1) { <ide> return false; /* not found */ <ide> } <ide> stream.pos += index;
1
Python
Python
add retagging images accross repos
bccb45f5fe067ffa64f5f303bfbb6e8c1b552add
<ide><path>dev/retag_docker_images.py <ide> <ide> PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] <ide> <del>GHCR_IO_PREFIX = "ghcr.io/apache/airflow" <add>GHCR_IO_PREFIX = "ghcr.io" <add> <ide> <ide> GHCR_IO_IMAGES = [ <del> "{prefix}/{branch}/ci-manifest/python{python_version}:latest", <del> "{prefix}/{branch}/ci/python{python_version}:latest", <del> "{prefix}/{branch}/prod-build/python{python_version}-build:latest", <del> "{prefix}/{branch}/prod/python{python_version}-build:latest", <del> "{prefix}/{branch}/python:{python_version}-slim-buster", <add> "{prefix}/{repo}/{branch}/ci-manifest/python{python_version}:latest", <add> "{prefix}/{repo}/{branch}/ci/python{python_version}:latest", <add> "{prefix}/{repo}/{branch}/prod-build/python{python_version}:latest", <add> "{prefix}/{repo}/{branch}/prod/python{python_version}:latest", <add> "{prefix}/{repo}/{branch}/python:{python_version}-slim-buster", <ide> ] <ide> <ide> <ide> # noinspection StrFormat <ide> def pull_push_all_images( <del> source_prefix: str, target_prefix: str, images: List[str], source_branch: str, target_branch: str <add> source_prefix: str, <add> target_prefix: str, <add> images: List[str], <add> source_branch: str, <add> source_repo: str, <add> target_branch: str, <add> target_repo: str, <ide> ): <ide> for python_version in PYTHON_VERSIONS: <ide> for image in images: <ide> source_image = image.format( <del> prefix=source_prefix, branch=source_branch, python_version=python_version <add> prefix=source_prefix, branch=source_branch, repo=source_repo, python_version=python_version <ide> ) <ide> target_image = image.format( <del> prefix=target_prefix, branch=target_branch, python_version=python_version <add> prefix=target_prefix, branch=target_branch, repo=target_repo, python_version=python_version <ide> ) <ide> print(f"Copying image: {source_image} -> {target_image}") <ide> subprocess.run(["docker", "pull", source_image], check=True) <ide> def pull_push_all_images( <ide> @click.group(invoke_without_command=True) <ide> @click.option("--source-branch", type=str, default="main", help="Source branch name [main]") <ide> @click.option("--target-branch", type=str, default="main", help="Target branch name [main]") <add>@click.option("--source-repo", type=str, default="apache/airflow", help="Source repo") <add>@click.option("--target-repo", type=str, default="apache/airflow", help="Target repo") <ide> def main( <ide> source_branch: str, <ide> target_branch: str, <add> source_repo: str, <add> target_repo: str, <ide> ): <del> pull_push_all_images(GHCR_IO_PREFIX, GHCR_IO_PREFIX, GHCR_IO_IMAGES, source_branch, target_branch) <add> pull_push_all_images( <add> GHCR_IO_PREFIX, GHCR_IO_PREFIX, GHCR_IO_IMAGES, source_branch, source_repo, target_branch, target_repo <add> ) <ide> <ide> <ide> if __name__ == "__main__":
1
Text
Text
add v3.14.3 to changelog.md
8444ca8831dab1f968c2af45089f16bcea633d98
<ide><path>CHANGELOG.md <ide> - [#18491](https://github.com/emberjs/ember.js/pull/18491) [DEPRECATION] Deprecate `{{partial}}` per [RFC #449](https://github.com/emberjs/rfcs/blob/master/text/0449-deprecate-partials.md). <ide> - [#18441](https://github.com/emberjs/ember.js/pull/18441) [DEPRECATION] Deprecate window.ENV <ide> <add>### v3.14.3 (December 3, 2019) <add> <add>- [#18582](https://github.com/emberjs/ember.js/pull/18582) [BUGFIX release] Ensure `loader.js` is transpiled to the applications specified targets (from `config/targets.js`). <add> <ide> ### v3.14.2 (November 20, 2019) <ide> <ide> - [#18539](https://github.com/emberjs/ember.js/pull/18539) / [#18548](https://github.com/emberjs/ember.js/pull/18548) [BUGFIX] Fix issues with the new APIs to be used by ember-inspector for building the "component's tree" including `@glimmer/component`.
1
Javascript
Javascript
add big proxy failing test
6732e7fa1794d49078ac34fd0541dfa77c1df36d
<ide><path>test/pummel/test-http-big-proxy-responses.js <add>require('../common'); <add>var sys = require("sys"), <add>fs = require("fs"), <add>http = require("http"), <add>url = require("url"); <add> <add>// Produce a very large response. <add>var chargen = http.createServer(function (req, res) { <add> var chunk = '01234567890123456789'; <add> var len = req.headers['x-len']; <add> res.writeHead(200, {"transfer-encoding":"chunked"}); <add> for (var i=0; i<len; i++) { <add> res.write(chunk); <add> } <add> res.end(); <add>}); <add>chargen.listen(9000); <add> <add>// Proxy to the chargen server. <add>var proxy = http.createServer(function (req, res) { <add> var proxy_req = http.createClient(9000, 'localhost') <add> .request(req.method, req.url, req.headers); <add> proxy_req.addListener('response', function(proxy_res) { <add> res.writeHead(proxy_res.statusCode, proxy_res.headers); <add> proxy_res.addListener('data', function(chunk) { <add> res.write(chunk); <add> }); <add> proxy_res.addListener('end', function() { <add> res.end(); <add> }); <add> }); <add> proxy_req.end(); <add>}); <add>proxy.listen(9001); <add> <add>var done = false; <add> <add>function call_chargen(list) { <add> if (list.length > 0) { <add> sys.debug("calling chargen for " + list[0] + " chunks."); <add> var req = http.createClient(9001, 'localhost').request('/', {'x-len': list[0]}); <add> req.addListener('response', function(res) { <add> res.addListener('end', function() { <add> sys.debug("end for " + list[0] + " chunks."); <add> list.shift(); <add> call_chargen(list); <add> }); <add> }); <add> req.end(); <add> } <add> else { <add> sys.puts("End of list."); <add> proxy.end(); <add> chargen.end(); <add> done = true; <add> } <add>} <add> <add>call_chargen([ 100, 1000, 10000, 100000, 1000000 ]); <add> <add>process.addListener('exit', function () { <add> assert.ok(done); <add>});
1
Python
Python
fix race condition between triggerer and scheduler
2a6792d94d153c6f2dd116843a43ee63cd296c8d
<ide><path>airflow/executors/base_executor.py <ide> """Base executor - this is the base class for all the implemented executors.""" <ide> import sys <ide> from collections import OrderedDict <del>from typing import Any, Dict, List, Optional, Set, Tuple, Union <add>from typing import Any, Counter, Dict, List, Optional, Set, Tuple, Union <ide> <ide> from airflow.configuration import conf <ide> from airflow.models.taskinstance import TaskInstance, TaskInstanceKey <ide> <ide> NOT_STARTED_MESSAGE = "The executor should be started first!" <ide> <add>QUEUEING_ATTEMPTS = 5 <add> <ide> # Command to execute - list of strings <ide> # the first element is always "airflow". <ide> # It should be result of TaskInstance.generate_command method.q <ide> def __init__(self, parallelism: int = PARALLELISM): <ide> self.queued_tasks: OrderedDict[TaskInstanceKey, QueuedTaskInstanceType] = OrderedDict() <ide> self.running: Set[TaskInstanceKey] = set() <ide> self.event_buffer: Dict[TaskInstanceKey, EventBufferValueType] = {} <add> self.attempts: Counter[TaskInstanceKey] = Counter() <ide> <ide> def __repr__(self): <ide> return f"{self.__class__.__name__}(parallelism={self.parallelism})" <ide> def queue_command( <ide> queue: Optional[str] = None, <ide> ): <ide> """Queues command to task""" <del> if task_instance.key not in self.queued_tasks and task_instance.key not in self.running: <add> if task_instance.key not in self.queued_tasks: <ide> self.log.info("Adding to queue: %s", command) <ide> self.queued_tasks[task_instance.key] = (command, priority, queue, task_instance) <ide> else: <ide> def trigger_tasks(self, open_slots: int) -> None: <ide> <ide> for _ in range(min((open_slots, len(self.queued_tasks)))): <ide> key, (command, _, queue, ti) = sorted_queue.pop(0) <del> self.queued_tasks.pop(key) <del> self.running.add(key) <del> self.execute_async(key=key, command=command, queue=queue, executor_config=ti.executor_config) <add> <add> # If a task makes it here but is still understood by the executor <add> # to be running, it generally means that the task has been killed <add> # externally and not yet been marked as failed. <add> # <add> # However, when a task is deferred, there is also a possibility of <add> # a race condition where a task might be scheduled again during <add> # trigger processing, even before we are able to register that the <add> # deferred task has completed. In this case and for this reason, <add> # we make a small number of attempts to see if the task has been <add> # removed from the running set in the meantime. <add> if key in self.running: <add> attempt = self.attempts[key] <add> if attempt < QUEUEING_ATTEMPTS - 1: <add> self.attempts[key] = attempt + 1 <add> self.log.info("task %s is still running", key) <add> continue <add> <add> # We give up and remove the task from the queue. <add> self.log.error("could not queue task %s (still running after %d attempts)", key, attempt) <add> del self.attempts[key] <add> del self.queued_tasks[key] <add> else: <add> del self.queued_tasks[key] <add> self.running.add(key) <add> self.execute_async(key=key, command=command, queue=queue, executor_config=ti.executor_config) <ide> <ide> def change_state(self, key: TaskInstanceKey, state: str, info=None) -> None: <ide> """ <ide><path>tests/executors/test_base_executor.py <ide> from datetime import timedelta <ide> from unittest import mock <ide> <del>from airflow.executors.base_executor import BaseExecutor <add>from pytest import mark <add> <add>from airflow.executors.base_executor import QUEUEING_ATTEMPTS, BaseExecutor <ide> from airflow.models.baseoperator import BaseOperator <ide> from airflow.models.taskinstance import TaskInstanceKey <ide> from airflow.utils import timezone <ide> def test_gauge_executor_metrics(mock_stats_gauge, mock_trigger_tasks, mock_sync) <ide> mock_stats_gauge.assert_has_calls(calls) <ide> <ide> <del>def test_try_adopt_task_instances(dag_maker): <add>def setup_dagrun(dag_maker): <ide> date = timezone.utcnow() <ide> start_date = date - timedelta(days=2) <ide> <ide> def test_try_adopt_task_instances(dag_maker): <ide> BaseOperator(task_id="task_2", start_date=start_date) <ide> BaseOperator(task_id="task_3", start_date=start_date) <ide> <del> dagrun = dag_maker.create_dagrun(execution_date=date) <del> tis = dagrun.task_instances <add> return dag_maker.create_dagrun(execution_date=date) <ide> <add> <add>def test_try_adopt_task_instances(dag_maker): <add> dagrun = setup_dagrun(dag_maker) <add> tis = dagrun.task_instances <ide> assert {ti.task_id for ti in tis} == {"task_1", "task_2", "task_3"} <ide> assert BaseExecutor().try_adopt_task_instances(tis) == tis <add> <add> <add>def enqueue_tasks(executor, dagrun): <add> for task_instance in dagrun.task_instances: <add> executor.queue_command(task_instance, ["airflow"]) <add> <add> <add>def setup_trigger_tasks(dag_maker): <add> dagrun = setup_dagrun(dag_maker) <add> executor = BaseExecutor() <add> executor.execute_async = mock.Mock() <add> enqueue_tasks(executor, dagrun) <add> return executor, dagrun <add> <add> <add>@mark.parametrize("open_slots", [1, 2, 3]) <add>def test_trigger_queued_tasks(dag_maker, open_slots): <add> executor, _ = setup_trigger_tasks(dag_maker) <add> executor.trigger_tasks(open_slots) <add> assert len(executor.execute_async.mock_calls) == open_slots <add> <add> <add>@mark.parametrize("change_state_attempt", range(QUEUEING_ATTEMPTS + 2)) <add>def test_trigger_running_tasks(dag_maker, change_state_attempt): <add> executor, dagrun = setup_trigger_tasks(dag_maker) <add> open_slots = 100 <add> executor.trigger_tasks(open_slots) <add> expected_calls = len(dagrun.task_instances) # initially `execute_async` called for each task <add> assert len(executor.execute_async.mock_calls) == expected_calls <add> <add> # All the tasks are now "running", so while we enqueue them again here, <add> # they won't be executed again until the executor has been notified of a state change. <add> enqueue_tasks(executor, dagrun) <add> <add> for attempt in range(QUEUEING_ATTEMPTS + 2): <add> # On the configured attempt, we notify the executor that the task has succeeded. <add> if attempt == change_state_attempt: <add> executor.change_state(dagrun.task_instances[0].key, State.SUCCESS) <add> # If we have not exceeded QUEUEING_ATTEMPTS, we should expect an additional "execute" call <add> if attempt < QUEUEING_ATTEMPTS: <add> expected_calls += 1 <add> executor.trigger_tasks(open_slots) <add> assert len(executor.execute_async.mock_calls) == expected_calls <add> if change_state_attempt < QUEUEING_ATTEMPTS: <add> assert len(executor.execute_async.mock_calls) == len(dagrun.task_instances) + 1 <add> else: <add> assert len(executor.execute_async.mock_calls) == len(dagrun.task_instances)
2
Ruby
Ruby
allow bottles with custom architectures
e893f16727d167390dacd9b2ed5eb6d5df103d70
<ide><path>Library/Homebrew/extend/ENV/super.rb <ide> def determine_make_jobs <ide> sig { returns(String) } <ide> def determine_optflags <ide> Hardware::CPU.optimization_flags.fetch(effective_arch) <add> rescue KeyError <add> odebug "Building a bottle for custom architecture (#{effective_arch})..." <add> Hardware::CPU.arch_flag(effective_arch) <ide> end <ide> <ide> sig { returns(String) } <ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> <ide> return if only_deps? <ide> <del> if build_bottle? && (arch = @bottle_arch) && Hardware::CPU.optimization_flags.exclude?(arch.to_sym) <del> raise CannotInstallFormulaError, "Unrecognized architecture for --bottle-arch: #{arch}" <del> end <del> <ide> formula.deprecated_flags.each do |deprecated_option| <ide> old_flag = deprecated_option.old_flag <ide> new_flag = deprecated_option.current_flag
2
Javascript
Javascript
remove "lastid" as there is no usecase
5b4836d185b3f127e686dc5628ace6e7f8dda53a
<ide><path>lib/Compilation.js <ide> class Compilation extends Tapable { <ide> cacheModule.errors.forEach(err => this.errors.push(err), this); <ide> cacheModule.warnings.forEach(err => this.warnings.push(err), this); <ide> return cacheModule; <del> } else { <del> module.lastId = cacheModule.id; <ide> } <ide> } <ide> module.unbuild(); <ide><path>lib/Module.js <ide> class Module extends DependenciesBlock { <ide> this.context = null; <ide> this.reasons = []; <ide> this.debugId = debugId++; <del> this.lastId = -1; <ide> this.id = null; <ide> this.portableId = null; <ide> this.index = null; <ide> class Module extends DependenciesBlock { <ide> <ide> disconnect() { <ide> this.reasons.length = 0; <del> this.lastId = this.id; <ide> this.id = null; <ide> this.index = null; <ide> this.index2 = null; <ide> class Module extends DependenciesBlock { <ide> } <ide> <ide> unseal() { <del> this.lastId = this.id; <ide> this.id = null; <ide> this.index = null; <ide> this.index2 = null;
2
Javascript
Javascript
fix global font settings
8d5b3809f6a607ebf2be7af40fb538ea5e42c4db
<ide><path>src/core/core.legend.js <ide> module.exports = function(Chart) { <ide> <ide> labels: { <ide> boxWidth: 40, <del> fontSize: Chart.defaults.global.defaultFontSize, <del> fontStyle: Chart.defaults.global.defaultFontStyle, <del> fontColor: Chart.defaults.global.defaultFontColor, <del> fontFamily: Chart.defaults.global.defaultFontFamily, <ide> padding: 10, <ide> // Generates labels shown in the legend <ide> // Valid properties to return: <ide> module.exports = function(Chart) { <ide> fit: function() { <ide> <ide> var ctx = this.ctx; <del> var labelFont = helpers.fontString(this.options.labels.fontSize, this.options.labels.fontStyle, this.options.labels.fontFamily); <add> var fontSize = helpers.getValueOrDefault(this.options.labels.fontSize, Chart.defaults.global.defaultFontSize); <add> var fontStyle = helpers.getValueOrDefault(this.options.labels.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var fontFamily = helpers.getValueOrDefault(this.options.labels.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); <ide> <ide> // Reset hit boxes <ide> this.legendHitBoxes = []; <ide> module.exports = function(Chart) { <ide> <ide> // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one <ide> this.lineWidths = [0]; <del> var totalHeight = this.legendItems.length ? this.options.labels.fontSize + (this.options.labels.padding) : 0; <add> var totalHeight = this.legendItems.length ? fontSize + (this.options.labels.padding) : 0; <ide> <ide> ctx.textAlign = "left"; <ide> ctx.textBaseline = 'top'; <ide> ctx.font = labelFont; <ide> <ide> helpers.each(this.legendItems, function(legendItem, i) { <del> var width = this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + ctx.measureText(legendItem.text).width; <add> var width = this.options.labels.boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; <ide> if (this.lineWidths[this.lineWidths.length - 1] + width + this.options.labels.padding >= this.width) { <del> totalHeight += this.options.labels.fontSize + (this.options.labels.padding); <add> totalHeight += fontSize + (this.options.labels.padding); <ide> this.lineWidths[this.lineWidths.length] = this.left; <ide> } <ide> <ide> module.exports = function(Chart) { <ide> left: 0, <ide> top: 0, <ide> width: width, <del> height: this.options.labels.fontSize <add> height: fontSize <ide> }; <ide> <ide> this.lineWidths[this.lineWidths.length - 1] += width + this.options.labels.padding; <ide> module.exports = function(Chart) { <ide> line: 0 <ide> }; <ide> <del> var labelFont = helpers.fontString(this.options.labels.fontSize, this.options.labels.fontStyle, this.options.labels.fontFamily); <add> var fontColor = helpers.getValueOrDefault(this.options.labels.fontColor, Chart.defaults.global.defaultFontColor); <add> var fontSize = helpers.getValueOrDefault(this.options.labels.fontSize, Chart.defaults.global.defaultFontSize); <add> var fontStyle = helpers.getValueOrDefault(this.options.labels.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var fontFamily = helpers.getValueOrDefault(this.options.labels.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); <ide> <ide> // Horizontal <ide> if (this.isHorizontal()) { <ide> // Labels <ide> ctx.textAlign = "left"; <ide> ctx.textBaseline = 'top'; <ide> ctx.lineWidth = 0.5; <del> ctx.strokeStyle = this.options.labels.fontColor; // for strikethrough effect <del> ctx.fillStyle = this.options.labels.fontColor; // render in correct colour <add> ctx.strokeStyle = fontColor; // for strikethrough effect <add> ctx.fillStyle = fontColor; // render in correct colour <ide> ctx.font = labelFont; <ide> <ide> helpers.each(this.legendItems, function(legendItem, i) { <ide> var textWidth = ctx.measureText(legendItem.text).width; <del> var width = this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + textWidth; <add> var width = this.options.labels.boxWidth + (fontSize / 2) + textWidth; <ide> <ide> if (cursor.x + width >= this.width) { <del> cursor.y += this.options.labels.fontSize + (this.options.labels.padding); <add> cursor.y += fontSize + (this.options.labels.padding); <ide> cursor.line++; <ide> cursor.x = this.left + ((this.width - this.lineWidths[cursor.line]) / 2); <ide> } <ide> module.exports = function(Chart) { <ide> } <ide> <ide> // Draw the box <del> ctx.strokeRect(cursor.x, cursor.y, this.options.labels.boxWidth, this.options.labels.fontSize); <del> ctx.fillRect(cursor.x, cursor.y, this.options.labels.boxWidth, this.options.labels.fontSize); <add> ctx.strokeRect(cursor.x, cursor.y, this.options.labels.boxWidth, fontSize); <add> ctx.fillRect(cursor.x, cursor.y, this.options.labels.boxWidth, fontSize); <ide> <ide> ctx.restore(); <ide> <ide> this.legendHitBoxes[i].left = cursor.x; <ide> this.legendHitBoxes[i].top = cursor.y; <ide> <ide> // Fill the actual label <del> ctx.fillText(legendItem.text, this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x, cursor.y); <add> ctx.fillText(legendItem.text, this.options.labels.boxWidth + (fontSize / 2) + cursor.x, cursor.y); <ide> <ide> if (legendItem.hidden) { <ide> // Strikethrough the text if hidden <ide> ctx.beginPath(); <ide> ctx.lineWidth = 2; <del> ctx.moveTo(this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x, cursor.y + (this.options.labels.fontSize / 2)); <del> ctx.lineTo(this.options.labels.boxWidth + (this.options.labels.fontSize / 2) + cursor.x + textWidth, cursor.y + (this.options.labels.fontSize / 2)); <add> ctx.moveTo(this.options.labels.boxWidth + (fontSize / 2) + cursor.x, cursor.y + (fontSize / 2)); <add> ctx.lineTo(this.options.labels.boxWidth + (fontSize / 2) + cursor.x + textWidth, cursor.y + (fontSize / 2)); <ide> ctx.stroke(); <ide> } <ide> <ide><path>src/core/core.scale.js <ide> module.exports = function(Chart) { <ide> <ide> // scale label <ide> scaleLabel: { <del> fontColor: Chart.defaults.global.defaultFontColor, <del> fontFamily: Chart.defaults.global.defaultFontFamily, <del> fontSize: Chart.defaults.global.defaultFontSize, <del> fontStyle: Chart.defaults.global.defaultFontStyle, <del> <ide> // actual label <ide> labelString: '', <ide> <ide> module.exports = function(Chart) { <ide> // label settings <ide> ticks: { <ide> beginAtZero: false, <del> fontSize: Chart.defaults.global.defaultFontSize, <del> fontStyle: Chart.defaults.global.defaultFontStyle, <del> fontColor: Chart.defaults.global.defaultFontColor, <del> fontFamily: Chart.defaults.global.defaultFontFamily, <ide> maxRotation: 90, <ide> mirror: false, <ide> padding: 10, <ide> module.exports = function(Chart) { <ide> calculateTickRotation: function() { <ide> //Get the width of each grid by calculating the difference <ide> //between x offsets between 0 and 1. <del> var labelFont = helpers.fontString(this.options.ticks.fontSize, this.options.ticks.fontStyle, this.options.ticks.fontFamily); <del> this.ctx.font = labelFont; <add> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <add> var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); <add> this.ctx.font = tickLabelFont; <ide> <ide> var firstWidth = this.ctx.measureText(this.ticks[0]).width; <ide> var lastWidth = this.ctx.measureText(this.ticks[this.ticks.length - 1]).width; <ide> module.exports = function(Chart) { <ide> if (!this.longestTextCache) { <ide> this.longestTextCache = {}; <ide> } <del> var originalLabelWidth = helpers.longestText(this.ctx, labelFont, this.ticks, this.longestTextCache); <add> var originalLabelWidth = helpers.longestText(this.ctx, tickLabelFont, this.ticks, this.longestTextCache); <ide> var labelWidth = originalLabelWidth; <ide> var cosRotation; <ide> var sinRotation; <ide> module.exports = function(Chart) { <ide> firstRotated = cosRotation * firstWidth; <ide> <ide> // We're right aligning the text now. <del> if (firstRotated + this.options.ticks.fontSize / 2 > this.yLabelWidth) { <del> this.paddingLeft = firstRotated + this.options.ticks.fontSize / 2; <add> if (firstRotated + tickFontSize / 2 > this.yLabelWidth) { <add> this.paddingLeft = firstRotated + tickFontSize / 2; <ide> } <ide> <del> this.paddingRight = this.options.ticks.fontSize / 2; <add> this.paddingRight = tickFontSize / 2; <ide> <ide> if (sinRotation * originalLabelWidth > this.maxHeight) { <ide> // go back one step <ide> module.exports = function(Chart) { <ide> height: 0 <ide> }; <ide> <add> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <add> var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); <add> <add> var scaleLabelFontSize = helpers.getValueOrDefault(this.options.scaleLabel.fontSize, Chart.defaults.global.defaultFontSize); <add> var scaleLabelFontStyle = helpers.getValueOrDefault(this.options.scaleLabel.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var scaleLabelFontFamily = helpers.getValueOrDefault(this.options.scaleLabel.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var scaleLabelFont = helpers.fontString(scaleLabelFontSize, scaleLabelFontStyle, scaleLabelFontFamily); <add> <ide> // Width <ide> if (this.isHorizontal()) { <ide> // subtract the margins to line up with the chartArea if we are a full width scale <ide> module.exports = function(Chart) { <ide> // Are we showing a title for the scale? <ide> if (this.options.scaleLabel.display) { <ide> if (this.isHorizontal()) { <del> this.minSize.height += (this.options.scaleLabel.fontSize * 1.5); <add> this.minSize.height += (scaleLabelFontSize * 1.5); <ide> } else { <del> this.minSize.width += (this.options.scaleLabel.fontSize * 1.5); <add> this.minSize.width += (scaleLabelFontSize * 1.5); <ide> } <ide> } <ide> <ide> if (this.options.ticks.display && this.options.display) { <ide> // Don't bother fitting the ticks if we are not showing them <del> var labelFont = helpers.fontString(this.options.ticks.fontSize, <del> this.options.ticks.fontStyle, this.options.ticks.fontFamily); <del> <ide> if (!this.longestTextCache) { <ide> this.longestTextCache = {}; <ide> } <ide> <del> var largestTextWidth = helpers.longestText(this.ctx, labelFont, this.ticks, this.longestTextCache); <add> var largestTextWidth = helpers.longestText(this.ctx, tickLabelFont, this.ticks, this.longestTextCache); <ide> <ide> if (this.isHorizontal()) { <ide> // A horizontal axis is more constrained by the height. <ide> this.longestLabelWidth = largestTextWidth; <ide> <ide> // TODO - improve this calculation <del> var labelHeight = (Math.sin(helpers.toRadians(this.labelRotation)) * this.longestLabelWidth) + 1.5 * this.options.ticks.fontSize; <add> var labelHeight = (Math.sin(helpers.toRadians(this.labelRotation)) * this.longestLabelWidth) + 1.5 * tickFontSize; <ide> <ide> this.minSize.height = Math.min(this.maxHeight, this.minSize.height + labelHeight); <del> <del> labelFont = helpers.fontString(this.options.ticks.fontSize, this.options.ticks.fontStyle, this.options.ticks.fontFamily); <del> this.ctx.font = labelFont; <add> this.ctx.font = tickLabelFont; <ide> <ide> var firstLabelWidth = this.ctx.measureText(this.ticks[0]).width; <ide> var lastLabelWidth = this.ctx.measureText(this.ticks[this.ticks.length - 1]).width; <ide> module.exports = function(Chart) { <ide> var cosRotation = Math.cos(helpers.toRadians(this.labelRotation)); <ide> var sinRotation = Math.sin(helpers.toRadians(this.labelRotation)); <ide> this.paddingLeft = this.labelRotation !== 0 ? (cosRotation * firstLabelWidth) + 3 : firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges <del> this.paddingRight = this.labelRotation !== 0 ? (sinRotation * (this.options.ticks.fontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated <add> this.paddingRight = this.labelRotation !== 0 ? (sinRotation * (tickFontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated <ide> } else { <ide> // A vertical axis is more constrained by the width. Labels are the dominant factor here, so get that length first <ide> var maxLabelWidth = this.maxWidth - this.minSize.width; <ide> module.exports = function(Chart) { <ide> this.minSize.width = this.maxWidth; <ide> } <ide> <del> this.paddingTop = this.options.ticks.fontSize / 2; <del> this.paddingBottom = this.options.ticks.fontSize / 2; <add> this.paddingTop = tickFontSize / 2; <add> this.paddingBottom = tickFontSize / 2; <ide> } <ide> } <ide> <ide> module.exports = function(Chart) { <ide> maxTicks = this.options.ticks.maxTicksLimit; <ide> } <ide> <del> // Make sure we draw text in the correct color and font <del> this.ctx.fillStyle = this.options.ticks.fontColor; <del> var labelFont = helpers.fontString(this.options.ticks.fontSize, this.options.ticks.fontStyle, this.options.ticks.fontFamily); <add> var tickFontColor = helpers.getValueOrDefault(this.options.ticks.fontColor, Chart.defaults.global.defaultFontColor); <add> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <add> var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); <add> <add> var scaleLabelFontColor = helpers.getValueOrDefault(this.options.scaleLabel.fontColor, Chart.defaults.global.defaultFontColor); <add> var scaleLabelFontSize = helpers.getValueOrDefault(this.options.scaleLabel.fontSize, Chart.defaults.global.defaultFontSize); <add> var scaleLabelFontStyle = helpers.getValueOrDefault(this.options.scaleLabel.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var scaleLabelFontFamily = helpers.getValueOrDefault(this.options.scaleLabel.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var scaleLabelFont = helpers.fontString(scaleLabelFontSize, scaleLabelFontStyle, scaleLabelFontFamily); <ide> <ide> var cosRotation = Math.cos(helpers.toRadians(this.labelRotation)); <ide> var sinRotation = Math.sin(helpers.toRadians(this.labelRotation)); <ide> var longestRotatedLabel = this.longestLabelWidth * cosRotation; <del> var rotatedLabelHeight = this.options.ticks.fontSize * sinRotation; <add> var rotatedLabelHeight = tickFontSize * sinRotation; <add> <add> // Make sure we draw text in the correct color and font <add> this.ctx.fillStyle = tickFontColor; <ide> <ide> if (this.isHorizontal()) { <ide> setContextLineSettings = true; <ide> module.exports = function(Chart) { <ide> this.ctx.save(); <ide> this.ctx.translate(xLabelValue, (isRotated) ? this.top + 12 : this.options.position === "top" ? this.bottom - 10 : this.top + 10); <ide> this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1); <del> this.ctx.font = labelFont; <add> this.ctx.font = tickLabelFont; <ide> this.ctx.textAlign = (isRotated) ? "right" : "center"; <ide> this.ctx.textBaseline = (isRotated) ? "middle" : this.options.position === "top" ? "bottom" : "top"; <ide> this.ctx.fillText(label, 0, 0); <ide> module.exports = function(Chart) { <ide> // Draw the scale label <ide> this.ctx.textAlign = "center"; <ide> this.ctx.textBaseline = 'middle'; <del> this.ctx.fillStyle = this.options.scaleLabel.fontColor; // render in correct colour <del> this.ctx.font = helpers.fontString(this.options.scaleLabel.fontSize, this.options.scaleLabel.fontStyle, this.options.scaleLabel.fontFamily); <add> this.ctx.fillStyle = scaleLabelFontColor; // render in correct colour <add> this.ctx.font = scaleLabelFont; <ide> <ide> scaleLabelX = this.left + ((this.right - this.left) / 2); // midpoint of the width <del> scaleLabelY = this.options.position === 'bottom' ? this.bottom - (this.options.scaleLabel.fontSize / 2) : this.top + (this.options.scaleLabel.fontSize / 2); <add> scaleLabelY = this.options.position === 'bottom' ? this.bottom - (scaleLabelFontSize / 2) : this.top + (scaleLabelFontSize / 2); <ide> <ide> this.ctx.fillText(this.options.scaleLabel.labelString, scaleLabelX, scaleLabelY); <ide> } <ide> module.exports = function(Chart) { <ide> <ide> this.ctx.translate(xLabelValue, yLabelValue); <ide> this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1); <del> this.ctx.font = labelFont; <add> this.ctx.font = tickLabelFont; <ide> this.ctx.textBaseline = "middle"; <ide> this.ctx.fillText(label, 0, 0); <ide> this.ctx.restore(); <ide> module.exports = function(Chart) { <ide> <ide> if (this.options.scaleLabel.display) { <ide> // Draw the scale label <del> scaleLabelX = this.options.position === 'left' ? this.left + (this.options.scaleLabel.fontSize / 2) : this.right - (this.options.scaleLabel.fontSize / 2); <add> scaleLabelX = this.options.position === 'left' ? this.left + (scaleLabelFontSize / 2) : this.right - (scaleLabelFontSize / 2); <ide> scaleLabelY = this.top + ((this.bottom - this.top) / 2); <ide> var rotation = this.options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; <ide> <ide> this.ctx.save(); <ide> this.ctx.translate(scaleLabelX, scaleLabelY); <ide> this.ctx.rotate(rotation); <ide> this.ctx.textAlign = "center"; <del> this.ctx.fillStyle = this.options.scaleLabel.fontColor; // render in correct colour <del> this.ctx.font = helpers.fontString(this.options.scaleLabel.fontSize, this.options.scaleLabel.fontStyle, this.options.scaleLabel.fontFamily); <add> this.ctx.fillStyle =scaleLabelFontColor; // render in correct colour <add> this.ctx.font = scaleLabelFont; <ide> this.ctx.textBaseline = 'middle'; <ide> this.ctx.fillText(this.options.scaleLabel.labelString, 0, 0); <ide> this.ctx.restore(); <ide><path>src/core/core.title.js <ide> module.exports = function(Chart) { <ide> position: 'top', <ide> fullWidth: true, // marks that this box should take the full width of the canvas (pushing down other boxes) <ide> <del> fontColor: Chart.defaults.global.defaultFontColor, <del> fontFamily: Chart.defaults.global.defaultFontFamily, <del> fontSize: Chart.defaults.global.defaultFontSize, <ide> fontStyle: 'bold', <ide> padding: 10, <ide> <ide> module.exports = function(Chart) { <ide> fit: function() { <ide> <ide> var ctx = this.ctx; <del> var titleFont = helpers.fontString(this.options.fontSize, this.options.fontStyle, this.options.fontFamily); <add> var fontSize = helpers.getValueOrDefault(this.options.fontSize, Chart.defaults.global.defaultFontSize); <add> var fontStyle = helpers.getValueOrDefault(this.options.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var fontFamily = helpers.getValueOrDefault(this.options.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily); <ide> <ide> // Width <ide> if (this.isHorizontal()) { <ide> module.exports = function(Chart) { <ide> <ide> // Title <ide> if (this.options.display) { <del> this.minSize.height += this.options.fontSize + (this.options.padding * 2); <add> this.minSize.height += fontSize + (this.options.padding * 2); <ide> } <ide> } else { <ide> if (this.options.display) { <del> this.minSize.width += this.options.fontSize + (this.options.padding * 2); <add> this.minSize.width += fontSize + (this.options.padding * 2); <ide> } <ide> } <ide> <ide> module.exports = function(Chart) { <ide> var ctx = this.ctx; <ide> var titleX, titleY; <ide> <add> var fontColor = helpers.getValueOrDefault(this.options.fontColor, Chart.defaults.global.defaultFontColor); <add> var fontSize = helpers.getValueOrDefault(this.options.fontSize, Chart.defaults.global.defaultFontSize); <add> var fontStyle = helpers.getValueOrDefault(this.options.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var fontFamily = helpers.getValueOrDefault(this.options.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily); <add> <add> ctx.fillStyle = fontColor; // render in correct colour <add> ctx.font = titleFont; <add> <ide> // Horizontal <ide> if (this.isHorizontal()) { <ide> // Title <del> if (this.options.display) { <add> ctx.textAlign = "center"; <add> ctx.textBaseline = 'middle'; <ide> <del> ctx.textAlign = "center"; <del> ctx.textBaseline = 'middle'; <del> ctx.fillStyle = this.options.fontColor; // render in correct colour <del> ctx.font = helpers.fontString(this.options.fontSize, this.options.fontStyle, this.options.fontFamily); <add> titleX = this.left + ((this.right - this.left) / 2); // midpoint of the width <add> titleY = this.top + ((this.bottom - this.top) / 2); // midpoint of the height <ide> <del> titleX = this.left + ((this.right - this.left) / 2); // midpoint of the width <del> titleY = this.top + ((this.bottom - this.top) / 2); // midpoint of the height <del> <del> ctx.fillText(this.options.text, titleX, titleY); <del> } <add> ctx.fillText(this.options.text, titleX, titleY); <ide> } else { <ide> <ide> // Title <del> if (this.options.display) { <del> titleX = this.options.position === 'left' ? this.left + (this.options.fontSize / 2) : this.right - (this.options.fontSize / 2); <del> titleY = this.top + ((this.bottom - this.top) / 2); <del> var rotation = this.options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; <del> <del> ctx.save(); <del> ctx.translate(titleX, titleY); <del> ctx.rotate(rotation); <del> ctx.textAlign = "center"; <del> ctx.fillStyle = this.options.fontColor; // render in correct colour <del> ctx.font = helpers.fontString(this.options.fontSize, this.options.fontStyle, this.options.fontFamily); <del> ctx.textBaseline = 'middle'; <del> ctx.fillText(this.options.text, 0, 0); <del> ctx.restore(); <del> <del> } <del> <add> titleX = this.options.position === 'left' ? this.left + (fontSize / 2) : this.right - (fontSize / 2); <add> titleY = this.top + ((this.bottom - this.top) / 2); <add> var rotation = this.options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; <add> <add> ctx.save(); <add> ctx.translate(titleX, titleY); <add> ctx.rotate(rotation); <add> ctx.textAlign = "center"; <add> ctx.textBaseline = 'middle'; <add> ctx.fillText(this.options.text, 0, 0); <add> ctx.restore(); <ide> } <ide> } <ide> } <ide><path>src/core/core.tooltip.js <ide> module.exports = function(Chart) { <ide> custom: null, <ide> mode: 'single', <ide> backgroundColor: "rgba(0,0,0,0.8)", <del> titleFontFamily: Chart.defaults.global.defaultFontFamily, <del> titleFontSize: Chart.defaults.global.defaultFontSize, <ide> titleFontStyle: "bold", <ide> titleSpacing: 2, <ide> titleMarginBottom: 6, <ide> titleColor: "#fff", <ide> titleAlign: "left", <del> bodyFontFamily: Chart.defaults.global.defaultFontFamily, <del> bodyFontSize: Chart.defaults.global.defaultFontSize, <del> bodyFontStyle: Chart.defaults.global.defaultFontStyle, <ide> bodySpacing: 2, <ide> bodyColor: "#fff", <ide> bodyAlign: "left", <del> footerFontFamily: Chart.defaults.global.defaultFontFamily, <del> footerFontSize: Chart.defaults.global.defaultFontSize, <ide> footerFontStyle: "bold", <ide> footerSpacing: 2, <ide> footerMarginTop: 6, <ide> module.exports = function(Chart) { <ide> <ide> // Body <ide> bodyColor: options.tooltips.bodyColor, <del> _bodyFontFamily: options.tooltips.bodyFontFamily, <del> _bodyFontStyle: options.tooltips.bodyFontStyle, <add> _bodyFontFamily: helpers.getValueOrDefault(options.tooltips.bodyFontFamily, Chart.defaults.global.defaultFontFamily), <add> _bodyFontStyle: helpers.getValueOrDefault(options.tooltips.bodyFontStyle, Chart.defaults.global.defaultFontStyle), <ide> _bodyAlign: options.tooltips.bodyAlign, <del> bodyFontSize: options.tooltips.bodyFontSize, <add> bodyFontSize: helpers.getValueOrDefault(options.tooltips.bodyFontSize, Chart.defaults.global.defaultFontSize), <ide> bodySpacing: options.tooltips.bodySpacing, <ide> <ide> // Title <ide> titleColor: options.tooltips.titleColor, <del> _titleFontFamily: options.tooltips.titleFontFamily, <del> _titleFontStyle: options.tooltips.titleFontStyle, <del> titleFontSize: options.tooltips.titleFontSize, <add> _titleFontFamily: helpers.getValueOrDefault(options.tooltips.titleFontFamily, Chart.defaults.global.defaultFontFamily), <add> _titleFontStyle: helpers.getValueOrDefault(options.tooltips.titleFontStyle, Chart.defaults.global.defaultFontStyle), <add> titleFontSize: helpers.getValueOrDefault(options.tooltips.titleFontSize, Chart.defaults.global.defaultFontSize), <ide> _titleAlign: options.tooltips.titleAlign, <ide> titleSpacing: options.tooltips.titleSpacing, <ide> titleMarginBottom: options.tooltips.titleMarginBottom, <ide> <ide> // Footer <ide> footerColor: options.tooltips.footerColor, <del> _footerFontFamily: options.tooltips.footerFontFamily, <del> _footerFontStyle: options.tooltips.footerFontStyle, <del> footerFontSize: options.tooltips.footerFontSize, <add> _footerFontFamily: helpers.getValueOrDefault(options.tooltips.footerFontFamily, Chart.defaults.global.defaultFontFamily), <add> _footerFontStyle: helpers.getValueOrDefault(options.tooltips.footerFontStyle, Chart.defaults.global.defaultFontStyle), <add> footerFontSize: helpers.getValueOrDefault(options.tooltips.footerFontSize, Chart.defaults.global.defaultFontSize), <ide> _footerAlign: options.tooltips.footerAlign, <ide> footerSpacing: options.tooltips.footerSpacing, <ide> footerMarginTop: options.tooltips.footerMarginTop, <ide><path>src/scales/scale.linear.js <ide> module.exports = function(Chart) { <ide> var maxTicks; <ide> <ide> if (this.isHorizontal()) { <del> maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, <del> Math.ceil(this.width / 50)); <add> maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, Math.ceil(this.width / 50)); <ide> } else { <ide> // The factor of 2 used to scale the font size has been experimentally determined. <del> maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, <del> Math.ceil(this.height / (2 * this.options.ticks.fontSize))); <add> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <add> maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, Math.ceil(this.height / (2 * tickFontSize))); <ide> } <ide> <ide> // Make sure we always have at least 2 ticks <ide><path>src/scales/scale.radialLinear.js <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> pointLabels: { <del> //String - Point label font declaration <del> fontFamily: Chart.defaults.global.defaultFontFamily, <del> <del> //String - Point label font weight <del> fontStyle: Chart.defaults.global.defaultFontStyle, <del> <ide> //Number - Point label font size in pixels <ide> fontSize: 10, <ide> <del> //String - Point label font colour <del> fontColor: Chart.defaults.global.defaultFontColor, <del> <ide> //Function - Used to convert point labels <ide> callback: function(label) { <ide> return label; <ide> module.exports = function(Chart) { <ide> this.yCenter = Math.round(this.height / 2); <ide> <ide> var minSize = helpers.min([this.height, this.width]); <del> this.drawingArea = (this.options.display) ? (minSize / 2) - (this.options.ticks.fontSize / 2 + this.options.ticks.backdropPaddingY) : (minSize / 2); <add> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <add> this.drawingArea = (this.options.display) ? (minSize / 2) - (tickFontSize / 2 + this.options.ticks.backdropPaddingY) : (minSize / 2); <ide> }, <ide> determineDataLimits: function() { <ide> this.min = null; <ide> module.exports = function(Chart) { <ide> // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 <ide> // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on <ide> // the graph <del> var maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, <del> Math.ceil(this.drawingArea / (1.5 * this.options.ticks.fontSize))); <add> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <add> var maxTicks = Math.min(this.options.ticks.maxTicksLimit ? this.options.ticks.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize))); <ide> maxTicks = Math.max(2, maxTicks); // Make sure we always have at least 2 ticks <ide> <ide> // To get a "nice" value for the tick spacing, we will use the appropriately named <ide> module.exports = function(Chart) { <ide> * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif <ide> */ <ide> <add> var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize); <add> var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var pointLabeFontFamily = helpers.getValueOrDefault(this.options.pointLabels.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily); <ide> <ide> // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. <ide> // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points <del> var largestPossibleRadius = helpers.min([(this.height / 2 - this.options.pointLabels.fontSize - 5), this.width / 2]), <add> var largestPossibleRadius = helpers.min([(this.height / 2 - pointLabelFontSize - 5), this.width / 2]), <ide> pointPosition, <ide> i, <ide> textWidth, <ide> module.exports = function(Chart) { <ide> radiusReductionRight, <ide> radiusReductionLeft, <ide> maxWidthRadius; <del> this.ctx.font = helpers.fontString(this.options.pointLabels.fontSize, this.options.pointLabels.fontStyle, this.options.pointLabels.fontFamily); <add> this.ctx.font = pointLabeFont; <add> <ide> for (i = 0; i < this.getValueCount(); i++) { <ide> // 5px to space the text slightly out - similar to what we do in the draw function. <ide> pointPosition = this.getPointPosition(i, largestPossibleRadius); <ide> module.exports = function(Chart) { <ide> } <ide> <ide> if (this.options.ticks.display) { <del> ctx.font = helpers.fontString(this.options.ticks.fontSize, this.options.ticks.fontStyle, this.options.ticks.fontFamily); <add> var tickFontColor = helpers.getValueOrDefault(this.options.ticks.fontColor, Chart.defaults.global.defaultFontColor); <add> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <add> var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); <add> ctx.font = tickLabelFont; <ide> <ide> if (this.options.ticks.showLabelBackdrop) { <ide> var labelWidth = ctx.measureText(label).width; <ide> ctx.fillStyle = this.options.ticks.backdropColor; <ide> ctx.fillRect( <ide> this.xCenter - labelWidth / 2 - this.options.ticks.backdropPaddingX, <del> yHeight - this.options.ticks.fontSize / 2 - this.options.ticks.backdropPaddingY, <add> yHeight - tickFontSize / 2 - this.options.ticks.backdropPaddingY, <ide> labelWidth + this.options.ticks.backdropPaddingX * 2, <del> this.options.ticks.fontSize + this.options.ticks.backdropPaddingY * 2 <add> tickFontSize + this.options.ticks.backdropPaddingY * 2 <ide> ); <ide> } <ide> <ide> ctx.textAlign = 'center'; <ide> ctx.textBaseline = "middle"; <del> ctx.fillStyle = this.options.ticks.fontColor; <add> ctx.fillStyle = tickFontColor; <ide> ctx.fillText(label, this.xCenter, yHeight); <ide> } <ide> } <ide> module.exports = function(Chart) { <ide> } <ide> // Extra 3px out for some label spacing <ide> var pointLabelPosition = this.getPointPosition(i, this.getDistanceFromCenterForValue(this.options.reverse ? this.min : this.max) + 5); <del> ctx.font = helpers.fontString(this.options.pointLabels.fontSize, this.options.pointLabels.fontStyle, this.options.pointLabels.fontFamily); <del> ctx.fillStyle = this.options.pointLabels.fontColor; <add> <add> var pointLabelFontColor = helpers.getValueOrDefault(this.options.pointLabels.fontColor, Chart.defaults.global.defaultFontColor); <add> var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize); <add> var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var pointLabeFontFamily = helpers.getValueOrDefault(this.options.pointLabels.fontFamily, Chart.defaults.global.defaultFontFamily); <add> var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily); <add> <add> ctx.font = pointLabeFont; <add> ctx.fillStyle = pointLabelFontColor; <ide> <ide> var labelsCount = this.pointLabels.length, <ide> halfLabelsCount = this.pointLabels.length / 2, <ide><path>src/scales/scale.time.js <ide> module.exports = function(Chart) { <ide> this.tickRange = Math.ceil(this.lastTick.diff(this.firstTick, this.tickUnit, true)); <ide> } else { <ide> // Determine the smallest needed unit of the time <add> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <ide> var innerWidth = this.isHorizontal() ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom); <del> var labelCapacity = innerWidth / (this.options.ticks.fontSize + 10); <add> var labelCapacity = innerWidth / (tickFontSize + 10); <ide> var buffer = this.options.time.round ? 0 : 1; <ide> <ide> // Start as small as possible <ide><path>test/core.helpers.tests.js <ide> describe('Core helper tests', function() { <ide> }, <ide> position: "right", <ide> scaleLabel: { <del> fontColor: '#666', <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: 'normal', <ide> labelString: '', <ide> display: false, <ide> }, <ide> ticks: { <ide> beginAtZero: false, <del> fontColor: "#666", <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: "normal", <ide> maxRotation: 90, <ide> mirror: false, <ide> padding: 10, <ide> describe('Core helper tests', function() { <ide> }, <ide> position: "left", <ide> scaleLabel: { <del> fontColor: '#666', <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: 'normal', <ide> labelString: '', <ide> display: false, <ide> }, <ide> ticks: { <ide> beginAtZero: false, <del> fontColor: "#666", <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: "normal", <ide> maxRotation: 90, <ide> mirror: false, <ide> padding: 10, <ide><path>test/core.legend.tests.js <ide> describe('Legend block tests', function() { <ide> <ide> labels: { <ide> boxWidth: 40, <del> fontSize: Chart.defaults.global.defaultFontSize, <del> fontStyle: Chart.defaults.global.defaultFontStyle, <del> fontColor: Chart.defaults.global.defaultFontColor, <del> fontFamily: Chart.defaults.global.defaultFontFamily, <ide> padding: 10, <ide> generateLabels: jasmine.any(Function) <ide> } <ide><path>test/core.title.tests.js <ide> describe('Title block tests', function() { <ide> display: false, <ide> position: 'top', <ide> fullWidth: true, <del> fontColor: Chart.defaults.global.defaultFontColor, <del> fontFamily: Chart.defaults.global.defaultFontFamily, <del> fontSize: Chart.defaults.global.defaultFontSize, <ide> fontStyle: 'bold', <ide> padding: 10, <ide> text: '' <ide> describe('Title block tests', function() { <ide> title.draw(); <ide> <ide> expect(context.getCalls()).toEqual([{ <add> name: 'setFillStyle', <add> args: ['#666'] <add> }, { <ide> name: 'save', <ide> args: [] <ide> }, { <ide> describe('Title block tests', function() { <ide> }, { <ide> name: 'rotate', <ide> args: [-0.5 * Math.PI] <del> }, { <del> name: 'setFillStyle', <del> args: ['#666'] <ide> }, { <ide> name: 'fillText', <ide> args: ['My title', 0, 0] <ide> describe('Title block tests', function() { <ide> title.draw(); <ide> <ide> expect(context.getCalls()).toEqual([{ <add> name: 'setFillStyle', <add> args: ['#666'] <add> }, { <ide> name: 'save', <ide> args: [] <ide> }, { <ide> describe('Title block tests', function() { <ide> }, { <ide> name: 'rotate', <ide> args: [0.5 * Math.PI] <del> }, { <del> name: 'setFillStyle', <del> args: ['#666'] <ide> }, { <ide> name: 'fillText', <ide> args: ['My title', 0, 0] <ide><path>test/scale.category.tests.js <ide> describe('Category scale tests', function() { <ide> }, <ide> position: "bottom", <ide> scaleLabel: { <del> fontColor: '#666', <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: 'normal', <ide> labelString: '', <ide> display: false, <ide> }, <ide> ticks: { <ide> beginAtZero: false, <del> fontColor: "#666", <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: "normal", <ide> maxRotation: 90, <ide> mirror: false, <ide> padding: 10, <ide><path>test/scale.linear.tests.js <ide> describe('Linear Scale', function() { <ide> }, <ide> position: "left", <ide> scaleLabel: { <del> fontColor: '#666', <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: 'normal', <ide> labelString: '', <ide> display: false, <ide> }, <ide> ticks: { <ide> beginAtZero: false, <del> fontColor: "#666", <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: "normal", <ide> maxRotation: 90, <ide> mirror: false, <ide> padding: 10, <ide><path>test/scale.logarithmic.tests.js <ide> describe('Logarithmic Scale tests', function() { <ide> }, <ide> position: "left", <ide> scaleLabel: { <del> fontColor: '#666', <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: 'normal', <ide> labelString: '', <ide> display: false, <ide> }, <ide> ticks: { <ide> beginAtZero: false, <del> fontColor: "#666", <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: "normal", <ide> maxRotation: 90, <ide> mirror: false, <ide> padding: 10, <ide><path>test/scale.radialLinear.tests.js <ide> describe('Test the radial linear scale', function() { <ide> }, <ide> lineArc: false, <ide> pointLabels: { <del> fontColor: "#666", <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <ide> fontSize: 10, <del> fontStyle: "normal", <ide> callback: defaultConfig.pointLabels.callback, // make this nicer, then check explicitly below <ide> }, <ide> position: "chartArea", <ide> scaleLabel: { <del> fontColor: '#666', <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: 'normal', <ide> labelString: '', <ide> display: false, <ide> }, <ide> describe('Test the radial linear scale', function() { <ide> backdropPaddingY: 2, <ide> backdropPaddingX: 2, <ide> beginAtZero: false, <del> fontColor: "#666", <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: "normal", <ide> maxRotation: 90, <ide> mirror: false, <ide> padding: 10, <ide><path>test/scale.time.tests.js <ide> describe('Time scale tests', function() { <ide> }, <ide> position: "bottom", <ide> scaleLabel: { <del> fontColor: '#666', <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: 'normal', <ide> labelString: '', <ide> display: false, <ide> }, <ide> ticks: { <ide> beginAtZero: false, <del> fontColor: "#666", <del> fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", <del> fontSize: 12, <del> fontStyle: "normal", <ide> maxRotation: 90, <ide> mirror: false, <ide> padding: 10,
15
Python
Python
fix pypi complaint on version naming
5fd3d81ec92b07181848f182f25494fab351326e
<ide><path>setup.py <ide> def run(self): <ide> <ide> setup( <ide> name="transformers", <del> version="4.1.0dev0", <add> version="4.1.0.dev0", <ide> author="Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Sam Shleifer, Patrick von Platen, Sylvain Gugger, Google AI Language Team Authors, Open AI team Authors, Facebook AI Authors, Carnegie Mellon University Authors", <ide> author_email="thomas@huggingface.co", <ide> description="State-of-the-art Natural Language Processing for TensorFlow 2.0 and PyTorch", <ide><path>src/transformers/__init__.py <ide> # There's no way to ignore "F401 '...' imported but unused" warnings in this <ide> # module, but to preserve other warnings. So, don't check this module at all. <ide> <del>__version__ = "4.1.0dev0" <add>__version__ = "4.1.0.dev0" <ide> <ide> # Work around to update TensorFlow's absl.logging threshold which alters the <ide> # default Python logging output behavior when present.
2
Python
Python
raise exceptions instead of asserts in xnli.py
708ffff665bf0b7ba3a1a27190fb7c315d099d0d
<ide><path>src/transformers/data/processors/xnli.py <ide> def get_train_examples(self, data_dir): <ide> text_a = line[0] <ide> text_b = line[1] <ide> label = "contradiction" if line[2] == "contradictory" else line[2] <del> assert isinstance(text_a, str), f"Training input {text_a} is not a string" <del> assert isinstance(text_b, str), f"Training input {text_b} is not a string" <del> assert isinstance(label, str), f"Training label {label} is not a string" <add> if not isinstance(text_a, str): <add> raise ValueError(f"Training input {text_a} is not a string") <add> if not isinstance(text_b, str): <add> raise ValueError(f"Training input {text_b} is not a string") <add> if not isinstance(label, str): <add> raise ValueError(f"Training label {label} is not a string") <ide> examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <ide> return examples <ide> <ide> def get_test_examples(self, data_dir): <ide> text_a = line[6] <ide> text_b = line[7] <ide> label = line[1] <del> assert isinstance(text_a, str), f"Training input {text_a} is not a string" <del> assert isinstance(text_b, str), f"Training input {text_b} is not a string" <del> assert isinstance(label, str), f"Training label {label} is not a string" <add> if not isinstance(text_a, str): <add> raise ValueError(f"Training input {text_a} is not a string") <add> if not isinstance(text_b, str): <add> raise ValueError(f"Training input {text_b} is not a string") <add> if not isinstance(label, str): <add> raise ValueError(f"Training label {label} is not a string") <ide> examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <ide> return examples <ide>
1
Ruby
Ruby
remove undocumented save_without_validation!
88b4a8fcafc7c52ad7deaa4fee9ee0fabf68940c
<ide><path>activerecord/lib/active_record/validations.rb <ide> def save(options={}) <ide> perform_validations(options) ? super : false <ide> end <ide> <del> def save_without_validation! <del> save!(:validate => false) <del> end <del> <ide> # Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false <ide> # if the record is not valid. <ide> def save!(options={}) <ide><path>activerecord/test/cases/validations_test.rb <ide> def test_deprecated_create_without_validation <ide> end <ide> end <ide> <del> def test_create_without_validation_bang <del> count = WrongReply.count <del> assert_nothing_raised { WrongReply.new.save_without_validation! } <del> assert count+1, WrongReply.count <del> end <del> <ide> def test_validates_acceptance_of_with_non_existant_table <ide> Object.const_set :IncorporealModel, Class.new(ActiveRecord::Base) <ide>
2
Javascript
Javascript
remove dead code
94230d15bdbfe229901b221feb5814b60f8eeedb
<ide><path>lib/stream.js <ide> Stream.Stream = Stream; <ide> <ide> Stream._isUint8Array = require('internal/util/types').isUint8Array; <ide> <del>const version = process.version.substr(1).split('.'); <del>if (version[0] === 0 && version[1] < 12) { <del> Stream._uint8ArrayToBuffer = Buffer; <del>} else { <del> try { <del> const internalBuffer = require('internal/buffer'); <del> Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { <del> return new internalBuffer.FastBuffer(chunk.buffer, <del> chunk.byteOffset, <del> chunk.byteLength); <del> }; <del> } catch (e) { // eslint-disable-line no-unused-vars <del> } <add>try { <add> const internalBuffer = require('internal/buffer'); <add> Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { <add> return new internalBuffer.FastBuffer(chunk.buffer, <add> chunk.byteOffset, <add> chunk.byteLength); <add> }; <add>} catch (e) { // eslint-disable-line no-unused-vars <add>} <ide> <del> if (!Stream._uint8ArrayToBuffer) { <del> Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { <del> return Buffer.prototype.slice.call(chunk); <del> }; <del> } <add>if (!Stream._uint8ArrayToBuffer) { <add> Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { <add> return Buffer.prototype.slice.call(chunk); <add> }; <ide> }
1
Ruby
Ruby
fix mysql to support duplicated column names
b8569b9337309c2d6c72566a3426994b6da443d7
<ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb <ide> def exec_without_stmt(sql, name = 'SQL') # :nodoc: <ide> <ide> if result <ide> types = {} <add> fields = [] <ide> result.fetch_fields.each { |field| <add> field_name = field.name <add> fields << field_name <add> <ide> if field.decimals > 0 <del> types[field.name] = Fields::Decimal.new <add> types[field_name] = Fields::Decimal.new <ide> else <del> types[field.name] = Fields.find_type field <add> types[field_name] = Fields.find_type field <ide> end <ide> } <del> result_set = ActiveRecord::Result.new(types.keys, result.to_a, types) <add> <add> result_set = ActiveRecord::Result.new(fields, result.to_a, types) <ide> result.free <ide> else <ide> result_set = ActiveRecord::Result.new([], []) <ide><path>activerecord/test/cases/finder_test.rb <ide> def test_find_with_nil_inside_set_passed_for_attribute <ide> <ide> def test_with_limiting_with_custom_select <ide> posts = Post.references(:authors).merge( <del> :includes => :author, :select => ' posts.*, authors.id as "author_id"', <add> :includes => :author, :select => 'posts.*, authors.id as "author_id"', <ide> :limit => 3, :order => 'posts.id' <ide> ).to_a <ide> assert_equal 3, posts.size
2
Javascript
Javascript
add image border*radius tests
9b5b07f97f7309b5e3bf955165ad0efd612ae8a2
<ide><path>RNTester/js/ImageExample.js <ide> exports.examples = [ <ide> style={[styles.base, styles.leftMargin, {borderRadius: 19}]} <ide> source={fullImage} <ide> /> <add> <Image <add> style={[styles.base, styles.leftMargin, {borderTopLeftRadius: 20}]} <add> source={fullImage} <add> /> <add> <Image <add> style={[styles.base, styles.leftMargin, { <add> borderWidth: 10, <add> borderTopLeftRadius: 10, <add> borderBottomRightRadius: 20, <add> borderColor: 'green', <add> }]} <add> source={fullImage} <add> /> <add> <Image <add> style={[styles.base, styles.leftMargin, { <add> borderWidth: 5, <add> borderTopLeftRadius: 10, <add> borderTopRightRadius: 20, <add> borderBottomRightRadius: 30, <add> borderBottomLeftRadius: 40, <add> borderColor: 'red', <add> }]} <add> source={fullImage} <add> /> <ide> </View> <ide> ); <ide> },
1
PHP
PHP
handle json request
a0bebba5593b4063076f93df228121293ead6d48
<ide><path>src/Illuminate/Foundation/Auth/AuthenticatesUsers.php <ide> protected function authenticated(Request $request, $user) <ide> */ <ide> protected function sendFailedLoginResponse(Request $request) <ide> { <add> $errors = [$this->username() => trans('auth.failed')]; <add> <add> if ($request->expectsJson()) { <add> return response()->json($errors, 422); <add> } <add> <ide> return redirect()->back() <ide> ->withInput($request->only($this->username(), 'remember')) <del> ->withErrors([ <del> $this->username() => trans('auth.failed'), <del> ]); <add> ->withErrors($errors); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php <ide> protected function sendLockoutResponse(Request $request) <ide> <ide> $message = Lang::get('auth.throttle', ['seconds' => $seconds]); <ide> <add> $errors = [$this->username() => $message]; <add> <add> if ($request->expectsJson()) { <add> return response()->json($errors, 423); <add> } <add> <ide> return redirect()->back() <ide> ->withInput($request->only($this->username(), 'remember')) <del> ->withErrors([$this->username() => $message]); <add> ->withErrors($errors); <ide> } <ide> <ide> /**
2
Python
Python
convert dialogpt format
ef99852961b9f3bb87a18a58093c9f513c86b683
<ide><path>transformers/modeling_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> new_key = key.replace('gamma', 'weight') <ide> if 'beta' in key: <ide> new_key = key.replace('beta', 'bias') <add> if key == 'lm_head.decoder.weight': <add> new_key = 'lm_head.weight' <ide> if new_key: <ide> old_keys.append(key) <ide> new_keys.append(new_key)
1
Python
Python
add new line correctly in docstring sections
f38734ef981663a2eeb088625a6623ccf2f1ec42
<ide><path>rest_framework/schemas.py <ide> def get_description(self, path, method, view): <ide> current_section, seperator, lead = line.partition(':') <ide> sections[current_section] = lead.strip() <ide> else: <del> sections[current_section] += line + '\n' <add> sections[current_section] += '\n' + line <ide> <ide> header = getattr(view, 'action', method.lower()) <ide> if header in sections:
1
Python
Python
remove deprecated imports from polynomial package
d41fc4d518cb516c254959ca8c096bc8db2c81e9
<ide><path>numpy/polynomial/__init__.py <ide> from hermite_e import HermiteE <ide> from laguerre import Laguerre <ide> <del># Deprecate direct import of functions from this package <del># version 1.6.0 <del> <del>from numpy.lib import deprecate <del> <del># polynomial functions <del> <del>@deprecate(message='Please import polyline from numpy.polynomial.polynomial') <del>def polyline(off, scl) : <del> from numpy.polynomial.polynomial import polyline <del> return polyline(off, scl) <del> <del>@deprecate(message='Please import polyfromroots from numpy.polynomial.polynomial') <del>def polyfromroots(roots) : <del> from numpy.polynomial.polynomial import polyfromroots <del> return polyfromroots(roots) <del> <del>@deprecate(message='Please import polyadd from numpy.polynomial.polynomial') <del>def polyadd(c1, c2): <del> from numpy.polynomial.polynomial import polyadd <del> return polyadd(c1, c2) <del> <del>@deprecate(message='Please import polysub from numpy.polynomial.polynomial') <del>def polysub(c1, c2): <del> from numpy.polynomial.polynomial import polysub <del> return polysub(c1, c2) <del> <del>@deprecate(message='Please import polymulx from numpy.polynomial.polynomial') <del>def polymulx(cs): <del> from numpy.polynomial.polynomial import polymulx <del> return polymulx(cs) <del> <del>@deprecate(message='Please import polymul from numpy.polynomial.polynomial') <del>def polymul(c1, c2): <del> from numpy.polynomial.polynomial import polymul <del> return polymul(c1, c2) <del> <del>@deprecate(message='Please import polydiv from numpy.polynomial.polynomial') <del>def polydiv(c1, c2): <del> from numpy.polynomial.polynomial import polydiv <del> return polydiv(c1, c2) <del> <del>@deprecate(message='Please import polypow from numpy.polynomial.polynomial') <del>def polypow(cs, pow, maxpower=None) : <del> from numpy.polynomial.polynomial import polypow <del> return polypow(cs, pow, maxpower) <del> <del>@deprecate(message='Please import polyder from numpy.polynomial.polynomial') <del>def polyder(cs, m=1, scl=1): <del> from numpy.polynomial.polynomial import polyder <del> return polyder(cs, m, scl) <del> <del>@deprecate(message='Please import polyint from numpy.polynomial.polynomial') <del>def polyint(cs, m=1, k=[], lbnd=0, scl=1): <del> from numpy.polynomial.polynomial import polyint <del> return polyint(cs, m, k, lbnd, scl) <del> <del>@deprecate(message='Please import polyval from numpy.polynomial.polynomial') <del>def polyval(x, cs): <del> from numpy.polynomial.polynomial import polyval <del> return polyval(x, cs) <del> <del>@deprecate(message='Please import polyvander from numpy.polynomial.polynomial') <del>def polyvander(x, deg) : <del> from numpy.polynomial.polynomial import polyvander <del> return polyvander(x, deg) <del> <del>@deprecate(message='Please import polyfit from numpy.polynomial.polynomial') <del>def polyfit(x, y, deg, rcond=None, full=False, w=None): <del> from numpy.polynomial.polynomial import polyfit <del> return polyfit(x, y, deg, rcond, full, w) <del> <del>@deprecate(message='Please import polyroots from numpy.polynomial.polynomial') <del>def polyroots(cs): <del> from numpy.polynomial.polynomial import polyroots <del> return polyroots(cs) <del> <del> <del># chebyshev functions <del> <del>@deprecate(message='Please import poly2cheb from numpy.polynomial.chebyshev') <del>def poly2cheb(pol) : <del> from numpy.polynomial.chebyshev import poly2cheb <del> return poly2cheb(pol) <del> <del>@deprecate(message='Please import cheb2poly from numpy.polynomial.chebyshev') <del>def cheb2poly(cs) : <del> from numpy.polynomial.chebyshev import cheb2poly <del> return cheb2poly(cs) <del> <del>@deprecate(message='Please import chebline from numpy.polynomial.chebyshev') <del>def chebline(off, scl) : <del> from numpy.polynomial.chebyshev import chebline <del> return chebline(off, scl) <del> <del>@deprecate(message='Please import chebfromroots from numpy.polynomial.chebyshev') <del>def chebfromroots(roots) : <del> from numpy.polynomial.chebyshev import chebfromroots <del> return chebfromroots(roots) <del> <del>@deprecate(message='Please import chebadd from numpy.polynomial.chebyshev') <del>def chebadd(c1, c2): <del> from numpy.polynomial.chebyshev import chebadd <del> return chebadd(c1, c2) <del> <del>@deprecate(message='Please import chebsub from numpy.polynomial.chebyshev') <del>def chebsub(c1, c2): <del> from numpy.polynomial.chebyshev import chebsub <del> return chebsub(c1, c2) <del> <del>@deprecate(message='Please import chebmulx from numpy.polynomial.chebyshev') <del>def chebmulx(cs): <del> from numpy.polynomial.chebyshev import chebmulx <del> return chebmulx(cs) <del> <del>@deprecate(message='Please import chebmul from numpy.polynomial.chebyshev') <del>def chebmul(c1, c2): <del> from numpy.polynomial.chebyshev import chebmul <del> return chebmul(c1, c2) <del> <del>@deprecate(message='Please import chebdiv from numpy.polynomial.chebyshev') <del>def chebdiv(c1, c2): <del> from numpy.polynomial.chebyshev import chebdiv <del> return chebdiv(c1, c2) <del> <del>@deprecate(message='Please import chebpow from numpy.polynomial.chebyshev') <del>def chebpow(cs, pow, maxpower=16) : <del> from numpy.polynomial.chebyshev import chebpow <del> return chebpow(cs, pow, maxpower) <del> <del>@deprecate(message='Please import chebder from numpy.polynomial.chebyshev') <del>def chebder(cs, m=1, scl=1) : <del> from numpy.polynomial.chebyshev import chebder <del> return chebder(cs, m, scl) <del> <del>@deprecate(message='Please import chebint from numpy.polynomial.chebyshev') <del>def chebint(cs, m=1, k=[], lbnd=0, scl=1): <del> from numpy.polynomial.chebyshev import chebint <del> return chebint(cs, m, k, lbnd, scl) <del> <del>@deprecate(message='Please import chebval from numpy.polynomial.chebyshev') <del>def chebval(x, cs): <del> from numpy.polynomial.chebyshev import chebval <del> return chebval(x, cs) <del> <del>@deprecate(message='Please import chebvander from numpy.polynomial.chebyshev') <del>def chebvander(x, deg) : <del> from numpy.polynomial.chebyshev import chebvander <del> return chebvander(x, deg) <del> <del>@deprecate(message='Please import chebfit from numpy.polynomial.chebyshev') <del>def chebfit(x, y, deg, rcond=None, full=False, w=None): <del> from numpy.polynomial.chebyshev import chebfit <del> return chebfit(x, y, deg, rcond, full, w) <del> <del>@deprecate(message='Please import chebroots from numpy.polynomial.chebyshev') <del>def chebroots(cs): <del> from numpy.polynomial.chebyshev import chebroots <del> return chebroots(cs) <del> <del>@deprecate(message='Please import chebpts1 from numpy.polynomial.chebyshev') <del>def chebpts1(npts): <del> from numpy.polynomial.chebyshev import chebpts1 <del> return chebpts1(npts) <del> <del>@deprecate(message='Please import chebpts2 from numpy.polynomial.chebyshev') <del>def chebpts2(npts): <del> from numpy.polynomial.chebyshev import chebpts2 <del> return chebpts2(npts) <del> <del> <del># legendre functions <del> <del>@deprecate(message='Please import poly2leg from numpy.polynomial.legendre') <del>def poly2leg(pol) : <del> from numpy.polynomial.legendre import poly2leg <del> return poly2leg(pol) <del> <del>@deprecate(message='Please import leg2poly from numpy.polynomial.legendre') <del>def leg2poly(cs) : <del> from numpy.polynomial.legendre import leg2poly <del> return leg2poly(cs) <del> <del>@deprecate(message='Please import legline from numpy.polynomial.legendre') <del>def legline(off, scl) : <del> from numpy.polynomial.legendre import legline <del> return legline(off, scl) <del> <del>@deprecate(message='Please import legfromroots from numpy.polynomial.legendre') <del>def legfromroots(roots) : <del> from numpy.polynomial.legendre import legfromroots <del> return legfromroots(roots) <del> <del>@deprecate(message='Please import legadd from numpy.polynomial.legendre') <del>def legadd(c1, c2): <del> from numpy.polynomial.legendre import legadd <del> return legadd(c1, c2) <del> <del>@deprecate(message='Please import legsub from numpy.polynomial.legendre') <del>def legsub(c1, c2): <del> from numpy.polynomial.legendre import legsub <del> return legsub(c1, c2) <del> <del>@deprecate(message='Please import legmulx from numpy.polynomial.legendre') <del>def legmulx(cs): <del> from numpy.polynomial.legendre import legmulx <del> return legmulx(cs) <del> <del>@deprecate(message='Please import legmul from numpy.polynomial.legendre') <del>def legmul(c1, c2): <del> from numpy.polynomial.legendre import legmul <del> return legmul(c1, c2) <del> <del>@deprecate(message='Please import legdiv from numpy.polynomial.legendre') <del>def legdiv(c1, c2): <del> from numpy.polynomial.legendre import legdiv <del> return legdiv(c1, c2) <del> <del>@deprecate(message='Please import legpow from numpy.polynomial.legendre') <del>def legpow(cs, pow, maxpower=16) : <del> from numpy.polynomial.legendre import legpow <del> return legpow(cs, pow, maxpower) <del> <del>@deprecate(message='Please import legder from numpy.polynomial.legendre') <del>def legder(cs, m=1, scl=1) : <del> from numpy.polynomial.legendre import legder <del> return legder(cs, m, scl) <del> <del>@deprecate(message='Please import legint from numpy.polynomial.legendre') <del>def legint(cs, m=1, k=[], lbnd=0, scl=1): <del> from numpy.polynomial.legendre import legint <del> return legint(cs, m, k, lbnd, scl) <del> <del>@deprecate(message='Please import legval from numpy.polynomial.legendre') <del>def legval(x, cs): <del> from numpy.polynomial.legendre import legval <del> return legval(x, cs) <del> <del>@deprecate(message='Please import legvander from numpy.polynomial.legendre') <del>def legvander(x, deg) : <del> from numpy.polynomial.legendre import legvander <del> return legvander(x, deg) <del> <del>@deprecate(message='Please import legfit from numpy.polynomial.legendre') <del>def legfit(x, y, deg, rcond=None, full=False, w=None): <del> from numpy.polynomial.legendre import legfit <del> return legfit(x, y, deg, rcond, full, w) <del> <del>@deprecate(message='Please import legroots from numpy.polynomial.legendre') <del>def legroots(cs): <del> from numpy.polynomial.legendre import legroots <del> return legroots(cs) <del> <del> <del># polyutils functions <del> <del>@deprecate(message='Please import trimseq from numpy.polynomial.polyutils') <del>def trimseq(seq) : <del> from numpy.polynomial.polyutils import trimseq <del> return trimseq(seq) <del> <del>@deprecate(message='Please import as_series from numpy.polynomial.polyutils') <del>def as_series(alist, trim=True) : <del> from numpy.polynomial.polyutils import as_series <del> return as_series(alist, trim) <del> <del>@deprecate(message='Please import trimcoef from numpy.polynomial.polyutils') <del>def trimcoef(c, tol=0) : <del> from numpy.polynomial.polyutils import trimcoef <del> return trimcoef(c, tol) <del> <del>@deprecate(message='Please import getdomain from numpy.polynomial.polyutils') <del>def getdomain(x) : <del> from numpy.polynomial.polyutils import getdomain <del> return getdomain(x) <del> <del># Just remove this function as it screws up the documentation of the same <del># named class method. <del># <del>#@deprecate(message='Please import mapparms from numpy.polynomial.polyutils') <del>#def mapparms(old, new) : <del># from numpy.polynomial.polyutils import mapparms <del># return mapparms(old, new) <del> <del>@deprecate(message='Please import mapdomain from numpy.polynomial.polyutils') <del>def mapdomain(x, old, new) : <del> from numpy.polynomial.polyutils import mapdomain <del> return mapdomain(x, old, new) <del> <del> <ide> from numpy.testing import Tester <ide> test = Tester().test <ide> bench = Tester().bench
1
Javascript
Javascript
fix typo in pdf_history.js
0de15d59b86ff9bd6535bbff9bc338873c0dfdaa
<ide><path>web/pdf_history.js <ide> class PDFHistory { <ide> // being scrolled into view, to avoid potentially inconsistent state. <ide> this._popStateInProgress = true; <ide> // We defer the resetting of `this._popStateInProgress`, to account for <del> // e.g. zooming occuring when the new destination is being navigated to. <add> // e.g. zooming occurring when the new destination is being navigated to. <ide> Promise.resolve().then(() => { <ide> this._popStateInProgress = false; <ide> }); <ide> class PDFHistory { <ide> // being scrolled into view, to avoid potentially inconsistent state. <ide> this._popStateInProgress = true; <ide> // We defer the resetting of `this._popStateInProgress`, to account for <del> // e.g. zooming occuring when the new page is being navigated to. <add> // e.g. zooming occurring when the new page is being navigated to. <ide> Promise.resolve().then(() => { <ide> this._popStateInProgress = false; <ide> });
1
Java
Java
fix a typo in @nonnullfields
8ddb1e7201f6726fee6ebc798e43a80094a2df0f
<ide><path>spring-core/src/main/java/org/springframework/lang/NonNullFields.java <ide> * <ide> * @author Sebastien Deleuze <ide> * @since 5.0 <del> * @see NonNullFields <add> * @see NonNullApi <ide> * @see Nullable <ide> * @see NonNull <ide> */
1
Python
Python
fix tests for windows + pypy
cf5e7665fdd764a6647f2b62d2740bb431180794
<ide><path>numpy/core/tests/test_memmap.py <ide> <ide> from numpy import arange, allclose, asarray <ide> from numpy.testing import ( <del> assert_, assert_equal, assert_array_equal, suppress_warnings <add> assert_, assert_equal, assert_array_equal, suppress_warnings, IS_PYPY, <add> break_cycles <ide> ) <ide> <ide> class TestMemmap: <ide> def setup(self): <ide> <ide> def teardown(self): <ide> self.tmpfp.close() <add> self.data = None <add> if IS_PYPY: <add> break_cycles() <add> break_cycles() <ide> shutil.rmtree(self.tempdir) <ide> <ide> def test_roundtrip(self): <ide><path>numpy/distutils/mingw32ccompiler.py <ide> <ide> """ <ide> import os <add>import platform <ide> import sys <ide> import subprocess <ide> import re <ide> def find_python_dll(): <ide> <ide> # search in the file system for possible candidates <ide> major_version, minor_version = tuple(sys.version_info[:2]) <del> patterns = ['python%d%d.dll'] <del> <del> for pat in patterns: <del> dllname = pat % (major_version, minor_version) <del> print("Looking for %s" % dllname) <del> for folder in lib_dirs: <del> dll = os.path.join(folder, dllname) <del> if os.path.exists(dll): <del> return dll <del> <add> implementation = platform.python_implementation() <add> if implementation == 'CPython': <add> dllname = f'python{major_version}{minor_version}.dll' <add> elif implementation == 'PyPy': <add> dllname = f'libpypy{major_version}-c.dll' <add> else: <add> dllname = 'Unknown platform {implementation}' <add> print("Looking for %s" % dllname) <add> for folder in lib_dirs: <add> dll = os.path.join(folder, dllname) <add> if os.path.exists(dll): <add> return dll <add> <ide> raise ValueError("%s not found in %s" % (dllname, lib_dirs)) <ide> <ide> def dump_table(dll): <ide><path>numpy/lib/tests/test_format.py <ide> import numpy as np <ide> from numpy.testing import ( <ide> assert_, assert_array_equal, assert_raises, assert_raises_regex, <del> assert_warns <add> assert_warns, IS_PYPY, break_cycles <ide> ) <ide> from numpy.lib import format <ide> <ide> def test_memmap_roundtrip(): <ide> # Write it out normally and through mmap. <ide> nfn = os.path.join(tempdir, 'normal.npy') <ide> mfn = os.path.join(tempdir, 'memmap.npy') <del> fp = open(nfn, 'wb') <del> try: <add> with open(nfn, 'wb') as fp: <ide> format.write_array(fp, arr) <del> finally: <del> fp.close() <ide> <ide> fortran_order = ( <ide> arr.flags.f_contiguous and not arr.flags.c_contiguous) <ide> ma = format.open_memmap(mfn, mode='w+', dtype=arr.dtype, <ide> shape=arr.shape, fortran_order=fortran_order) <ide> ma[...] = arr <ide> del ma <add> if IS_PYPY: <add> break_cycles() <ide> <ide> # Check that both of these files' contents are the same. <del> fp = open(nfn, 'rb') <del> normal_bytes = fp.read() <del> fp.close() <del> fp = open(mfn, 'rb') <del> memmap_bytes = fp.read() <del> fp.close() <add> with open(nfn, 'rb') as fp: <add> normal_bytes = fp.read() <add> with open(mfn, 'rb') as fp: <add> memmap_bytes = fp.read() <ide> assert_equal_(normal_bytes, memmap_bytes) <ide> <ide> # Check that reading the file using memmap works. <ide> ma = format.open_memmap(nfn, mode='r') <ide> del ma <add> if IS_PYPY: <add> break_cycles() <ide> <ide> <ide> def test_compressed_roundtrip(): <ide> arr = np.random.rand(200, 200) <ide> npz_file = os.path.join(tempdir, 'compressed.npz') <ide> np.savez_compressed(npz_file, arr=arr) <del> arr1 = np.load(npz_file)['arr'] <add> with np.load(npz_file) as npz: <add> arr1 = npz['arr'] <ide> assert_array_equal(arr, arr1) <ide> <ide> <ide> def test_load_padded_dtype(dt): <ide> arr[i] = i + 5 <ide> npz_file = os.path.join(tempdir, 'aligned.npz') <ide> np.savez(npz_file, arr=arr) <del> arr1 = np.load(npz_file)['arr'] <add> with np.load(npz_file) as npz: <add> arr1 = npz['arr'] <ide> assert_array_equal(arr, arr1) <ide> <ide> <ide> def test_pickle_disallow(): <ide> allow_pickle=False, encoding='latin1') <ide> <ide> path = os.path.join(data_dir, 'py2-objarr.npz') <del> f = np.load(path, allow_pickle=False, encoding='latin1') <del> assert_raises(ValueError, f.__getitem__, 'x') <add> with np.load(path, allow_pickle=False, encoding='latin1') as f: <add> assert_raises(ValueError, f.__getitem__, 'x') <ide> <ide> path = os.path.join(tempdir, 'pickle-disabled.npy') <ide> assert_raises(ValueError, np.save, path, np.array([None], dtype=object), <ide> def test_version_2_0_memmap(): <ide> shape=d.shape, version=(2, 0)) <ide> ma[...] = d <ide> del ma <add> if IS_PYPY: <add> break_cycles() <ide> <ide> with warnings.catch_warnings(record=True) as w: <ide> warnings.filterwarnings('always', '', UserWarning) <ide> def test_version_2_0_memmap(): <ide> assert_(w[0].category is UserWarning) <ide> ma[...] = d <ide> del ma <add> if IS_PYPY: <add> break_cycles() <ide> <ide> ma = format.open_memmap(tf, mode='r') <ide> assert_array_equal(ma, d) <add> del ma <add> if IS_PYPY: <add> break_cycles() <ide> <ide> <ide> def test_write_version(): <ide> def test_empty_npz(): <ide> # Test for gh-9989 <ide> fname = os.path.join(tempdir, "nothing.npz") <ide> np.savez(fname) <del> np.load(fname) <add> with np.load(fname) as nps: <add> pass <ide> <ide> <ide> def test_unicode_field_names(): <ide><path>numpy/lib/tests/test_io.py <ide> from numpy.testing import ( <ide> assert_warns, assert_, assert_raises_regex, assert_raises, <ide> assert_allclose, assert_array_equal, temppath, tempdir, IS_PYPY, <del> HAS_REFCOUNT, suppress_warnings, assert_no_gc_cycles, assert_no_warnings <add> HAS_REFCOUNT, suppress_warnings, assert_no_gc_cycles, assert_no_warnings, <add> break_cycles <ide> ) <ide> from numpy.testing._private.utils import requires_memory <ide> <ide> def test_save_load_memmap(self): <ide> assert_array_equal(data, a) <ide> # close the mem-mapped file <ide> del data <add> if IS_PYPY: <add> break_cycles() <add> break_cycles() <ide> <ide> def test_save_load_memmap_readwrite(self): <ide> # Test that pathlib.Path instances can be written mem-mapped. <ide> def test_save_load_memmap_readwrite(self): <ide> a[0][0] = 5 <ide> b[0][0] = 5 <ide> del b # closes the file <add> if IS_PYPY: <add> break_cycles() <add> break_cycles() <ide> data = np.load(path) <ide> assert_array_equal(data, a) <ide> <ide><path>numpy/testing/_private/utils.py <ide> def break_cycles(): <ide> if IS_PYPY: <ide> # interpreter runs now, to call deleted objects' __del__ methods <ide> gc.collect() <del> # one more, just to make sure <add> # two more, just to make sure <add> gc.collect() <ide> gc.collect() <ide> <ide>
5
Go
Go
preserve underlying error
4fa853f5defdc97e516a3f9b93b2d812104955dc
<ide><path>pkg/fileutils/fileutils.go <ide> func CopyFile(src, dst string) (int64, error) { <ide> <ide> // ReadSymlinkedDirectory returns the target directory of a symlink. <ide> // The target of the symbolic link may not be a file. <del>func ReadSymlinkedDirectory(path string) (string, error) { <del> var realPath string <del> var err error <add>func ReadSymlinkedDirectory(path string) (realPath string, err error) { <ide> if realPath, err = filepath.Abs(path); err != nil { <del> return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) <add> return "", fmt.Errorf("unable to get absolute path for %s: %w", path, err) <ide> } <ide> if realPath, err = filepath.EvalSymlinks(realPath); err != nil { <del> return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) <add> return "", fmt.Errorf("failed to canonicalise path for %s: %w", path, err) <ide> } <ide> realPathInfo, err := os.Stat(realPath) <ide> if err != nil { <del> return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) <add> return "", fmt.Errorf("failed to stat target '%s' of '%s': %w", realPath, path, err) <ide> } <ide> if !realPathInfo.Mode().IsDir() { <ide> return "", fmt.Errorf("canonical path points to a file '%s'", realPath) <ide><path>pkg/fileutils/fileutils_test.go <ide> func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) { <ide> if err == nil { <ide> t.Errorf("error expected for non-existing symlink") <ide> } <add> if !errors.Is(err, os.ErrNotExist) { <add> t.Errorf("Expected an os.ErrNotExist, got: %v", err) <add> } <ide> if symLinkedPath != "" { <ide> t.Fatalf("expected empty path, but '%s' was returned", symLinkedPath) <ide> }
2