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 |
|---|---|---|---|---|---|
Go | Go | allow force sigint and allow sigquit after sigint | cd910cb6858541b432e20b650fad262772c9ef18 | <ide><path>server/server.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> c := make(chan os.Signal, 1)
<ide> gosignal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
<ide> go func() {
<add> interruptCount := 0
<ide> for sig := range c {
<del> log.Printf("Received signal '%v', starting shutdown of docker...\n", sig)
<del> switch sig {
<del> case os.Interrupt, syscall.SIGTERM:
<del> utils.RemovePidFile(srv.runtime.Config().Pidfile)
<del> srv.Close()
<del> case syscall.SIGQUIT:
<del> }
<del> os.Exit(128 + int(sig.(syscall.Signal)))
<add> go func() {
<add> log.Printf("Received signal '%v', starting shutdown of docker...\n", sig)
<add> switch sig {
<add> case os.Interrupt, syscall.SIGTERM:
<add> // If the user really wants to interrupt, let him do so.
<add> if interruptCount < 3 {
<add> interruptCount++
<add> // Initiate the cleanup only once
<add> if interruptCount == 1 {
<add> utils.RemovePidFile(srv.runtime.Config().Pidfile)
<add> srv.Close()
<add> } else {
<add> return
<add> }
<add> } else {
<add> log.Printf("Force shutdown of docker, interrupting cleanup\n")
<add> }
<add> case syscall.SIGQUIT:
<add> }
<add> os.Exit(128 + int(sig.(syscall.Signal)))
<add> }()
<ide> }
<ide> }()
<ide> job.Eng.Hack_SetGlobalVar("httpapi.server", srv) | 1 |
Javascript | Javascript | replace var with let and const in readline.js | 205046af7eb6be0b4a7a785082962586ed6f1dec | <ide><path>lib/readline.js
<ide> function Interface(input, output, completer, terminal) {
<ide> this.escapeCodeTimeout = ESCAPE_CODE_TIMEOUT;
<ide>
<ide> EventEmitter.call(this);
<del> var historySize;
<del> var removeHistoryDuplicates = false;
<add> let historySize;
<add> let removeHistoryDuplicates = false;
<ide> let crlfDelay;
<ide> let prompt = '> ';
<ide>
<ide> Object.defineProperty(Interface.prototype, 'columns', {
<ide> configurable: true,
<ide> enumerable: true,
<ide> get: function() {
<del> var columns = Infinity;
<ide> if (this.output && this.output.columns)
<del> columns = this.output.columns;
<del> return columns;
<add> return this.output.columns;
<add> return Infinity;
<ide> }
<ide> });
<ide>
<ide> Interface.prototype.question = function(query, cb) {
<ide>
<ide> Interface.prototype._onLine = function(line) {
<ide> if (this._questionCallback) {
<del> var cb = this._questionCallback;
<add> const cb = this._questionCallback;
<ide> this._questionCallback = null;
<ide> this.setPrompt(this._oldPrompt);
<ide> cb(line);
<ide> Interface.prototype._normalWrite = function(b) {
<ide> if (b === undefined) {
<ide> return;
<ide> }
<del> var string = this._decoder.write(b);
<add> let string = this._decoder.write(b);
<ide> if (this._sawReturnAt &&
<ide> Date.now() - this._sawReturnAt <= this.crlfDelay) {
<ide> string = string.replace(/^\n/, '');
<ide> Interface.prototype._normalWrite = function(b) {
<ide> this._sawReturnAt = string.endsWith('\r') ? Date.now() : 0;
<ide>
<ide> // Got one or more newlines; process into "line" events
<del> var lines = string.split(lineEnding);
<add> const lines = string.split(lineEnding);
<ide> // Either '' or (conceivably) the unfinished portion of the next line
<ide> string = lines.pop();
<ide> this._line_buffer = string;
<del> for (var n = 0; n < lines.length; n++)
<add> for (let n = 0; n < lines.length; n++)
<ide> this._onLine(lines[n]);
<ide> } else if (string) {
<ide> // No newlines this time, save what we have for next time
<ide> Interface.prototype._normalWrite = function(b) {
<ide>
<ide> Interface.prototype._insertString = function(c) {
<ide> if (this.cursor < this.line.length) {
<del> var beg = this.line.slice(0, this.cursor);
<del> var end = this.line.slice(this.cursor, this.line.length);
<add> const beg = this.line.slice(0, this.cursor);
<add> const end = this.line.slice(this.cursor, this.line.length);
<ide> this.line = beg + c + end;
<ide> this.cursor += c.length;
<ide> this._refreshLine();
<ide> Interface.prototype._tabComplete = function(lastKeypressWasTab) {
<ide> // Apply/show completions.
<ide> if (lastKeypressWasTab) {
<ide> self._writeToOutput('\r\n');
<del> var width = completions.reduce(function completionReducer(a, b) {
<add> const width = completions.reduce(function completionReducer(a, b) {
<ide> return a.length > b.length ? a : b;
<ide> }).length + 2; // 2 space padding
<del> var maxColumns = Math.floor(self.columns / width);
<add> let maxColumns = Math.floor(self.columns / width);
<ide> if (!maxColumns || maxColumns === Infinity) {
<ide> maxColumns = 1;
<ide> }
<del> var group = [];
<del> for (var i = 0; i < completions.length; i++) {
<del> var c = completions[i];
<add> let group = [];
<add> for (let i = 0; i < completions.length; i++) {
<add> const c = completions[i];
<ide> if (c === '') {
<ide> handleGroup(self, group, width, maxColumns);
<ide> group = [];
<ide> Interface.prototype._tabComplete = function(lastKeypressWasTab) {
<ide> }
<ide>
<ide> // If there is a common prefix to all matches, then apply that portion.
<del> var f = completions.filter((e) => e);
<del> var prefix = commonPrefix(f);
<add> const f = completions.filter((e) => e);
<add> const prefix = commonPrefix(f);
<ide> if (prefix.length > completeOn.length) {
<ide> self._insertString(prefix.slice(completeOn.length));
<ide> }
<ide> function handleGroup(self, group, width, maxColumns) {
<ide> return;
<ide> }
<ide> const minRows = Math.ceil(group.length / maxColumns);
<del> for (var row = 0; row < minRows; row++) {
<del> for (var col = 0; col < maxColumns; col++) {
<del> var idx = row * maxColumns + col;
<add> for (let row = 0; row < minRows; row++) {
<add> for (let col = 0; col < maxColumns; col++) {
<add> const idx = row * maxColumns + col;
<ide> if (idx >= group.length) {
<ide> break;
<ide> }
<del> var item = group[idx];
<add> const item = group[idx];
<ide> self._writeToOutput(item);
<ide> if (col < maxColumns - 1) {
<del> for (var s = 0; s < width - item.length; s++) {
<add> for (let s = 0; s < width - item.length; s++) {
<ide> self._writeToOutput(' ');
<ide> }
<ide> }
<ide> function commonPrefix(strings) {
<ide> const sorted = strings.slice().sort();
<ide> const min = sorted[0];
<ide> const max = sorted[sorted.length - 1];
<del> for (var i = 0, len = min.length; i < len; i++) {
<add> for (let i = 0, len = min.length; i < len; i++) {
<ide> if (min[i] !== max[i]) {
<ide> return min.slice(0, i);
<ide> }
<ide> Interface.prototype._wordLeft = function() {
<ide> if (this.cursor > 0) {
<ide> // Reverse the string and match a word near beginning
<ide> // to avoid quadratic time complexity
<del> var leading = this.line.slice(0, this.cursor);
<del> var reversed = leading.split('').reverse().join('');
<del> var match = reversed.match(/^\s*(?:[^\w\s]+|\w+)?/);
<add> const leading = this.line.slice(0, this.cursor);
<add> const reversed = leading.split('').reverse().join('');
<add> const match = reversed.match(/^\s*(?:[^\w\s]+|\w+)?/);
<ide> this._moveCursor(-match[0].length);
<ide> }
<ide> };
<ide>
<ide>
<ide> Interface.prototype._wordRight = function() {
<ide> if (this.cursor < this.line.length) {
<del> var trailing = this.line.slice(this.cursor);
<del> var match = trailing.match(/^(?:\s+|[^\w\s]+|\w+)\s*/);
<add> const trailing = this.line.slice(this.cursor);
<add> const match = trailing.match(/^(?:\s+|[^\w\s]+|\w+)\s*/);
<ide> this._moveCursor(match[0].length);
<ide> }
<ide> };
<ide> Interface.prototype._deleteWordLeft = function() {
<ide> if (this.cursor > 0) {
<ide> // Reverse the string and match a word near beginning
<ide> // to avoid quadratic time complexity
<del> var leading = this.line.slice(0, this.cursor);
<del> var reversed = leading.split('').reverse().join('');
<del> var match = reversed.match(/^\s*(?:[^\w\s]+|\w+)?/);
<add> let leading = this.line.slice(0, this.cursor);
<add> const reversed = leading.split('').reverse().join('');
<add> const match = reversed.match(/^\s*(?:[^\w\s]+|\w+)?/);
<ide> leading = leading.slice(0, leading.length - match[0].length);
<ide> this.line = leading + this.line.slice(this.cursor, this.line.length);
<ide> this.cursor = leading.length;
<ide> Interface.prototype._deleteWordLeft = function() {
<ide>
<ide> Interface.prototype._deleteWordRight = function() {
<ide> if (this.cursor < this.line.length) {
<del> var trailing = this.line.slice(this.cursor);
<del> var match = trailing.match(/^(?:\s+|\W+|\w+)\s*/);
<add> const trailing = this.line.slice(this.cursor);
<add> const match = trailing.match(/^(?:\s+|\W+|\w+)\s*/);
<ide> this.line = this.line.slice(0, this.cursor) +
<ide> trailing.slice(match[0].length);
<ide> this._refreshLine();
<ide> Interface.prototype._historyPrev = function() {
<ide>
<ide> // Returns the last character's display position of the given string
<ide> Interface.prototype._getDisplayPos = function(str) {
<del> var offset = 0;
<add> let offset = 0;
<ide> const col = this.columns;
<del> var row = 0;
<del> var code;
<add> let row = 0;
<ide> str = stripVTControlCharacters(str);
<del> for (var i = 0, len = str.length; i < len; i++) {
<del> code = str.codePointAt(i);
<add> for (let i = 0, len = str.length; i < len; i++) {
<add> const code = str.codePointAt(i);
<ide> if (code >= kUTF16SurrogateThreshold) { // Surrogates.
<ide> i++;
<ide> }
<ide> Interface.prototype._getCursorPos = function() {
<ide> const strBeforeCursor = this._prompt + this.line.substring(0, this.cursor);
<ide> const dispPos = this._getDisplayPos(
<ide> stripVTControlCharacters(strBeforeCursor));
<del> var cols = dispPos.cols;
<del> var rows = dispPos.rows;
<add> let cols = dispPos.cols;
<add> let rows = dispPos.rows;
<ide> // If the cursor is on a full-width character which steps over the line,
<ide> // move the cursor to the beginning of the next line.
<ide> if (cols + 1 === columns &&
<ide> Interface.prototype._moveCursor = function(dx) {
<ide>
<ide> // Check if cursors are in the same line
<ide> if (oldPos.rows === newPos.rows) {
<del> var diffCursor = this.cursor - oldcursor;
<del> var diffWidth;
<add> const diffCursor = this.cursor - oldcursor;
<add> let diffWidth;
<ide> if (diffCursor < 0) {
<ide> diffWidth = -getStringWidth(
<ide> this.line.substring(this.cursor, oldcursor)
<ide> Interface.prototype._ttyWrite = function(s, key) {
<ide>
<ide> default:
<ide> if (typeof s === 'string' && s) {
<del> var lines = s.split(/\r\n|\n|\r/);
<del> for (var i = 0, len = lines.length; i < len; i++) {
<add> const lines = s.split(/\r\n|\n|\r/);
<add> for (let i = 0, len = lines.length; i < len; i++) {
<ide> if (i > 0) {
<ide> this._line();
<ide> }
<ide> function emitKeypressEvents(stream, iface) {
<ide>
<ide> function onData(b) {
<ide> if (stream.listenerCount('keypress') > 0) {
<del> var r = stream[KEYPRESS_DECODER].write(b);
<add> const r = stream[KEYPRESS_DECODER].write(b);
<ide> if (r) {
<ide> clearTimeout(timeoutId);
<ide>
<ide> if (iface) {
<ide> iface._sawKeyPress = r.length === 1;
<ide> }
<ide>
<del> for (var i = 0; i < r.length; i++) {
<add> for (let i = 0; i < r.length; i++) {
<ide> if (r[i] === '\t' && typeof r[i + 1] === 'string' && iface) {
<ide> iface.isCompletionEnabled = false;
<ide> } | 1 |
Java | Java | fix javadoc in contentresultmatchers | 6aa300d733b696628f0c80d3ede10f1676527c1a | <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java
<ide> public void match(MvcResult result) {
<ide> * Assert the response body content with a Hamcrest {@link Matcher}.
<ide> * <pre class="code">
<ide> * mockMvc.perform(get("/path"))
<del> * .andExpect(content(containsString("text")));
<add> * .andExpect(content().string(containsString("text")));
<ide> * </pre>
<ide> */
<ide> public ResultMatcher string(final Matcher<? super String> matcher) { | 1 |
Ruby | Ruby | add nodoc to internal class [ci skip] | c153503a236c822f6a486ca83c5db1a88630dc66 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def primary_key?
<ide> class ChangeColumnDefinition < Struct.new(:column, :type, :options) #:nodoc:
<ide> end
<ide>
<del> class ForeignKeyDefinition < Struct.new(:from_table, :to_table, :options)
<add> class ForeignKeyDefinition < Struct.new(:from_table, :to_table, :options) #:nodoc:
<ide> def name
<ide> options[:name]
<ide> end | 1 |
Text | Text | add angular2+ libraries for chart.js in docs | b835df02cd05830fb734806f3af27fa43cc5674c | <ide><path>docs/notes/extensions.md
<ide> In addition, many plugins can be found on the [npm registry](https://www.npmjs.c
<ide>
<ide> ## Integrations
<ide>
<del>### Angular
<add>### Angular (v2+)
<add>
<add> - <a href="https://github.com/emn178/angular2-chartjs" target="_blank">emn178/angular2-chartjs</a>
<add> - <a href="https://github.com/valor-software/ng2-charts" target="_blank">valor-software/ng2-charts</a>
<add>
<add>### Angular (v1)
<ide> - <a href="https://github.com/jtblin/angular-chart.js" target="_blank">angular-chart.js</a>
<ide> - <a href="https://github.com/carlcraig/tc-angular-chartjs" target="_blank">tc-angular-chartjs</a>
<ide> - <a href="https://github.com/petermelias/angular-chartjs" target="_blank">angular-chartjs</a> | 1 |
Javascript | Javascript | add test case for enum validation | 0963d744e9bbfbec52e32d1663df03ff0b0ba339 | <ide><path>lib/WebpackOptionsValidationError.js
<ide> class WebpackOptionsValidationError extends WebpackError {
<ide> return "RegExp";
<ide> }
<ide>
<add> if (schema.enum) {
<add> return schema.enum.map(item => JSON.stringify(item)).join(" | ");
<add> }
<add>
<ide> if (schema.$ref) {
<ide> return formatInnerSchema(getSchemaPart(schema.$ref), true);
<ide> }
<ide> class WebpackOptionsValidationError extends WebpackError {
<ide> if (schema.anyOf) {
<ide> return schema.anyOf.map(formatInnerSchema).join(" | ");
<ide> }
<del> if (schema.enum) {
<del> return schema.enum.map(item => JSON.stringify(item)).join(" | ");
<del> }
<ide> return JSON.stringify(schema, null, 2);
<ide> }
<ide>
<ide> class WebpackOptionsValidationError extends WebpackError {
<ide> err.parentSchema
<ide> )}`;
<ide> } else if (err.keyword === "enum") {
<add> console.log(err.parentSchema);
<ide> if (
<ide> err.parentSchema &&
<ide> err.parentSchema.enum &&
<ide><path>test/Validation.test.js
<ide> describe("Validation", () => {
<ide> -> The run point of the plugin, required method.
<ide> * configuration.plugins[0] should be an instance of function
<ide> -> Function acting as plugin"
<add>`)
<add> );
<add>
<add> createTestCase(
<add> "invalid mode",
<add> {
<add> mode: "protuction"
<add> },
<add> msg =>
<add> expect(msg).toMatchInlineSnapshot(`
<add>"Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
<add> - configuration.mode should be one of these:
<add> \\"development\\" | \\"production\\" | \\"none\\"
<add> -> Enable production optimizations or development hints."
<ide> `)
<ide> );
<ide> }); | 2 |
Ruby | Ruby | fix typos in string_ext_test.rb [ci skip] | fc2ecbb844908b2c2daaa3f1cfcfb97b4d41044c | <ide><path>activesupport/test/core_ext/string_ext_test.rb
<ide> def test_truncate
<ide> assert_equal "Hello Wor...", "Hello World!!".truncate(12)
<ide> end
<ide>
<del> def test_truncate_with_omission_and_seperator
<add> def test_truncate_with_omission_and_separator
<ide> assert_equal "Hello[...]", "Hello World!".truncate(10, :omission => "[...]")
<ide> assert_equal "Hello[...]", "Hello Big World!".truncate(13, :omission => "[...]", :separator => ' ')
<ide> assert_equal "Hello Big[...]", "Hello Big World!".truncate(14, :omission => "[...]", :separator => ' ')
<ide> assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, :omission => "[...]", :separator => ' ')
<ide> end
<ide>
<del> def test_truncate_with_omission_and_regexp_seperator
<add> def test_truncate_with_omission_and_regexp_separator
<ide> assert_equal "Hello[...]", "Hello Big World!".truncate(13, :omission => "[...]", :separator => /\s/)
<ide> assert_equal "Hello Big[...]", "Hello Big World!".truncate(14, :omission => "[...]", :separator => /\s/)
<ide> assert_equal "Hello Big[...]", "Hello Big World!".truncate(15, :omission => "[...]", :separator => /\s/)
<ide> def test_truncate_words
<ide> assert_equal "Hello Big...", "Hello Big World!".truncate_words(2)
<ide> end
<ide>
<del> def test_truncate_words_with_ommission
<add> def test_truncate_words_with_omission
<ide> assert_equal "Hello Big World!", "Hello Big World!".truncate_words(3, :omission => "[...]")
<ide> assert_equal "Hello Big[...]", "Hello Big World!".truncate_words(2, :omission => "[...]")
<ide> end
<ide> def test_truncate_words_with_separator
<ide> assert_equal "Hello\n<br>Big...", "Hello\n<br>Big<br>Wide<br>World!".truncate_words(2, :separator => '<br>')
<ide> end
<ide>
<del> def test_truncate_words_with_separator_and_ommission
<add> def test_truncate_words_with_separator_and_omission
<ide> assert_equal "Hello<br>Big<br>World![...]", "Hello<br>Big<br>World!<br>".truncate_words(3, :omission => "[...]", :separator => '<br>')
<ide> assert_equal "Hello<br>Big<br>World!", "Hello<br>Big<br>World!".truncate_words(3, :omission => "[...]", :separator => '<br>')
<ide> end | 1 |
Java | Java | use .setstatus in responsestatusexceptionresolver | 0ef8af4798222eccfa69d3e3a0c339b170e6d072 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java
<ide> protected ModelAndView resolveResponseStatus(ResponseStatus responseStatus, Http
<ide> reason = this.messageSource.getMessage(reason, null, reason, LocaleContextHolder.getLocale());
<ide> }
<ide> if (!StringUtils.hasLength(reason)) {
<del> response.sendError(statusCode);
<add> response.setStatus(statusCode);
<ide> }
<ide> else {
<ide> response.sendError(statusCode, reason); | 1 |
Text | Text | change the sentence to clarify the effect of style | 45e15ede109601546bf2c9e8d16d6cb9d946834a | <ide><path>guide/english/typography/index.md
<ide> title: Typography
<ide>
<ide> Typography is a field that deals with the written word and how letters and characters are presented.
<ide>
<del>The same letters can be styled in different ways to convey different emotions. And there are all kinds of tradeoffs around style versus readability.
<add>The same letters can be styled in different ways to convey different emotions. However, there are all kinds of tradeoffs when it comes to focusing on style or readability.
<ide>
<del>In this section, we'll have guides to a variety of typography concepts.
<ide>\ No newline at end of file
<add>In this section, we'll have guides to a variety of typography concepts. | 1 |
PHP | PHP | update config file | d201c69a8bb6cf7407ac3a6c0a0e89f183061682 | <ide><path>config/auth.php
<ide> 'api' => [
<ide> 'driver' => 'token',
<ide> 'provider' => 'users',
<add> 'hash' => false,
<ide> ],
<ide> ],
<ide> | 1 |
Javascript | Javascript | fix profiler and nits | 80d9d8d841d02689d4c75360e2b42b543ab3477e | <ide><path>shells/dev/app/SuspenseTree/index.js
<ide> function SuspenseTree() {
<ide> return (
<ide> <>
<ide> <h1>Suspense</h1>
<del> <PrimaryFallbackTest />
<add> <h4>Primary to Fallback Cycle</h4>
<add> <PrimaryFallbackTest initialSuspend={false} />
<add> <h4>Fallback to Primary Cycle</h4>
<add> <PrimaryFallbackTest initialSuspend={true} />
<ide> <NestedSuspenseTest />
<ide> </>
<ide> );
<ide> }
<ide>
<del>function PrimaryFallbackTest() {
<del> const [suspend, setSuspend] = useState(false);
<add>function PrimaryFallbackTest({ initialSuspend }) {
<add> const [suspend, setSuspend] = useState(initialSuspend);
<ide> const fallbackStep = useTestSequence('fallback', Fallback1, Fallback2);
<ide> const primaryStep = useTestSequence('primary', Primary1, Primary2);
<ide> return (
<ide> <>
<del> <h3>Suspense Primary / Fallback</h3>
<ide> <label>
<ide> <input
<ide> checked={suspend}
<ide><path>src/backend/renderer.js
<ide> export function attach(
<ide> }
<ide> }
<ide>
<del> function recordUnmount(fiber) {
<add> function recordUnmount(fiber: Fiber) {
<ide> const isRoot = fiber.tag === HostRoot;
<ide> const primaryFiber = getPrimaryFiber(fiber);
<ide> if (!fiberToIDMap.has(primaryFiber)) {
<ide><path>src/devtools/views/Profiler/CommitTreeBuilder.js
<ide> import {
<ide> __DEBUG__,
<ide> TREE_OPERATION_ADD,
<add> TREE_OPERATION_RECURSIVE_REMOVE_CHILDREN,
<ide> TREE_OPERATION_REMOVE,
<ide> TREE_OPERATION_RESET_CHILDREN,
<ide> TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
<ide> function updateTree(
<ide> }
<ide> }
<ide> break;
<add> case TREE_OPERATION_RECURSIVE_REMOVE_CHILDREN:
<add> id = ((operations[i + 1]: any): number);
<add>
<add> i = i + 2;
<add>
<add> node = getClonedNode(id);
<add>
<add> const recursivelyRemove = childID => {
<add> const child = getClonedNode(childID);
<add> nodes.delete(childID);
<add> child.children.forEach(recursivelyRemove);
<add> };
<add>
<add> node.children.forEach(recursivelyRemove);
<add> node.children = [];
<add> break;
<ide> case TREE_OPERATION_REMOVE:
<ide> id = ((operations[i + 1]: any): number);
<ide> | 3 |
Go | Go | add check for removing non-existing config | cdc39fa29c710c7b56aef827166f9e98bb7c20b8 | <ide><path>integration/config/config_test.go
<ide> func TestConfigsCreateAndDelete(t *testing.T) {
<ide> assert.Check(t, errdefs.IsNotFound(err))
<ide> assert.Check(t, is.ErrorContains(err, configID))
<ide>
<add> err = c.ConfigRemove(ctx, "non-existing")
<add> assert.Check(t, errdefs.IsNotFound(err))
<add> assert.Check(t, is.ErrorContains(err, "non-existing"))
<add>
<ide> testName = "test_secret_with_labels_" + t.Name()
<ide> configID = createConfig(ctx, t, c, testName, []byte("TESTINGDATA"), map[string]string{
<ide> "key1": "value1", | 1 |
PHP | PHP | update remaining tests and fix path issues | eac89bf8bb490fa253e5d6711e91a8cb04374841 | <ide><path>src/Console/Command/Task/FixtureTask.php
<ide> class FixtureTask extends BakeTask {
<ide> *
<ide> * @var array
<ide> */
<del> public $tasks = ['DbConfig', 'Model', 'Template'];
<add> public $tasks = ['Model', 'Template'];
<ide>
<ide> /**
<ide> * path to fixtures directory
<ide> class FixtureTask extends BakeTask {
<ide> */
<ide> public function __construct($stdout = null, $stderr = null, $stdin = null) {
<ide> parent::__construct($stdout, $stderr, $stdin);
<del> $this->path = APP . 'Test/Fixture/';
<add> $this->path = ROOT . '/Test/Fixture/';
<ide> }
<ide>
<ide> /**
<ide> public function getOptionParser() {
<ide> 'help' => __d('cake_console', 'Used with --count and <name>/all commands to pull [n] records from the live tables, where [n] is either --count or the default of 10.'),
<ide> 'short' => 'r',
<ide> 'boolean' => true
<add> ])->addOption('conditions', [
<add> 'help' => __d('cake_console', 'The SQL snippet to use when importing records.'),
<add> 'default' => '1=1',
<ide> ]);
<ide>
<ide> return $parser;
<ide> protected function _makeRecordString($records) {
<ide> * @return array Array of records.
<ide> */
<ide> protected function _getRecordsFromTable($modelName, $useTable = null) {
<del> $condition = 'WHERE 1=1';
<ide> $recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
<del> $model = TableRegistry::get($modelName, [
<del> 'table' => $useTable,
<del> 'connection' => ConnectionManager::get($this->connection)
<del> ]);
<add> $conditions = (isset($this->params['conditions']) ? $this->params['conditions'] : '1=1');
<add> if (TableRegistry::exists($modelName)) {
<add> $model = TableRegistry::get($modelName);
<add> } else {
<add> $model = TableRegistry::get($modelName, [
<add> 'table' => $useTable,
<add> 'connection' => ConnectionManager::get($this->connection)
<add> ]);
<add> }
<ide> $records = $model->find('all', [
<del> 'conditions' => $condition,
<add> 'conditions' => $conditions,
<ide> 'recursive' => -1,
<ide> 'limit' => $recordCount
<ide> ]);
<ide> protected function _getRecordsFromTable($modelName, $useTable = null) {
<ide> $alias = $model->alias();
<ide> $out = [];
<ide> foreach ($records as $record) {
<del> $row = [];
<del> foreach ($record[$model->alias] as $field => $value) {
<del> if ($schema->columnType($field) === 'boolean') {
<del> $value = (int)(bool)$value;
<del> }
<del> $row[$field] = $value;
<del> }
<del> $out[] = $row;
<add> $out[] = $record->toArray();
<ide> }
<ide> return $out;
<ide> }
<ide><path>tests/TestCase/Console/Command/Task/FixtureTaskTest.php
<ide> public function testConstruct() {
<ide> $in = $this->getMock('Cake\Console\ConsoleInput', array(), array(), '', false);
<ide>
<ide> $Task = new FixtureTask($out, $out, $in);
<del> $this->assertEquals(APP . 'Test/Fixture/', $Task->path);
<add> $this->assertEquals(ROOT . '/Test/Fixture/', $Task->path);
<ide> }
<ide>
<ide> /**
<ide> public function testImportOptionsWithRecords() {
<ide> * @return void
<ide> */
<ide> public function testImportRecordsFromDatabaseWithConditionsPoo() {
<del> $this->markTestIncomplete('not done');
<del> $this->Task->interactive = true;
<del> $this->Task->expects($this->at(0))->method('in')
<del> ->will($this->returnValue('WHERE 1=1'));
<del>
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<ide>
<del> $result = $this->Task->bake('Article', false, array(
<del> 'fromTable' => true, 'schema' => 'Article', 'records' => false
<add> $result = $this->Task->bake('Articles', false, array(
<add> 'fromTable' => true,
<add> 'schema' => 'Articles',
<add> 'records' => false
<ide> ));
<ide>
<ide> $this->assertContains('namespace App\Test\Fixture;', $result);
<ide> public function testImportOptionsAlternateConnection() {
<ide> * @return void
<ide> */
<ide> public function testImportRecordsNoEscaping() {
<del> $this->markTestIncomplete('not done');
<ide> $db = ConnectionManager::get('test');
<ide> if ($db instanceof Sqlserver) {
<ide> $this->markTestSkipped('This test does not run on SQLServer');
<ide> }
<ide>
<ide> $articles = TableRegistry::get('Articles');
<del> $articles->updateAll(['body' => "'Body \"value\"'"]);
<del>
<del> $this->Task->interactive = true;
<del> $this->Task->expects($this->at(0))
<del> ->method('in')
<del> ->will($this->returnValue('WHERE 1=1 LIMIT 10'));
<add> $articles->updateAll(['body' => "Body \"value\""], []);
<ide>
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<ide> public function testExecuteIntoAll() {
<ide> * @return void
<ide> */
<ide> public function testAllWithCountAndRecordsFlags() {
<del> $this->markTestIncomplete('not done');
<ide> $this->Task->connection = 'test';
<ide> $this->Task->path = '/my/path/';
<del> $this->Task->args = array('all');
<del> $this->Task->params = array('count' => 10, 'records' => true);
<add> $this->Task->args = ['all'];
<add> $this->Task->params = ['count' => 10, 'records' => true];
<ide>
<ide> $this->Task->Model->expects($this->any())->method('listAll')
<ide> ->will($this->returnValue(array('Articles', 'comments')));
<ide>
<ide> $filename = '/my/path/ArticleFixture.php';
<del> $this->Task->expects($this->at(0))->method('createFile')
<add> $this->Task->expects($this->at(0))
<add> ->method('createFile')
<ide> ->with($filename, $this->stringContains("'title' => 'Third Article'"));
<ide>
<ide> $filename = '/my/path/CommentFixture.php';
<del> $this->Task->expects($this->at(1))->method('createFile')
<add> $this->Task->expects($this->at(1))
<add> ->method('createFile')
<ide> ->with($filename, $this->stringContains("'comment' => 'First Comment for First Article'"));
<ide> $this->Task->expects($this->exactly(2))->method('createFile');
<ide>
<ide><path>tests/TestCase/Console/Command/Task/ModelTaskTest.php
<ide> public function setUp() {
<ide> );
<ide> $this->Task->connection = 'test';
<ide> $this->_setupOtherMocks();
<add> TableRegistry::clear();
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Console/Command/Task/TemplateTaskTest.php
<ide> <?php
<ide> /**
<del> * TemplateTask file
<del> *
<del> * Test Case for TemplateTask generation shell task
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide>
<ide> /**
<ide> * TemplateTaskTest class
<del> *
<ide> */
<ide> class TemplateTaskTest extends TestCase {
<ide>
<ide> public function testGenerateWithTemplateFallbacks() {
<ide> $this->Task->initialize();
<ide> $this->Task->params['theme'] = 'test';
<ide> $this->Task->set(array(
<add> 'name' => 'Article',
<ide> 'model' => 'Article',
<ide> 'table' => 'articles',
<ide> 'import' => false, | 4 |
Ruby | Ruby | simplify cache hit logging | 07da5aebb165f824d540fac620d2374b7a3799bb | <ide><path>actionview/lib/action_view/helpers/cache_helper.rb
<ide> def cache_fragment_name(name = {}, skip_digest: nil, virtual_path: nil)
<ide> end
<ide> end
<ide>
<add> attr_reader :cache_hit # :nodoc:
<add>
<ide> private
<ide>
<ide> def fragment_name_with_digest(name, virtual_path) #:nodoc:
<ide> def fragment_name_with_digest(name, virtual_path) #:nodoc:
<ide> end
<ide> end
<ide>
<del> # TODO: Create an object that has caching read/write on it
<ide> def fragment_for(name = {}, options = nil, &block) #:nodoc:
<ide> if content = read_fragment_for(name, options)
<del> @log_payload_for_partial_render[:cache_hit] = true if defined?(@log_payload_for_partial_render)
<add> @cache_hit = true
<ide> content
<ide> else
<del> @log_payload_for_partial_render[:cache_hit] = false if defined?(@log_payload_for_partial_render)
<add> @cache_hit = false
<ide> write_fragment_for(name, options, &block)
<ide> end
<ide> end
<ide><path>actionview/lib/action_view/renderer/partial_renderer.rb
<ide> def render_partial
<ide> view, locals, block = @view, @locals, @block
<ide> object, as = @object, @variable
<ide>
<del> view.instance_variable_set(:@log_payload_for_partial_render, payload)
<del>
<ide> if !block && (layout = @options[:layout])
<ide> layout = find_template(layout.to_s, @template_keys)
<ide> end
<ide> def render_partial
<ide> end
<ide>
<ide> content = layout.render(view, locals) { content } if layout
<add> payload[:cache_hit] = view.cache_hit
<ide> content
<ide> end
<ide> end | 2 |
Javascript | Javascript | add more tests | da98e09d1384c592b3c44dfa3bc806ae367cbad4 | <ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js
<ide> const EMPTY_SET = new Set();
<ide> /**
<ide> * @param {string[][]} referencedExports list of referenced exports, will be added to
<ide> * @param {string[]} prefix export prefix
<del> * @param {ExportInfo} exportInfo the export info
<add> * @param {ExportInfo=} exportInfo the export info
<ide> * @param {boolean} defaultPointsToSelf when true, using default will reference itself
<ide> * @param {Set<ExportInfo>} alreadyVisited already visited export info (to handle circular reexports)
<ide> */
<ide><path>test/cases/parsing/harmony-export-import-specifier/b.js
<ide> import {c} from "./c.js";
<ide>
<ide> const b2 = 3;
<ide> const b3 = c;
<del>export {c as b1, b2, b3}
<add>export {c as b1, c as b4, b2, b3}
<ide> export const usedB1 = __webpack_exports_info__.b1.used;
<ide> export const usedB2 = __webpack_exports_info__.b2.used;
<ide> export const usedB3 = __webpack_exports_info__.b3.used;
<add>export const usedB4 = __webpack_exports_info__.b4.used;
<ide><path>test/cases/parsing/harmony-export-import-specifier/e.js
<add>export const e1 = 10;
<add>export const e2 = 20;
<add>export const usedE1 = __webpack_exports_info__.e1.used;
<add>export const usedE2 = __webpack_exports_info__.e2.used;
<ide><path>test/cases/parsing/harmony-export-import-specifier/e1.js
<add>export * as e from "./e.js";
<ide><path>test/cases/parsing/harmony-export-import-specifier/f.js
<add>export * as f1 from "./e1.js";
<add>export * as f2 from "./e.js";
<ide><path>test/cases/parsing/harmony-export-import-specifier/g.js
<add>import {f1, f2} from "./f.js";
<add>
<add>export {f1, f2 as g1};
<ide><path>test/cases/parsing/harmony-export-import-specifier/h.js
<add>export * as h from "./g.js";
<ide><path>test/cases/parsing/harmony-export-import-specifier/index.js
<ide>
<ide> import { x, y } from "./a";
<ide> import {d2, usedD1, usedD2} from "./d.js";
<del>import {b1, usedB1, usedB2, usedB3} from "./b.js";
<add>import {b1, usedB1, usedB2, usedB3, usedB4} from "./b.js";
<add>import {usedE1, usedE2} from "./e.js";
<add>import {h} from "./h.js";
<ide>
<ide> it("namespace export as from commonjs should override named export", function() {
<ide> expect(x).toBe(1);
<ide> it("named namespace export should work correctly", function () {
<ide> expect(usedB1).toBe(true);
<ide> expect(usedB2).toBe(false);
<ide> expect(usedB3).toBe(false);
<add> expect(usedB4).toBe(false);
<add>});
<add>
<add>it("complex case should work correctly", () => {
<add> expect(h.f1.e.e1).toBe(10);
<add> expect(h.g1.e1).toBe(10);
<add> expect(usedE1).toBe(true);
<add> expect(usedE2).toBe(false);
<ide> }); | 8 |
PHP | PHP | fix route facade docblock | a7931c396a2545bd4fd2ba2d73d0d8d5fbd16874 | <ide><path>src/Illuminate/Support/Facades/Route.php
<ide> namespace Illuminate\Support\Facades;
<ide>
<ide> /**
<del> * @method static \Illuminate\Routing\Route get(string $uri, \Closure|array|string $action)
<del> * @method static \Illuminate\Routing\Route post(string $uri, \Closure|array|string $action)
<del> * @method static \Illuminate\Routing\Route put(string $uri, \Closure|array|string $action)
<del> * @method static \Illuminate\Routing\Route delete(string $uri, \Closure|array|string $action)
<del> * @method static \Illuminate\Routing\Route patch(string $uri, \Closure|array|string $action)
<del> * @method static \Illuminate\Routing\Route options(string $uri, \Closure|array|string $action)
<del> * @method static \Illuminate\Routing\Route any(string $uri, \Closure|array|string $action)
<del> * @method static \Illuminate\Routing\Route match(array|string $methods, string $uri, \Closure|array|string $action)
<add> * @method static \Illuminate\Routing\Route get(string $uri, \Closure|array|string|null $action = null)
<add> * @method static \Illuminate\Routing\Route post(string $uri, \Closure|array|string|null $action = null)
<add> * @method static \Illuminate\Routing\Route put(string $uri, \Closure|array|string|null $action = null)
<add> * @method static \Illuminate\Routing\Route delete(string $uri, \Closure|array|string|null $action = null)
<add> * @method static \Illuminate\Routing\Route patch(string $uri, \Closure|array|string|null $action = null)
<add> * @method static \Illuminate\Routing\Route options(string $uri, \Closure|array|string|null $action = null)
<add> * @method static \Illuminate\Routing\Route any(string $uri, \Closure|array|string|null $action = null)
<add> * @method static \Illuminate\Routing\Route match(array|string $methods, string $uri, \Closure|array|string|null $action = null)
<ide> * @method static \Illuminate\Routing\Route prefix(string $prefix)
<ide> * @method static void resource(string $name, string $controller, array $options = [])
<ide> * @method static void apiResource(string $name, string $controller, array $options = [])
<del> * @method static void group(array $attributes, \Closure $callback)
<add> * @method static void group(array $attributes, \Closure|string $callback)
<ide> * @method static \Illuminate\Routing\Route middleware(array|string|null $middleware)
<ide> * @method static \Illuminate\Routing\Route substituteBindings(\Illuminate\Routing\Route $route)
<ide> * @method static void substituteImplicitBindings(\Illuminate\Routing\Route $route) | 1 |
Text | Text | finish authoring packages section | d9d9b6800be8af7ad28e39515a01e60aa9ac16f4 | <ide><path>docs/packages/authoring-packages.md
<ide> available, Atom package.json files [have their own additions](./package_json.md)
<ide> ## Source Code
<ide>
<ide> If you want to extend Atom's behavior, your package should contain a single
<del>top-level module, which you export from `index.coffee` (or whichever file is
<del>indicated by the `main` key in your `package.json` file). The remainder of your
<add>top-level module, which you export from _index.coffee_ (or whichever file is
<add>indicated by the `main` key in your _package.json_ file). The remainder of your
<ide> code should be placed in the `lib` directory, and required from your top-level
<ide> file.
<ide>
<ide> for examples of Atom's API in action.
<ide>
<ide> ## Stylesheets
<ide>
<del>Stylesheets for your package should be placed in the `stylesheets` directory.
<add>Stylesheets for your package should be placed in the _stylesheets_ directory.
<ide> Any stylesheets in this directory will be loaded and attached to the DOM when
<ide> your package is activated. Stylesheets can be written as CSS or LESS.
<ide>
<del>An optional `stylesheets` array in your `package.json` can list the stylesheets by
<add>An optional `stylesheets` array in your _package.json_ can list the stylesheets by
<ide> name to specify a loading order; otherwise, stylesheets are loaded alphabetically.
<ide>
<ide> ## Keymaps
<ide>
<del>Keymaps are placed in the `keymaps` subdirectory. It's a good idea to provide
<add>Keymaps are placed in the _keymaps_ subdirectory. It's a good idea to provide
<ide> default keymaps for your extension, especially if you're also adding a new command.
<ide>
<ide> By default, all keymaps are loaded in alphabetical order. An optional `keymaps`
<del>array in your `package.json` can specify which keymaps to load and in what order.
<add>array in your _package.json_ can specify which keymaps to load and in what order.
<ide>
<ide> See the [main keymaps documentation](../internals/keymaps.md) for more information on
<ide> how keymaps work.
<ide>
<ide> ## Snippets
<ide>
<del>An extension can supply language snippets in the `snippets` directory. These can
<add>An extension can supply language snippets in the _snippets_ directory. These can
<ide> be `.cson` or `.json` files. Here's an example:
<ide>
<ide> ```coffeescript
<ide> the first few letters to type before hitting the `tab` key to autocomplete. The
<ide> regions in the body the user can navigate to every time they hit `tab`.
<ide>
<ide> All files in the directory are automatically loaded, unless the
<del>`package.json` supplies a `snippets` key. As with all scoped
<add>_package.json_ supplies a `snippets` key. As with all scoped
<ide> items, snippets loaded later take precedence over earlier snippets when two
<ide> snippets match a scope with the same specificity.
<add>
<add>## Language Grammars
<add>
<add>If you're developing a new language grammar, you'll want to place your file in
<add>the _grammars_ directory. Each grammar is a pairing of two keys, `match` and
<add>`captures`. `match` is a regular expression identifying the pattern to highlight,
<add>while `captures` is a JSON representing what to do with each matching group.
<add>For example:
<add>
<add>
<add>```json
<add>{
<add> 'match': '(?:^|\\s)(__[^_]+__)'
<add> 'captures':
<add> '1': 'name': 'markup.bold.gfm'
<add>}
<add>```
<add>
<add>This indicates that the first matching capture (`(__[^_]+__)`) should have the
<add>`markup.bold.gfm` token applied to it.
<add>
<add>To capture a single group, simply use the `name` key instead:
<add>
<add>```json
<add>{
<add> 'match': '^#{1,6}\\s+.+$'
<add> 'name': 'markup.heading.gfm'
<add>}
<add>```
<add>
<add>This indicates that Markdown header lines (`#`, `##`, `###`) should be applied with
<add>the `markup.heading.gfm` token.
<add>
<add>More information about the significance of these tokens can be found in
<add>[section 12.4 of the TextMate Manual](http://manual.macromates.com/en/language_grammars.html).
<add>
<add>Your grammar should also include a `filetypes` array, which is a list of file extensions
<add>your grammar supports:
<add>
<add>```
<add>'fileTypes': [
<add> 'markdown'
<add> 'md'
<add> 'mkd'
<add> 'mkdown'
<add> 'ron'
<add>]
<add>```
<ide><path>docs/packages/authoring-themes.md
<del># Authoring A Theme
<add># Authoring Themes
<ide>
<ide> If you understand CSS, you can write an Atom theme easily. Your theme can style
<ide> Atom's user interface, specify the appearance of syntax-highlighted code, or | 2 |
PHP | PHP | fix typo in class name | 6d83c72dfb732857a4439187c2c8770ad9bcf069 | <ide><path>src/Cache/Engine/MemcachedEngine.php
<ide> public function init(array $config = []) {
<ide> if ($this->_config['persistent']) {
<ide> $this->_Memcached = new Memcached((string)$this->_config['persistent']);
<ide> } else {
<del> $this->_Memcached = new Memecached();
<add> $this->_Memcached = new Memcached();
<ide> }
<ide> $this->_setOptions();
<ide> | 1 |
PHP | PHP | add tests. extract class | b1a80f0c32e16753b5f50ec1172fdf8a8d41256e | <ide><path>src/Illuminate/Database/Console/Migrations/MigrateMakeCommand.php
<ide> public function handle()
<ide> // "create" in the name. This will allow us to provide a convenient way
<ide> // of creating migrations that create new tables for the application.
<ide> if (! $table) {
<del> if (preg_match('/^create_(\w+)_table$/', $name, $matches)) {
<del> $table = $matches[1];
<del>
<del> $create = true;
<del> }
<del> }
<del>
<del> // Next, we will attempt to guess the table name if this the migration has
<del> // "to", "from", "in" in the name. This will allow us to provide a convenient
<del> // way of creating migrations that modify tables in the application.
<del> if (! $table) {
<del> if (preg_match('/_(to|from|in)_(\w+)_table$/', $name, $matches)) {
<del> $table = $matches[2];
<del>
<del> $create = false;
<del> }
<add> [$table, $create] = TableGuesser::guess($name);
<ide> }
<ide>
<ide> // Now we are ready to write the migration out to disk. Once we've written
<ide><path>src/Illuminate/Database/Console/Migrations/TableGuesser.php
<add><?php
<add>
<add>namespace Illuminate\Database\Console\Migrations;
<add>
<add>class TableGuesser
<add>{
<add> /**
<add> * Attempt to guess the table name and "creation" status of the given migration.
<add> *
<add> * @param string $migration
<add> * @return array
<add> */
<add> public static function guess($migration)
<add> {
<add> if (preg_match('/^create_(\w+)_table$/', $migration, $matches)) {
<add> return [$matches[1], $create = true];
<add> }
<add>
<add> if (preg_match('/_(to|from|in)_(\w+)_table$/', $migration, $matches)) {
<add> return [$matches[2], $create = false];
<add> }
<add> }
<add>}
<ide><path>tests/Database/TableGuesserTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Database;
<add>
<add>use PHPUnit\Framework\TestCase;
<add>use Illuminate\Database\Console\Migrations\TableGuesser;
<add>
<add>class TableGuesserTest extends TestCase
<add>{
<add> public function test_migration_is_properly_parsed()
<add> {
<add> [$table, $create] = TableGuesser::guess('create_users_table');
<add> $this->assertEquals('users', $table);
<add> $this->assertTrue($create);
<add>
<add> [$table, $create] = TableGuesser::guess('add_status_column_to_users_table');
<add> $this->assertEquals('users', $table);
<add> $this->assertFalse($create);
<add>
<add> [$table, $create] = TableGuesser::guess('drop_status_column_from_users_table');
<add> $this->assertEquals('users', $table);
<add> $this->assertFalse($create);
<add> }
<add>} | 3 |
PHP | PHP | add basic implementation of deleteall() | b59c0376e01f7a4f6d36b77dea65de9a1a49e725 | <ide><path>lib/Cake/ORM/Table.php
<ide> public function updateAll($fields, $conditions) {
<ide> return true;
<ide> }
<ide>
<add>/**
<add> * Delete all matching rows.
<add> *
<add> * Deletes all rows matching the provided conditions.
<add> *
<add> * This method will *not* trigger beforeDelete/afterDelete events. If you
<add> * need those first load a collection of records and delete them.
<add> *
<add> * This method will *not* execute on associations `cascade` attribute. You should
<add> * use database foreign keys + ON CASCADE rules if you need cascading deletes combined
<add> * with this method.
<add> *
<add> * @param array $conditions An array of conditions, similar to those used with find()
<add> * @return boolean Success
<add> */
<add> public function deleteAll($conditions) {
<add> $query = $this->_buildQuery();
<add> $query->delete($this->table())
<add> ->where($conditions);
<add> $query->execute();
<add> return true;
<add> }
<add>
<ide> }
<ide><path>lib/Cake/Test/TestCase/ORM/TableTest.php
<ide> public function testUpdateAllFailure() {
<ide> $table->updateAll(['username' => 'mark'], []);
<ide> }
<ide>
<add>/**
<add> * Test deleting many records.
<add> *
<add> * @return void
<add> */
<add> public function testDeleteAll() {
<add> $table = new Table(['table' => 'users', 'connection' => $this->connection]);
<add> $result = $table->deleteAll(['id <' => 4]);
<add> $this->assertTrue($result);
<add>
<add> $result = $table->find('all')->toArray();
<add> $this->assertCount(1, $result, 'Only one record should remain');
<add> $this->assertEquals(4, $result[0]['id']);
<add> }
<add>
<add>/**
<add> * Test that exceptions from the Query bubble up.
<add> *
<add> * @expectedException Cake\Database\Exception
<add> */
<add> public function testDeleteAllFailure() {
<add> $table = $this->getMock(
<add> 'Cake\ORM\Table',
<add> ['_buildQuery'],
<add> ['table' => 'users', 'connection' => $this->connection]
<add> );
<add> $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection]);
<add> $table->expects($this->once())
<add> ->method('_buildQuery')
<add> ->will($this->returnValue($query));
<add> $query->expects($this->once())
<add> ->method('execute')
<add> ->will($this->throwException(new \Cake\Database\Exception('Not good')));
<add> $table->deleteAll(['id >' => 4]);
<add> }
<add>
<ide> } | 2 |
Text | Text | use my legal name in readme | 64129898fecb3c60ec9bdcc015da1eef6afec236 | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> * [thlorenz](https://github.com/thlorenz) -
<ide> **Thorsten Lorenz** <thlorenz@gmx.de>
<ide> * [TimothyGu](https://github.com/TimothyGu) -
<del>**Timothy Gu** <timothygu99@gmail.com> (he/him)
<add>**Tiancheng "Timothy" Gu** <timothygu99@gmail.com> (he/him)
<ide> * [tniessen](https://github.com/tniessen) -
<ide> **Tobias Nießen** <tniessen@tnie.de>
<ide> * [trevnorris](https://github.com/trevnorris) - | 1 |
PHP | PHP | allow quarterly scheduling | e53d12ae28536d42f93e6a5c7327eefd05c6b2cf | <ide><path>src/Illuminate/Console/Scheduling/Event.php
<ide> public function yearly()
<ide> return $this->cron('0 0 1 1 * *');
<ide> }
<ide>
<add> /**
<add> * Schedule the event to run quarterly.
<add> *
<add> * @return $this
<add> */
<add> public function quarterly()
<add> {
<add> return $this->cron('0 0 1 */3 *');
<add> }
<add>
<ide> /**
<ide> * Schedule the event to run every minute.
<ide> * | 1 |
Text | Text | fix documentation inconsistency for volume create | f67da614e9963e626d4ec12fd624249947b97d6a | <ide><path>docs/reference/commandline/volume_create.md
<ide> Creates a new volume that containers can consume and store data in. If a name is
<ide> hello
<ide> $ docker run -d -v hello:/world busybox ls /world
<ide>
<del>The mount is created inside the container's `/src` directory. Docker does not support relative paths for mount points inside the container.
<add>The mount is created inside the container's `/world` directory. Docker does not support relative paths for mount points inside the container.
<ide>
<ide> Multiple containers can use the same volume in the same time period. This is useful if two containers need access to shared data. For example, if one container writes and the other reads the data.
<ide> | 1 |
Text | Text | add command flag to import.meta.resolve | eee2c331ef501e91a0811284323cff431630e5f4 | <ide><path>doc/api/esm.md
<ide> const buffer = readFileSync(new URL('./data.proto', import.meta.url));
<ide>
<ide> > Stability: 1 - Experimental
<ide>
<add>This feature is only available with the `--experimental-import-meta-resolve`
<add>command flag enabled.
<add>
<ide> * `specifier` {string} The module specifier to resolve relative to `parent`.
<ide> * `parent` {string|URL} The absolute parent module URL to resolve from. If none
<ide> is specified, the value of `import.meta.url` is used as the default. | 1 |
PHP | PHP | rewrite conditionals to be more intuitive | 9be2b500eaa5833628046d096410f23948f454fe | <ide><path>src/Illuminate/Support/Arr.php
<ide> public static function get($array, $key, $default = null)
<ide> }
<ide>
<ide> foreach (explode('.', $key) as $segment) {
<del> if ((! is_array($array) || ! array_key_exists($segment, $array)) &&
<del> (! $array instanceof ArrayAccess || ! $array->offsetExists($segment))) {
<add> if ((is_array($array) && array_key_exists($segment, $array))
<add> || ($array instanceof ArrayAccess && $array->offsetExists($segment))) {
<add> $array = $array[$segment];
<add> } else {
<ide> return value($default);
<ide> }
<del>
<del> $array = $array[$segment];
<ide> }
<ide>
<ide> return $array;
<ide> public static function has($array, $key)
<ide> }
<ide>
<ide> foreach (explode('.', $key) as $segment) {
<del> if ((! is_array($array) || ! array_key_exists($segment, $array)) &&
<del> (! $array instanceof ArrayAccess || ! $array->offsetExists($segment))) {
<add> if ((is_array($array) && array_key_exists($segment, $array))
<add> || ($array instanceof ArrayAccess && $array->offsetExists($segment))) {
<add> $array = $array[$segment];
<add> } else {
<ide> return false;
<ide> }
<del>
<del> $array = $array[$segment];
<ide> }
<ide>
<ide> return true; | 1 |
Javascript | Javascript | update cms examples to use the new tw grid gaps | 6b37d6c39e6752ab21a4417cace73f51a30e513c | <ide><path>examples/cms-agilitycms/components/hero-post.js
<ide> export default function HeroPost({
<ide> slug={slug}
<ide> />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-agilitycms/components/more-stories.js
<ide> export default function MoreStories({ title, posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> {title}
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-builder-io/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage title={title} slug={slug} url={coverImage} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-builder-io/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.data.slug}
<ide><path>examples/cms-buttercms/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage title={title} url={coverImage} slug={slug} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-buttercms/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-contentful/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage title={title} slug={slug} url={coverImage.url} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-contentful/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-cosmic/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage title={title} url={coverImage.imgix_url} slug={slug} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-cosmic/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-datocms/components/hero-post.js
<ide> export default function HeroPost({
<ide> slug={slug}
<ide> />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-datocms/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-drupal/components/hero-post.js
<ide> export default function HeroPost({
<ide> <CoverImage title={title} coverImage={coverImage} slug={slug} />
<ide> )}
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={slug}>
<ide><path>examples/cms-ghost/components/hero-post.js
<ide> export default function HeroPost({
<ide> height={1216}
<ide> />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-ghost/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-graphcms/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage slug={slug} title={title} url={coverImage.url} />
<ide> </div>
<del> <div className="mb-20 md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 md:mb-28">
<add> <div className="mb-20 md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl leading-tight lg:text-6xl">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-kontent/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage title={title} src={coverImage} slug={slug} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-kontent/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-prepr/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage slug={slug} title={title} url={coverImage} />
<ide> </div>
<del> <div className="mb-20 md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 md:mb-28">
<add> <div className="mb-20 md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl leading-tight lg:text-6xl">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-prismic/components/hero-post.js
<ide> export default function HeroPost({
<ide> url={coverImage.url}
<ide> />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-prismic/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map(({ node }) => (
<ide> <PostPreview
<ide> key={node._meta.uid}
<ide><path>examples/cms-sanity/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage slug={slug} title={title} image={coverImage} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-sanity/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-storyblok/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage title={title} url={coverImage} slug={slug} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-storyblok/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-strapi/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage title={title} url={coverImage.url} slug={slug} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-strapi/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-takeshape/components/hero-post.js
<ide> export default function HeroPost({
<ide> <div className="mb-8 md:mb-16">
<ide> <CoverImage title={title} coverImage={coverImage} slug={slug} />
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-takeshape/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map((post) => (
<ide> <PostPreview
<ide> key={post.slug}
<ide><path>examples/cms-wordpress/components/hero-post.js
<ide> export default function HeroPost({
<ide> <CoverImage title={title} coverImage={coverImage} slug={slug} />
<ide> )}
<ide> </div>
<del> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28">
<add> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<ide> <div>
<ide> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<ide> <Link href={`/posts/${slug}`}>
<ide><path>examples/cms-wordpress/components/more-stories.js
<ide> export default function MoreStories({ posts }) {
<ide> <h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
<ide> More Stories
<ide> </h2>
<del> <div className="grid grid-cols-1 md:grid-cols-2 md:col-gap-16 lg:col-gap-32 row-gap-20 md:row-gap-32 mb-32">
<add> <div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
<ide> {posts.map(({ node }) => (
<ide> <PostPreview
<ide> key={node.slug} | 31 |
Python | Python | remove outdated tests | d36c7b2d937aa85574b0ff993d6e8e8f15ccc6aa | <ide><path>tests/keras/engine/test_training.py
<ide> def test_check_bad_shape():
<ide> [a], [losses.CategoricalCrossentropy()], [(2, 3, 6)])
<ide>
<ide>
<del>@pytest.mark.parametrize('input_metrics,expected_output', [
<del> (None, [[], []]),
<del> (['mse', 'mae'], [['mse', 'mae'], ['mse', 'mae']]),
<del> ({'layer_1': 'mae', 'layer_2': 'mse'}, [['mae'], ['mse']]),
<del>])
<del>def test_collect_metrics(input_metrics, expected_output):
<del> output_names = ['layer_1', 'layer_2']
<del>
<del> output_metrics = training_utils.collect_metrics(input_metrics,
<del> output_names)
<del> assert output_metrics == expected_output
<del>
<del>
<del>def test_collect_metrics_with_invalid_metrics_format():
<del> with pytest.raises(TypeError):
<del> training_utils.collect_metrics({'a', 'set', 'type'}, [])
<del>
<del>
<del>def test_collect_metrics_with_invalid_layer_name():
<del> with pytest.warns(Warning) as w:
<del> training_utils.collect_metrics({'unknown_layer': 'mse'}, ['layer_1'])
<del>
<del> warning_raised = all(['unknown_layer' in str(w_.message) for w_ in w])
<del> assert warning_raised, 'Warning was raised for unknown_layer'
<del>
<del>
<ide> @pytest.mark.skipif(K.backend() != 'tensorflow',
<ide> reason='Requires TensorFlow backend')
<ide> def test_model_with_input_feed_tensor(): | 1 |
Go | Go | skip apparmor tests on user namespace | 70ce2d9b10e7119218ccf10a9b83d86acd2b1ed6 | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestMountIntoSys(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
<ide> // Not applicable on Windows as uses Unix specific functionality
<del> testRequires(c, Apparmor, DaemonIsLinux)
<add> testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
<ide>
<ide> name := "acidburn"
<ide> if out, _, err := dockerCmdWithError("run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount"); err == nil || !strings.Contains(out, "Permission denied") {
<ide> func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) {
<ide> // Not applicable on Windows as uses Unix specific functionality
<del> testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux)
<add> testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotUserNamespace)
<ide> _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo")
<ide> if exitCode == 0 {
<ide> // If our test failed, attempt to repair the host system... | 1 |
Python | Python | add __neg__ and __pos__ methods to poly1d | 6f509f626355208b3cb97e692daf52c3734769cd | <ide><path>numpy/lib/polynomial.py
<ide> def __str__(self):
<ide> def __call__(self, val):
<ide> return polyval(self.coeffs, val)
<ide>
<add> def __neg__(self):
<add> return poly1d(-self.coeffs)
<add>
<add> def __pos__(self):
<add> return self
<add>
<ide> def __mul__(self, other):
<ide> if isscalar(other):
<ide> return poly1d(self.coeffs * other) | 1 |
Python | Python | fix mypy errors in `tests/utils` | 18a977ccc53f036413ccac4cab679fb7b37c65f0 | <ide><path>airflow/utils/email.py
<ide> def send_email_smtp(
<ide> mime_subtype: str = 'mixed',
<ide> mime_charset: str = 'utf-8',
<ide> conn_id: str = "smtp_default",
<del> from_email: str = None,
<add> from_email: Optional[str] = None,
<ide> custom_headers: Optional[Dict[str, Any]] = None,
<ide> **kwargs,
<ide> ):
<ide> def send_email_smtp(
<ide> """
<ide> smtp_mail_from = conf.get('smtp', 'SMTP_MAIL_FROM')
<ide>
<del> mail_from = smtp_mail_from or from_email
<add> if smtp_mail_from:
<add> mail_from = smtp_mail_from
<add> else:
<add> mail_from = from_email
<ide>
<ide> msg, recipients = build_mime_message(
<ide> mail_from=mail_from,
<ide> def build_mime_message(
<ide>
<ide>
<ide> def send_mime_email(
<del> e_from: str, e_to: List[str], mime_msg: MIMEMultipart, conn_id: str = "smtp_default", dryrun: bool = False
<add> e_from: str,
<add> e_to: Union[str, List[str]],
<add> mime_msg: MIMEMultipart,
<add> conn_id: str = "smtp_default",
<add> dryrun: bool = False,
<ide> ) -> None:
<ide> """Send MIME email."""
<ide> smtp_host = conf.get('smtp', 'SMTP_HOST')
<ide> def send_mime_email(
<ide> smtp_user = None
<ide> smtp_password = None
<ide>
<del> smtp_user, smtp_password = None, None
<ide> if conn_id is not None:
<ide> try:
<ide> from airflow.hooks.base import BaseHook
<ide> def send_mime_email(
<ide> for attempt in range(1, smtp_retry_limit + 1):
<ide> log.info("Email alerting: attempt %s", str(attempt))
<ide> try:
<del> conn = _get_smtp_connection(smtp_host, smtp_port, smtp_timeout, smtp_ssl)
<add> smtp_conn = _get_smtp_connection(smtp_host, smtp_port, smtp_timeout, smtp_ssl)
<ide> except smtplib.SMTPServerDisconnected:
<ide> if attempt < smtp_retry_limit:
<ide> continue
<ide> raise
<ide>
<ide> if smtp_starttls:
<del> conn.starttls()
<add> smtp_conn.starttls()
<ide> if smtp_user and smtp_password:
<del> conn.login(smtp_user, smtp_password)
<add> smtp_conn.login(smtp_user, smtp_password)
<ide> log.info("Sent an alert email to %s", e_to)
<del> conn.sendmail(e_from, e_to, mime_msg.as_string())
<del> conn.quit()
<add> smtp_conn.sendmail(e_from, e_to, mime_msg.as_string())
<add> smtp_conn.quit()
<ide> break
<ide>
<ide>
<ide><path>tests/utils/test_email.py
<ide>
<ide> import pytest
<ide>
<del>from airflow import utils
<ide> from airflow.configuration import conf
<del>from airflow.utils.email import build_mime_message, get_email_address_list
<add>from airflow.utils import email
<ide> from tests.test_utils.config import conf_vars
<ide>
<ide> EMAILS = ['test1@example.com', 'test2@example.com']
<ide> class TestEmail(unittest.TestCase):
<ide> def test_get_email_address_single_email(self):
<ide> emails_string = 'test1@example.com'
<ide>
<del> assert get_email_address_list(emails_string) == [emails_string]
<add> assert email.get_email_address_list(emails_string) == [emails_string]
<ide>
<ide> def test_get_email_address_comma_sep_string(self):
<ide> emails_string = 'test1@example.com, test2@example.com'
<ide>
<del> assert get_email_address_list(emails_string) == EMAILS
<add> assert email.get_email_address_list(emails_string) == EMAILS
<ide>
<ide> def test_get_email_address_colon_sep_string(self):
<ide> emails_string = 'test1@example.com; test2@example.com'
<ide>
<del> assert get_email_address_list(emails_string) == EMAILS
<add> assert email.get_email_address_list(emails_string) == EMAILS
<ide>
<ide> def test_get_email_address_list(self):
<ide> emails_list = ['test1@example.com', 'test2@example.com']
<ide>
<del> assert get_email_address_list(emails_list) == EMAILS
<add> assert email.get_email_address_list(emails_list) == EMAILS
<ide>
<ide> def test_get_email_address_tuple(self):
<ide> emails_tuple = ('test1@example.com', 'test2@example.com')
<ide>
<del> assert get_email_address_list(emails_tuple) == EMAILS
<add> assert email.get_email_address_list(emails_tuple) == EMAILS
<ide>
<ide> def test_get_email_address_invalid_type(self):
<ide> emails_string = 1
<ide>
<ide> with pytest.raises(TypeError):
<del> get_email_address_list(emails_string)
<add> email.get_email_address_list(emails_string)
<ide>
<ide> def test_get_email_address_invalid_type_in_iterable(self):
<ide> emails_list = ['test1@example.com', 2]
<ide>
<ide> with pytest.raises(TypeError):
<del> get_email_address_list(emails_list)
<add> email.get_email_address_list(emails_list)
<ide>
<ide> def setUp(self):
<ide> conf.remove_option('email', 'EMAIL_BACKEND')
<ide> conf.remove_option('email', 'EMAIL_CONN_ID')
<ide>
<ide> @mock.patch('airflow.utils.email.send_email')
<ide> def test_default_backend(self, mock_send_email):
<del> res = utils.email.send_email('to', 'subject', 'content')
<add> res = email.send_email('to', 'subject', 'content')
<ide> mock_send_email.assert_called_once_with('to', 'subject', 'content')
<ide> assert mock_send_email.return_value == res
<ide>
<ide> @mock.patch('airflow.utils.email.send_email_smtp')
<ide> def test_custom_backend(self, mock_send_email):
<ide> with conf_vars({('email', 'email_backend'): 'tests.utils.test_email.send_email_test'}):
<del> utils.email.send_email('to', 'subject', 'content')
<add> email.send_email('to', 'subject', 'content')
<ide> send_email_test.assert_called_once_with(
<ide> 'to',
<ide> 'subject',
<ide> def test_custom_backend(self, mock_send_email):
<ide> }
<ide> )
<ide> def test_custom_backend_sender(self, mock_send_email_smtp):
<del> utils.email.send_email('to', 'subject', 'content')
<add> email.send_email('to', 'subject', 'content')
<ide> _, call_kwargs = send_email_test.call_args
<ide> assert call_kwargs['from_email'] == 'from@test.com'
<ide> assert not mock_send_email_smtp.called
<ide> def test_build_mime_message(self):
<ide> html_content = '<html>Test</html>'
<ide> custom_headers = {'Reply-To': 'reply_to@example.com'}
<ide>
<del> msg, recipients = build_mime_message(
<add> msg, recipients = email.build_mime_message(
<ide> mail_from=mail_from,
<ide> to=mail_to,
<ide> subject=subject,
<ide> def test_send_smtp(self, mock_send_mime):
<ide> with tempfile.NamedTemporaryFile() as attachment:
<ide> attachment.write(b'attachment')
<ide> attachment.seek(0)
<del> utils.email.send_email_smtp('to', 'subject', 'content', files=[attachment.name])
<add> email.send_email_smtp('to', 'subject', 'content', files=[attachment.name])
<ide> assert mock_send_mime.called
<ide> _, call_args = mock_send_mime.call_args
<ide> assert conf.get('smtp', 'SMTP_MAIL_FROM') == call_args['e_from']
<ide> def test_send_smtp(self, mock_send_mime):
<ide>
<ide> @mock.patch('airflow.utils.email.send_mime_email')
<ide> def test_send_smtp_with_multibyte_content(self, mock_send_mime):
<del> utils.email.send_email_smtp('to', 'subject', '🔥', mime_charset='utf-8')
<add> email.send_email_smtp('to', 'subject', '🔥', mime_charset='utf-8')
<ide> assert mock_send_mime.called
<ide> _, call_args = mock_send_mime.call_args
<ide> msg = call_args['mime_msg']
<ide> def test_send_bcc_smtp(self, mock_send_mime):
<ide> with tempfile.NamedTemporaryFile() as attachment:
<ide> attachment.write(b'attachment')
<ide> attachment.seek(0)
<del> utils.email.send_email_smtp(
<add> email.send_email_smtp(
<ide> 'to',
<ide> 'subject',
<ide> 'content',
<ide> def test_send_bcc_smtp(self, mock_send_mime):
<ide> def test_send_mime(self, mock_smtp, mock_smtp_ssl):
<ide> mock_smtp.return_value = mock.Mock()
<ide> msg = MIMEMultipart()
<del> utils.email.send_mime_email('from', 'to', msg, dryrun=False)
<add> email.send_mime_email('from', 'to', msg, dryrun=False)
<ide> mock_smtp.assert_called_once_with(
<ide> host=conf.get('smtp', 'SMTP_HOST'),
<ide> port=conf.getint('smtp', 'SMTP_PORT'),
<ide> def test_send_mime_conn_id(self, mock_hook, mock_smtp):
<ide> mock_conn.login = 'user'
<ide> mock_conn.password = 'password'
<ide> mock_hook.get_connection.return_value = mock_conn
<del> utils.email.send_mime_email('from', 'to', msg, dryrun=False, conn_id='smtp_default')
<add> email.send_mime_email('from', 'to', msg, dryrun=False, conn_id='smtp_default')
<ide> mock_hook.get_connection.assert_called_with('smtp_default')
<ide> mock_smtp.return_value.login.assert_called_once_with('user', 'password')
<ide> mock_smtp.return_value.sendmail.assert_called_once_with('from', 'to', msg.as_string())
<ide> def test_send_mime_conn_id(self, mock_hook, mock_smtp):
<ide> def test_send_mime_ssl(self, mock_smtp, mock_smtp_ssl):
<ide> mock_smtp_ssl.return_value = mock.Mock()
<ide> with conf_vars({('smtp', 'smtp_ssl'): 'True'}):
<del> utils.email.send_mime_email('from', 'to', MIMEMultipart(), dryrun=False)
<add> email.send_mime_email('from', 'to', MIMEMultipart(), dryrun=False)
<ide> assert not mock_smtp.called
<ide> mock_smtp_ssl.assert_called_once_with(
<ide> host=conf.get('smtp', 'SMTP_HOST'),
<ide> def test_send_mime_noauth(self, mock_smtp, mock_smtp_ssl):
<ide> ('smtp', 'smtp_password'): None,
<ide> }
<ide> ):
<del> utils.email.send_mime_email('from', 'to', MIMEMultipart(), dryrun=False)
<add> email.send_mime_email('from', 'to', MIMEMultipart(), dryrun=False)
<ide> assert not mock_smtp_ssl.called
<ide> mock_smtp.assert_called_once_with(
<ide> host=conf.get('smtp', 'SMTP_HOST'),
<ide> def test_send_mime_noauth(self, mock_smtp, mock_smtp_ssl):
<ide> @mock.patch('smtplib.SMTP_SSL')
<ide> @mock.patch('smtplib.SMTP')
<ide> def test_send_mime_dryrun(self, mock_smtp, mock_smtp_ssl):
<del> utils.email.send_mime_email('from', 'to', MIMEMultipart(), dryrun=True)
<add> email.send_mime_email('from', 'to', MIMEMultipart(), dryrun=True)
<ide> assert not mock_smtp.called
<ide> assert not mock_smtp_ssl.called
<ide>
<ide> @mock.patch('smtplib.SMTP_SSL')
<ide> @mock.patch('smtplib.SMTP')
<del> def test_send_mime_complete_failure(self, mock_smtp: mock, mock_smtp_ssl):
<add> def test_send_mime_complete_failure(self, mock_smtp: mock.Mock, mock_smtp_ssl: mock.Mock):
<ide> mock_smtp.side_effect = SMTPServerDisconnected()
<ide> msg = MIMEMultipart()
<ide> with pytest.raises(SMTPServerDisconnected):
<del> utils.email.send_mime_email('from', 'to', msg, dryrun=False)
<add> email.send_mime_email('from', 'to', msg, dryrun=False)
<ide>
<ide> mock_smtp.assert_any_call(
<ide> host=conf.get('smtp', 'SMTP_HOST'),
<ide> def test_send_mime_ssl_complete_failure(self, mock_smtp, mock_smtp_ssl):
<ide> msg = MIMEMultipart()
<ide> with conf_vars({('smtp', 'smtp_ssl'): 'True'}):
<ide> with pytest.raises(SMTPServerDisconnected):
<del> utils.email.send_mime_email('from', 'to', msg, dryrun=False)
<add> email.send_mime_email('from', 'to', msg, dryrun=False)
<ide>
<ide> mock_smtp_ssl.assert_any_call(
<ide> host=conf.get('smtp', 'SMTP_HOST'),
<ide> def test_send_mime_custom_timeout_retrylimit(self, mock_smtp, mock_smtp_ssl):
<ide> }
<ide> ):
<ide> with pytest.raises(SMTPServerDisconnected):
<del> utils.email.send_mime_email('from', 'to', msg, dryrun=False)
<add> email.send_mime_email('from', 'to', msg, dryrun=False)
<ide>
<ide> mock_smtp.assert_any_call(
<ide> host=conf.get('smtp', 'SMTP_HOST'), port=conf.getint('smtp', 'SMTP_PORT'), timeout=custom_timeout
<ide> def test_send_mime_partial_failure(self, mock_smtp, mock_smtp_ssl):
<ide> mock_smtp.side_effect = side_effects
<ide> msg = MIMEMultipart()
<ide>
<del> utils.email.send_mime_email('from', 'to', msg, dryrun=False)
<add> email.send_mime_email('from', 'to', msg, dryrun=False)
<ide>
<ide> mock_smtp.assert_any_call(
<ide> host=conf.get('smtp', 'SMTP_HOST'), | 2 |
Javascript | Javascript | improve invalidation of view's controller prop | 627d214428191b7bcd2a8ad23aa5d048d9e6734c | <ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> return value;
<ide> } else {
<ide> parentView = get(this, 'parentView');
<del>
<ide> return parentView ? get(parentView, 'controller') : null;
<ide> }
<ide> }).property().cacheable(),
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> view.propertyDidChange('itemView');
<ide> view.propertyDidChange('contentView');
<ide> });
<add>
<add> if (getPath(this, 'parentView.controller') && !get(this, 'controller')) {
<add> this.notifyPropertyChange('controller');
<add> }
<ide> }, '_parentView'),
<ide>
<add> _controllerDidChange: Ember.observer(function() {
<add> if (this.isDestroying) { return; }
<add>
<add> this.forEachChildView(function(view) {
<add> view.propertyDidChange('controller');
<add> });
<add> }, 'controller'),
<add>
<ide> cloneKeywords: function() {
<ide> var templateData = get(this, 'templateData');
<ide>
<ide><path>packages/ember-views/tests/views/view/controller_test.js
<add>module("Ember.View - controller property");
<add>
<add>test("controller property should be inherited from nearest ancestor with controller", function() {
<add> var grandparent = Ember.ContainerView.create();
<add> var parent = Ember.ContainerView.create();
<add> var child = Ember.ContainerView.create();
<add> var grandchild = Ember.ContainerView.create();
<add>
<add> var grandparentController = {};
<add> var parentController = {};
<add>
<add> Ember.run(function() {
<add> grandparent.set('controller', grandparentController);
<add> parent.set('controller', parentController);
<add>
<add> grandparent.get('childViews').pushObject(parent);
<add> parent.get('childViews').pushObject(child);
<add>
<add> strictEqual(grandparent.get('controller'), grandparentController);
<add> strictEqual(parent.get('controller'), parentController);
<add> strictEqual(child.get('controller'), parentController);
<add> strictEqual(grandchild.get('controller'), null);
<add>
<add> child.get('childViews').pushObject(grandchild);
<add> strictEqual(grandchild.get('controller'), parentController);
<add>
<add> var newController = {};
<add> parent.set('controller', newController);
<add> strictEqual(parent.get('controller'), newController);
<add> strictEqual(child.get('controller'), newController);
<add> strictEqual(grandchild.get('controller'), newController);
<add> });
<add>}); | 2 |
Go | Go | fix improper use of `--rm` in test case | f05ed0075893bb907b5cc2612d9193d775134e2d | <ide><path>integration-cli/docker_cli_network_unix_test.go
<ide> func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromBridge(c *check.C) {
<ide> network := strings.TrimSpace(out)
<ide>
<ide> name := "test"
<del> dockerCmd(c, "create", "--rm", "--name", name, "busybox", "top")
<add> dockerCmd(c, "create", "--name", name, "busybox", "top")
<ide>
<ide> _, _, err := dockerCmdWithError("network", "disconnect", network, name)
<ide> c.Assert(err, check.IsNil) | 1 |
Text | Text | add teletype highlights from the past week | 1cb3a0ed60fe282e55dca12b7bb2646d6f502ca4 | <ide><path>docs/focus/2018-04-09.md
<ide> - Started implementing [atom/github/#1374 "Add dialog for new co-author"](https://github.com/atom/github/pull/1374). This includes UI polish and some bugfixes for existing co author flows. @kuychaco / @annthurium
<ide> - Merged [atom/github#1364 "Undo last commit and amend context menu option"](https://github.com/atom/github/pull/1364) @kuychaco / @annthurium
<ide> - Teletype
<add> - Enhanced file metadata syncing to update guest workspaces when host renames a shared file ([atom/teletype#147](https://github.com/atom/teletype/issues/147#issuecomment-378401644)). Thanks, [@CaptainJohnyAppleSeed](https://github.com/CaptainJohnyAppleSeed) and [@odoyle71](https://github.com/odoyle71)!
<add> - Improved handling (hopefully 🤞) of potential race condition when joining a portal with poor network connectivity ([atom/teletype-client#58](https://github.com/atom/teletype-client/pull/58))
<add> - Published [Teletype 0.12.0](https://github.com/atom/teletype/releases/tag/v0.12.0) with the above improvements
<ide> - Xray
<ide> - Reactor Duty
<ide>
<ide> - Get "Add dialog for new co-author" [atom/github#1374](https://github.com/atom/github/pull/1374) merged. @annthurium / @kuychaco
<ide> - Start implementing code coverage to get better visibility into our unit test coverage gaps. @annthurium
<ide> - Revive the React 16 and Enzyme port started in [atom/github#1174](https://github.com/atom/github/pull/1174). @smashwilson
<del>- Teletype
<ide> - Tree-sitter
<ide> - Xray
<ide><path>docs/focus/README.md
<ide> Longer-term goal: Provide the world's fastest transition from "I want to collabo
<ide>
<ide> ##### 4. Prioritized bugs
<ide>
<del>- [ ] Uncaught TypeError: Cannot match against 'undefined' or 'null' (https://github.com/atom/teletype/issues/233)
<add>- [x] Uncaught TypeError: Cannot match against 'undefined' or 'null' (https://github.com/atom/teletype/issues/233)
<ide>
<ide> ## Looking farther ahead
<ide> | 2 |
Python | Python | add some tests for array2print | 4b45c32ec108bd197e76697088079c96cf106902 | <ide><path>numpy/core/tests/test_arrayprint.py
<ide> def test_str(self):
<ide> dtypes = [np.complex64, np.cdouble, np.clongdouble]
<ide> actual = [str(np.array([c], dt)) for c in cvals for dt in dtypes]
<ide> wanted = [
<del> '[ 0.+0.j]', '[ 0.+0.j]', '[ 0.0+0.0j]',
<del> '[ 0.+1.j]', '[ 0.+1.j]', '[ 0.0+1.0j]',
<del> '[ 0.-1.j]', '[ 0.-1.j]', '[ 0.0-1.0j]',
<del> '[ 0.+infj]', '[ 0.+infj]', '[ 0.0+infj]',
<del> '[ 0.-infj]', '[ 0.-infj]', '[ 0.0-infj]',
<del> '[ 0.+nanj]', '[ 0.+nanj]', '[ 0.0+nanj]',
<del> '[ 1.+0.j]', '[ 1.+0.j]', '[ 1.0+0.0j]',
<del> '[ 1.+1.j]', '[ 1.+1.j]', '[ 1.0+1.0j]',
<del> '[ 1.-1.j]', '[ 1.-1.j]', '[ 1.0-1.0j]',
<del> '[ 1.+infj]', '[ 1.+infj]', '[ 1.0+infj]',
<del> '[ 1.-infj]', '[ 1.-infj]', '[ 1.0-infj]',
<del> '[ 1.+nanj]', '[ 1.+nanj]', '[ 1.0+nanj]',
<del> '[-1.+0.j]', '[-1.+0.j]', '[-1.0+0.0j]',
<del> '[-1.+1.j]', '[-1.+1.j]', '[-1.0+1.0j]',
<del> '[-1.-1.j]', '[-1.-1.j]', '[-1.0-1.0j]',
<del> '[-1.+infj]', '[-1.+infj]', '[-1.0+infj]',
<del> '[-1.-infj]', '[-1.-infj]', '[-1.0-infj]',
<del> '[-1.+nanj]', '[-1.+nanj]', '[-1.0+nanj]',
<del> '[ inf+0.j]', '[ inf+0.j]', '[ inf+0.0j]',
<del> '[ inf+1.j]', '[ inf+1.j]', '[ inf+1.0j]',
<del> '[ inf-1.j]', '[ inf-1.j]', '[ inf-1.0j]',
<del> '[ inf+infj]', '[ inf+infj]', '[ inf+infj]',
<del> '[ inf-infj]', '[ inf-infj]', '[ inf-infj]',
<del> '[ inf+nanj]', '[ inf+nanj]', '[ inf+nanj]',
<del> '[-inf+0.j]', '[-inf+0.j]', '[-inf+0.0j]',
<del> '[-inf+1.j]', '[-inf+1.j]', '[-inf+1.0j]',
<del> '[-inf-1.j]', '[-inf-1.j]', '[-inf-1.0j]',
<del> '[-inf+infj]', '[-inf+infj]', '[-inf+infj]',
<del> '[-inf-infj]', '[-inf-infj]', '[-inf-infj]',
<del> '[-inf+nanj]', '[-inf+nanj]', '[-inf+nanj]',
<del> '[ nan+0.j]', '[ nan+0.j]', '[ nan+0.0j]',
<del> '[ nan+1.j]', '[ nan+1.j]', '[ nan+1.0j]',
<del> '[ nan-1.j]', '[ nan-1.j]', '[ nan-1.0j]',
<del> '[ nan+infj]', '[ nan+infj]', '[ nan+infj]',
<del> '[ nan-infj]', '[ nan-infj]', '[ nan-infj]',
<add> '[ 0.+0.j]', '[ 0.+0.j]', '[ 0.0+0.0j]',
<add> '[ 0.+1.j]', '[ 0.+1.j]', '[ 0.0+1.0j]',
<add> '[ 0.-1.j]', '[ 0.-1.j]', '[ 0.0-1.0j]',
<add> '[ 0.+infj]', '[ 0.+infj]', '[ 0.0+infj]',
<add> '[ 0.-infj]', '[ 0.-infj]', '[ 0.0-infj]',
<add> '[ 0.+nanj]', '[ 0.+nanj]', '[ 0.0+nanj]',
<add> '[ 1.+0.j]', '[ 1.+0.j]', '[ 1.0+0.0j]',
<add> '[ 1.+1.j]', '[ 1.+1.j]', '[ 1.0+1.0j]',
<add> '[ 1.-1.j]', '[ 1.-1.j]', '[ 1.0-1.0j]',
<add> '[ 1.+infj]', '[ 1.+infj]', '[ 1.0+infj]',
<add> '[ 1.-infj]', '[ 1.-infj]', '[ 1.0-infj]',
<add> '[ 1.+nanj]', '[ 1.+nanj]', '[ 1.0+nanj]',
<add> '[-1.+0.j]', '[-1.+0.j]', '[-1.0+0.0j]',
<add> '[-1.+1.j]', '[-1.+1.j]', '[-1.0+1.0j]',
<add> '[-1.-1.j]', '[-1.-1.j]', '[-1.0-1.0j]',
<add> '[-1.+infj]', '[-1.+infj]', '[-1.0+infj]',
<add> '[-1.-infj]', '[-1.-infj]', '[-1.0-infj]',
<add> '[-1.+nanj]', '[-1.+nanj]', '[-1.0+nanj]',
<add> '[ inf+0.j]', '[ inf+0.j]', '[ inf+0.0j]',
<add> '[ inf+1.j]', '[ inf+1.j]', '[ inf+1.0j]',
<add> '[ inf-1.j]', '[ inf-1.j]', '[ inf-1.0j]',
<add> '[ inf+infj]', '[ inf+infj]', '[ inf+infj]',
<add> '[ inf-infj]', '[ inf-infj]', '[ inf-infj]',
<add> '[ inf+nanj]', '[ inf+nanj]', '[ inf+nanj]',
<add> '[-inf+0.j]', '[-inf+0.j]', '[-inf+0.0j]',
<add> '[-inf+1.j]', '[-inf+1.j]', '[-inf+1.0j]',
<add> '[-inf-1.j]', '[-inf-1.j]', '[-inf-1.0j]',
<add> '[-inf+infj]', '[-inf+infj]', '[-inf+infj]',
<add> '[-inf-infj]', '[-inf-infj]', '[-inf-infj]',
<add> '[-inf+nanj]', '[-inf+nanj]', '[-inf+nanj]',
<add> '[ nan+0.j]', '[ nan+0.j]', '[ nan+0.0j]',
<add> '[ nan+1.j]', '[ nan+1.j]', '[ nan+1.0j]',
<add> '[ nan-1.j]', '[ nan-1.j]', '[ nan-1.0j]',
<add> '[ nan+infj]', '[ nan+infj]', '[ nan+infj]',
<add> '[ nan-infj]', '[ nan-infj]', '[ nan-infj]',
<ide> '[ nan+nanj]', '[ nan+nanj]', '[ nan+nanj]']
<ide>
<ide> for res, val in zip(actual, wanted):
<ide> assert_(res == val)
<del>
<add>
<add>def test_array2string():
<add> """Basic test of array2string."""
<add> a = np.arange(3)
<add> assert_(np.array2string(a) == '[0 1 2]')
<add> assert_(np.array2string(a, max_line_width=4) == '[0 1\n 2]')
<add> stylestr = np.array2string(np.array(1.5),
<add> style=lambda x: "Value in 0-D array: " + str(x))
<add> assert_(stylestr == 'Value in 0-D array: 1.5')
<add>
<add>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 1 |
PHP | PHP | fix coding standards | 454c087050d0482628168bcfd4b78a3e0fa835f0 | <ide><path>tests/test_app/Plugin/TestPlugin/Test/Fixture/ArticleFixture.php
<ide> *
<ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> * @link http://cakephp.org CakePHP(tm) Project
<del> * @since 2.0.0
<add> * @since 3.0.0
<ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<ide> */
<ide> namespace TestPlugin\Test\Fixture;
<ide> * Plugin article fixture.
<ide> */
<ide> class ArticleFixture extends TestFixture {
<add>
<ide> /**
<ide> * fields property
<ide> *
<ide> * @var array
<ide> */
<del> public $fields = array(
<add> public $fields = [
<ide> 'id' => ['type' => 'integer'],
<ide> 'author_id' => ['type' => 'integer', 'null' => true],
<ide> 'title' => ['type' => 'string', 'null' => true],
<ide> 'body' => 'text',
<ide> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
<del> );
<add> ];
<ide>
<ide> /**
<ide> * records property | 1 |
Python | Python | add weight loading to prelu, parametricsoftplus | a478930d25543f9f2de7cd76c3c051df08b78475 | <ide><path>keras/layers/advanced_activations.py
<add>from .. import initializations
<ide> from ..layers.core import Layer, MaskedLayer
<ide> from ..utils.theano_utils import shared_zeros, shared_ones, sharedX
<ide> import theano.tensor as T
<ide> class PReLU(MaskedLayer):
<ide> Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
<ide> http://arxiv.org/pdf/1502.01852v1.pdf
<ide> '''
<del> def __init__(self, input_shape):
<add> def __init__(self, input_shape, init='zero', weights=None):
<ide> super(PReLU, self).__init__()
<del> self.alphas = shared_zeros(input_shape)
<add> self.init = initializations.get(init)
<add> self.alphas = self.init(input_shape)
<ide> self.params = [self.alphas]
<ide> self.input_shape = input_shape
<ide>
<add> if weights is not None:
<add> self.set_weights(weights)
<add>
<ide> def get_output(self, train):
<ide> X = self.get_input(train)
<ide> pos = ((X + abs(X)) / 2.0)
<ide> def get_output(self, train):
<ide>
<ide> def get_config(self):
<ide> return {"name": self.__class__.__name__,
<del> "input_shape": self.input_shape}
<add> "input_shape": self.input_shape,
<add> "init": self.init.__name__}
<ide>
<ide>
<ide> class ParametricSoftplus(MaskedLayer):
<ide> class ParametricSoftplus(MaskedLayer):
<ide> Inferring Nonlinear Neuronal Computation Based on Physiologically Plausible Inputs
<ide> http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003143
<ide> '''
<del> def __init__(self, input_shape, alpha_init=0.2, beta_init=5.0):
<add> def __init__(self, input_shape, alpha_init=0.2, beta_init=5.0, weights=None):
<ide>
<ide> super(ParametricSoftplus, self).__init__()
<ide> self.alpha_init = alpha_init
<ide> def __init__(self, input_shape, alpha_init=0.2, beta_init=5.0):
<ide> self.params = [self.alphas, self.betas]
<ide> self.input_shape = input_shape
<ide>
<add> if weights is not None:
<add> self.set_weights(weights)
<add>
<ide> def get_output(self, train):
<ide> X = self.get_input(train)
<ide> return T.nnet.softplus(self.betas * X) * self.alphas | 1 |
Python | Python | use comprehensions instead of map/lambda (take 2) | 9e904d6204569665895439ccbf7e6fa09f537ee1 | <ide><path>glances/plugins/glances_ip.py
<ide> def ip_to_cidr(ip):
<ide>
<ide> Example: '255.255.255.0' will return 24
<ide> """
<del> return sum(map(lambda x: int(x) << 8, ip.split('.'))) // 8128
<add> return sum([int(x) << 8 for x in ip.split('.')]) // 8128 | 1 |
Text | Text | add scorer to textcat api docs config settings | d0578c2ede80890ed610573c95f11ad30b2f8cd2 | <ide><path>website/docs/api/textcategorizer.md
<ide> architectures and their arguments and hyperparameters.
<ide> | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<ide> | `threshold` | Cutoff to consider a prediction "positive", relevant when printing accuracy results. ~~float~~ |
<ide> | `model` | A model instance that predicts scores for each category. Defaults to [TextCatEnsemble](/api/architectures#TextCatEnsemble). ~~Model[List[Doc], List[Floats2d]]~~ |
<add>| `scorer` | The scoring method. Defaults to [`Scorer.score_cats`](/api/scorer#score_cats) for the attribute `"cats"`. ~~Optional[Callable]~~ |
<ide>
<ide> ```python
<ide> %%GITHUB_SPACY/spacy/pipeline/textcat.py | 1 |
Javascript | Javascript | remove forcedomain so we can test beta website | af75452db5a11dcdfe53065e1d106306cf1f5b57 | <ide><path>server/server.js
<ide> app.set('port', process.env.PORT || 3000);
<ide> app.set('views', path.join(__dirname, 'views'));
<ide> app.set('view engine', 'jade');
<ide>
<del>if (process.env.NODE_ENV === 'production') {
<del> app.use(forceDomain({
<del> hostname: 'www.freecodecamp.com'
<del> }));
<del>}
<add>//if (process.env.NODE_ENV === 'production') {
<add>// app.use(forceDomain({
<add>// hostname: 'www.freecodecamp.com'
<add>// }));
<add>//}
<ide>
<ide> app.use(compress());
<ide> app.use(lessMiddleware(path.join(__dirname, '/public'))); | 1 |
Java | Java | remove stray println | c90e51b29f126c4a363510aff3a922be1c2f7907 | <ide><path>rxjava-core/src/main/java/rx/operators/OperatorGroupBy.java
<ide> public void onNext(T t) {
<ide>
<ide> private void completeInner() {
<ide> if (completionCounter.decrementAndGet() == 0 && (completed.get() || childObserver.isUnsubscribed())) {
<del> System.out.println("groupBy INNER completed");
<ide> if (childObserver.isUnsubscribed()) {
<ide> // if the entire groupBy has been unsubscribed and children are completed we will propagate the unsubscribe up.
<ide> unsubscribe(); | 1 |
PHP | PHP | avoid array_key_exists() check on objects | a7e6ca3e10cb169d100aefd71bfe0de25279b55d | <ide><path>src/Utility/Hash.php
<ide> protected static function _matches($data, $selector)
<ide> return false;
<ide> }
<ide>
<add> if (is_array($data)) {
<add> $attrPresent = array_key_exists($attr, $data);
<add> } else {
<add> $attrPresent = $data->offsetExists($attr);
<add> }
<ide> // Empty attribute = fail.
<del> if (!(isset($data[$attr]) || array_key_exists($attr, $data))) {
<add> if (!$attrPresent) {
<ide> return false;
<ide> }
<ide> | 1 |
PHP | PHP | fix input submit via magic input method | c126e61362f089d89950d671320a46c5312f246f | <ide><path>src/View/Helper/FormHelper.php
<ide> public function input($fieldName, array $options = [])
<ide>
<ide> $label = $options['label'];
<ide> unset($options['label']);
<add>
<ide> $nestedInput = false;
<ide> if ($options['type'] === 'checkbox') {
<ide> $nestedInput = true;
<ide> public function input($fieldName, array $options = [])
<ide> }
<ide>
<ide> $input = $this->_getInput($fieldName, $options);
<del> if ($options['type'] === 'hidden') {
<add> if ($options['type'] === 'hidden' || $options['type'] === 'submit') {
<ide> if ($newTemplates) {
<ide> $templater->pop();
<ide> }
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testInputMagicSelectChangeToRadio()
<ide> $this->assertContains('input type="radio"', $result);
<ide> }
<ide>
<add> /**
<add> * testFormInputSubmit method
<add> *
<add> * test correct results for form::input() and type submit.
<add> *
<add> * @return void
<add> */
<add> public function testFormInputSubmit()
<add> {
<add> $result = $this->Form->input('Test Submit', ['type' => 'submit', 'class' => 'foobar']);
<add> $expected = [
<add> 'div' => ['class' => 'submit'],
<add> 'input' => ['type' => 'submit', 'class' => 'foobar', 'id' => 'test-submit', 'value' => 'Test Submit'],
<add> '/div'
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<add>
<ide> /**
<ide> * testFormInputs method
<ide> * | 2 |
Text | Text | update changelog release date for 18.2.0 | 89bae8f371eb2cf49dbe310ec7f04d0e52e32f98 | <ide><path>CHANGELOG.md
<del>## 18.2.0 (TODO)
<add>## 18.2.0 (June 14, 2022)
<ide>
<ide> ### React DOM
<ide> | 1 |
Text | Text | fix chromium document link in pull-requests.md | 218664f638a91e331b800b2d49eca55a65899a50 | <ide><path>doc/contributing/pull-requests.md
<ide> There are a number of more advanced mechanisms for managing commits using
<ide> Feel free to post a comment in the pull request to ping reviewers if you are
<ide> awaiting an answer on something. If you encounter words or acronyms that
<ide> seem unfamiliar, refer to this
<del>[glossary](https://sites.google.com/a/chromium.org/dev/glossary).
<add>[glossary](https://chromium.googlesource.com/chromiumos/docs/+/HEAD/glossary.md).
<ide>
<ide> #### Approval and request changes workflow
<ide> | 1 |
Text | Text | fix shinny -> shiny typo | bd061b8df64b3015dc69b86a5c1de10ff37265cc | <ide><path>project/ISSUE-TRIAGE.md
<ide> An issue can have multiple of the following labels.
<ide> | kind/bug | Bugs are bugs. The cause may or may not be known at triage time so debugging should be taken account into the time estimate. |
<ide> | kind/docs | Writing documentation, man pages, articles, blogs, or other significant word-driven task. |
<ide> | kind/enhancement | Enhancement are not bugs or new features but can drastically improve usability or performance of a project component. |
<del>| kind/feature | Functionality or other elements that the project does not currently support. Features are new and shinny. |
<add>| kind/feature | Functionality or other elements that the project does not currently support. Features are new and shiny. |
<ide> | kind/question | Contains a user or contributor question requiring a response. |
<ide>
<ide> #### Functional area | 1 |
Python | Python | add verbose flag. | 0249c26bc00cc985f1d13b076d6bf3f9bac8a8ee | <ide><path>keras/callbacks.py
<ide> class LearningRateScheduler(Callback):
<ide> schedule: a function that takes an epoch index as input
<ide> (integer, indexed from 0) and returns a new
<ide> learning rate as output (float).
<add> verbose: int. 0: quiet, 1: update messages.
<ide> """
<ide>
<del> def __init__(self, schedule):
<add> def __init__(self, schedule, verbose=0):
<ide> super(LearningRateScheduler, self).__init__()
<ide> self.schedule = schedule
<add> self.verbose = verbose
<ide>
<ide> def on_epoch_begin(self, epoch, logs=None):
<ide> if not hasattr(self.model.optimizer, 'lr'):
<ide> def on_epoch_begin(self, epoch, logs=None):
<ide> if not isinstance(lr, (float, np.float32, np.float64)):
<ide> raise ValueError('The output of the "schedule" function '
<ide> 'should be float.')
<del> K.set_value(self.model.optimizer.lr, lr)
<add> if self.verbose > 0:
<add> print('\nEpoch %05d: LearningRateScheduler reducing learning '
<add> 'rate to %s.' % (epoch + 1, lr))
<ide>
<ide>
<ide> class TensorBoard(Callback): | 1 |
Ruby | Ruby | remove wrong test | 62671b1703c8fb8fd17d5548ff2f21df43678fd7 | <ide><path>Library/Homebrew/test/rubocops/lines_spec.rb
<ide> class Foo < Formula
<ide> RUBY
<ide> end
<ide>
<del> it "Using ARGV to check options" do
<del> expect_no_offenses(<<~RUBY)
<del> class Foo < Formula
<del> desc "foo"
<del> url 'https://brew.sh/foo-1.0.tgz'
<del> def install
<del> verbose = Homebrew.args.verbose?
<del> end
<del> end
<del> RUBY
<del> end
<del>
<ide> it 'man+"man8" usage' do
<ide> expect_offense(<<~RUBY)
<ide> class Foo < Formula | 1 |
Ruby | Ruby | define attribute methods in a thread safe manner | b670d799e4f7c1ddc235fbeec1ca1806a8b5d6ff | <ide><path>activerecord/lib/active_record/attribute_methods.rb
<ide> def define_attribute_methods # :nodoc:
<ide> # Use a mutex; we don't want two thread simultaneously trying to define
<ide> # attribute methods.
<ide> generated_attribute_methods.synchronize do
<del> return if attribute_methods_generated?
<add> return false if attribute_methods_generated?
<ide> superclass.define_attribute_methods unless self == base_class
<ide> super(column_names)
<ide> @attribute_methods_generated = true
<ide> end
<add> true
<ide> end
<ide>
<ide> def attribute_methods_generated? # :nodoc:
<ide> def attribute_names
<ide> # If we haven't generated any methods yet, generate them, then
<ide> # see if we've created the method we're looking for.
<ide> def method_missing(method, *args, &block) # :nodoc:
<del> unless self.class.attribute_methods_generated?
<del> self.class.define_attribute_methods
<del>
<add> if self.class.define_attribute_methods
<ide> if respond_to_without_attributes?(method)
<ide> send(method, *args, &block)
<ide> else
<ide> def attribute_missing(match, *args, &block) # :nodoc:
<ide> # person.respond_to(:nothing) # => false
<ide> def respond_to?(name, include_private = false)
<ide> name = name.to_s
<del> self.class.define_attribute_methods unless self.class.attribute_methods_generated?
<add> self.class.define_attribute_methods
<ide> result = super
<ide>
<ide> # If the result is false the answer is false. | 1 |
Javascript | Javascript | convert spec to use async/await | 9fa32c7c22b2aa8443205a262867a16a1e5c2d98 | <ide><path>spec/project-spec.js
<ide> describe('Project', () => {
<ide> });
<ide> };
<ide>
<del> it('reports filesystem changes within project paths', () => {
<add> it('reports filesystem changes within project paths', async () => {
<ide> jasmine.useRealClock();
<ide> const dirOne = temp.mkdirSync('atom-spec-project-one');
<ide> const fileOne = path.join(dirOne, 'file-one.txt');
<ide> describe('Project', () => {
<ide> const fileThree = path.join(dirTwo, 'file-three.txt');
<ide>
<ide> // Ensure that all preexisting watchers are stopped
<del> waitsForPromise(() => stopAllWatchers());
<del>
<del> runs(() => atom.project.setPaths([dirOne]));
<del> waitsForPromise(() => atom.project.getWatcherPromise(dirOne));
<del>
<del> runs(() => {
<del> expect(atom.project.watcherPromisesByPath[dirTwo]).toEqual(undefined);
<add> await stopAllWatchers();
<ide>
<del> fs.writeFileSync(fileThree, 'three\n');
<del> fs.writeFileSync(fileTwo, 'two\n');
<del> fs.writeFileSync(fileOne, 'one\n');
<del> });
<del>
<del> waitsForPromise(() => waitForEvents([fileOne, fileTwo]));
<add> atom.project.setPaths([dirOne]);
<add> await atom.project.getWatcherPromise(dirOne);
<ide>
<del> runs(() =>
<del> expect(events.some(event => event.path === fileThree)).toBeFalsy()
<del> );
<add> expect(atom.project.watcherPromisesByPath[dirTwo]).toEqual(undefined);
<add> fs.writeFileSync(fileThree, 'three\n');
<add> fs.writeFileSync(fileTwo, 'two\n');
<add> fs.writeFileSync(fileOne, 'one\n');
<add> await waitForEvents([fileOne, fileTwo]);
<add> expect(events.some(event => event.path === fileThree)).toBeFalsy()
<ide> });
<ide> });
<ide> | 1 |
Ruby | Ruby | avoid more dynamic symbols | 81d10b9add4283a6740f6682e4579d15c5475e6c | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def symbol_unscoping(scope)
<ide> end
<ide>
<ide> single_val_method = Relation::SINGLE_VALUE_METHODS.include?(scope)
<del> unscope_code = :"#{scope}_value#{'s' unless single_val_method}="
<add> unscope_code = "#{scope}_value#{'s' unless single_val_method}="
<ide>
<ide> case scope
<ide> when :order | 1 |
Javascript | Javascript | fix word async -> concurrent | fbbbea16e11e849d2a75e0b0d66e38266783a01c | <ide><path>packages/react-dom/src/events/__tests__/SimpleEventPlugin-test.internal.js
<ide> describe('SimpleEventPlugin', function() {
<ide> expect(button.textContent).toEqual('Count: 3');
<ide> });
<ide>
<del> describe('interactive events, in async mode', () => {
<add> describe('interactive events, in concurrent mode', () => {
<ide> beforeEach(() => {
<ide> jest.resetModules();
<ide> ReactFeatureFlags = require('shared/ReactFeatureFlags'); | 1 |
Text | Text | add a note about react/react-native versioning | 7c82cc3095e7593379dc66cb046ae215b0635602 | <ide><path>Libraries/Renderer/README.md
<add># React & React Native Versions
<add>
<add>This page describes how React and React Native versions interact each other.
<add>The version alignment between the two frameworks relies on two syncronization points:
<add>
<add>1. The versions in the `package.json` of the new app template. For example [for React Native 0.68.1](https://github.com/facebook/react-native/blob/0.68-stable/template/package.json#L12-L15) the versions are aligned as follows:
<add>
<add>```
<add> "dependencies": {
<add> "react": "17.0.2",
<add> "react-native": "0.68.1"
<add> },
<add>```
<add>
<add>1. The React renderers **shipped** with React Native inside this folder, the [./Libraries/Renderer](https://github.com/facebook/react-native/tree/main/Libraries/Renderer) folder, of React Native.
<add>
<add>This practically means that you **can't bump** the version of React in your `package.json` to a later version,
<add>as you will still be using the older renderer from the folder mentioned above. Bumping the react version in your `package.json` will lead to unexpected behaviors.
<add>
<add>For the sake of React 18, the first version of React Native compatible with React 18 is **0.69.0**. Users on React Native 0.68.0 and previous versions won't be able to use React 18.
<add>
<add>If you use the `react-native upgrade` command or the React Native Upgrade Helper, you'll bump to the correct React version once you upgrade React Native. | 1 |
Javascript | Javascript | switch octal format | 15facf0ae1d3b1a750ef02370384f17acb499dcb | <ide><path>flyfile.js
<ide> export async function compile(fly) {
<ide> }
<ide>
<ide> export async function bin(fly, opts) {
<del> await fly.source(opts.src || 'bin/*').babel().target('dist/bin', {mode: 0o755})
<add> await fly.source(opts.src || 'bin/*').babel().target('dist/bin', {mode: 0755})
<ide> notify('Compiled binaries')
<ide> }
<ide> | 1 |
PHP | PHP | fix casing of error category | f0ff8c4cab00da3132f34b2fa07b99b641f28a9e | <ide><path>src/Error/Renderer/HtmlRenderer.php
<ide> public function render(PhpError $error): string
<ide> debug($error);
<ide> $errorMessage = sprintf(
<ide> '<b>%s</b> (%s)',
<del> h($error->getLabel()),
<add> h(ucfirst($error->getLabel())),
<ide> h($error->getCode())
<ide> );
<ide> $toggle = $this->renderToggle($errorMessage, $id, 'trace'); | 1 |
Ruby | Ruby | check openssl and openssl@1.1 | fbeeae96eff0c02fd51b21d2671f76656ce5783c | <ide><path>Library/Homebrew/rubocops/text.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> problem "Please set plist_options when using a formula-defined plist."
<ide> end
<ide>
<del> if depends_on?("openssl") && depends_on?("libressl")
<add> if (depends_on?("openssl") || depends_on?("openssl@1.1")) && depends_on?("libressl")
<ide> problem "Formulae should not depend on both OpenSSL and LibreSSL (even optionally)."
<ide> end
<ide> | 1 |
Javascript | Javascript | fix minlang task | 71ae9647e2fd7b62337c20c99529aad003ce3050 | <ide><path>Gruntfile.js
<ide> module.exports = function (grunt) {
<ide> 'min/moment.min.js' : ['moment.js']
<ide> };
<ide>
<add> var minLangs = {
<add> langs: {
<add> src: ['min/langs.js'],
<add> dest: 'min/langs.min.js'
<add> }
<add> };
<add>
<ide> // all the lang files need to be added manually
<ide> fs.readdirSync('./lang').forEach(function (path) {
<ide> if (path.indexOf('.js') > -1) {
<ide> var dest = 'min/lang/' + path,
<ide> src = ['lang/' + path];
<add>
<ide> minifiedFiles[dest] = src;
<add> minLangs[path] = {src:src, dest:dest};
<ide> }
<ide> });
<ide>
<ide> module.exports = function (grunt) {
<ide> dest: 'min/langs.js'
<ide> }
<ide> },
<add> minlang : minLangs,
<ide> uglify : {
<ide> my_target: {
<ide> files: minifiedFiles
<ide> },
<ide> options: {
<del> mangle: true,
<add> mangle: {
<add> toplevel: true
<add> },
<ide> squeeze: {
<ide> dead_code: false
<ide> },
<ide><path>tasks/minify-lang.js
<ide> var fs = require('fs'),
<ide>
<ide> module.exports = function (grunt) {
<ide>
<add> var helpers = require('grunt-lib-legacyhelpers').init(grunt);
<add>
<ide> var START = [
<ide> "(function(){",
<ide> " function onload (moment) {",
<ide> module.exports = function (grunt) {
<ide> // UglifyJS does not support keeping the first line comments unless using the CLI.
<ide> // This multi-task ensures that the first comments are kept.
<ide> grunt.registerMultiTask('minlang', 'Minify lang files with UglifyJS.', function () {
<del> var files = grunt.file.expandFiles(this.file.src),
<add> var files = grunt.file.expand(this.data.src),
<ide> min,
<ide> code,
<ide> comments,
<ide> tok;
<ide>
<ide> // Concat specified files. This should really be a single, pre-built (and
<ide> // linted) file, but it supports any number of files.
<del> code = grunt.helper('concat', files, {separator: this.data.separator});
<add> code = helpers.concat(files, {separator: this.data.separator});
<ide>
<ide> // Add the first comments
<ide> tok = uglifyjs.parser.tokenizer(code);
<ide> min = showCopyright(tok().comments_before);
<ide>
<ide> // Add the minified source.
<del> min += grunt.helper('uglify', wrapFile(code), grunt.config('uglify'));
<del> grunt.file.write(this.file.dest, min);
<add> min += uglifyjs(wrapFile(code), grunt.config('uglify'));
<add> grunt.file.write(this.data.dest, min);
<ide>
<ide> // Fail task if errors were logged.
<ide> if (this.errorCount) { return false; }
<ide>
<ide> // Otherwise, print a success message....
<del> grunt.log.writeln('File "' + this.file.dest + '" created.');
<add> grunt.log.writeln('File "' + this.data.dest + '" created.');
<ide>
<ide> // ...and report some size information.
<del> grunt.helper('min_max_info', min, code);
<add> helpers.min_max_info(min, code);
<ide> });
<ide>
<ide> // Helper for the 'mincomment' multitask | 2 |
Javascript | Javascript | allow invalidation after first watch run | 94bd3bc6f98594c1ff8d8efbd10d0551c352ee25 | <ide><path>lib/MultiCompiler.js
<ide> module.exports = class MultiCompiler {
<ide> node.compiler,
<ide> i,
<ide> nodeDone.bind(null, node),
<del> () => node.state !== "running",
<add> () => node.state !== "done" && node.state !== "running",
<ide> () => nodeChange(node),
<ide> () => nodeInvalid(node)
<ide> )
<ide><path>test/MultiCompiler.test.js
<ide> describe("MultiCompiler", function () {
<ide> }
<ide> });
<ide> });
<add>
<add> it("shouldn't hang when invalidating watchers", done => {
<add> const entriesA = { a: "./a.js" };
<add> const entriesB = { b: "./b.js" };
<add> const compiler = webpack([
<add> {
<add> name: "a",
<add> mode: "development",
<add> entry: () => entriesA,
<add> context: path.join(__dirname, "fixtures")
<add> },
<add> {
<add> name: "b",
<add> mode: "development",
<add> entry: () => entriesB,
<add> context: path.join(__dirname, "fixtures")
<add> }
<add> ]);
<add>
<add> compiler.watchFileSystem = { watch() {} };
<add> compiler.outputFileSystem = createFsFromVolume(new Volume());
<add>
<add> const watching = compiler.watch({}, error => {
<add> if (error) {
<add> done(error);
<add> return;
<add> }
<add>
<add> entriesA.b = "./b.js";
<add> entriesB.a = "./a.js";
<add>
<add> watching.invalidate(done);
<add> });
<add> }, 2000);
<add>
<ide> it("shouldn't hang when invalidating during build", done => {
<ide> const compiler = webpack(
<ide> Object.assign([ | 2 |
Python | Python | use context manager. get latest download_json | 41aace5f84c3d2eb7f54e61429e594c7e167526a | <ide><path>contrib/scrape-ec2-prices.py
<ide> import os
<ide> import re
<ide> import json
<add>import atexit
<ide> import copy
<ide> import time
<ide> from collections import defaultdict, OrderedDict
<ide> PRICING_FILE_PATH = os.path.join(BASE_PATH, "../libcloud/data/pricing.json")
<ide> PRICING_FILE_PATH = os.path.abspath(PRICING_FILE_PATH)
<ide>
<del>TEMPFILE = os.environ.get("TMP_JSON", "/tmp/ec.json")
<add>FILEPATH = os.environ.get("TMP_JSON", "/tmp/ec.json")
<ide>
<ide> INSTANCE_SIZES = [
<ide> "micro",
<ide>
<ide>
<ide> def download_json():
<del> response = requests.get(URL, stream=True)
<del> try:
<del> return open(TEMPFILE, "r")
<del> except IOError:
<del> with open(TEMPFILE, "wb") as fo:
<del> for chunk in response.iter_content(chunk_size=2**20):
<del> if chunk:
<del> fo.write(chunk)
<del> return open(TEMPFILE, "r")
<add> if os.path.isfile(FILEPATH):
<add> print("Using data from existing cached file %s" % (FILEPATH))
<add> return open(FILEPATH, "r")
<add>
<add> def remove_partial_cached_file():
<add> if os.path.isfile(FILEPATH):
<add> os.remove(FILEPATH)
<add>
<add> # File not cached locally, download data and cache it
<add> with requests.get(URL, stream=True) as response:
<add> atexit.register(remove_partial_cached_file)
<add>
<add> total_size_in_bytes = int(response.headers.get("content-length", 0))
<add> progress_bar = tqdm.tqdm(total=total_size_in_bytes, unit="iB", unit_scale=True)
<add>
<add> chunk_size = 10 * 1024 * 1024
<add>
<add> with open(FILEPATH, "wb") as fp:
<add> # NOTE: We use shutil.copyfileobj with large chunk size instead of
<add> # response.iter_content with large chunk size since data we
<add> # download is massive and copyfileobj is more efficient.
<add> # shutil.copyfileobj(response.raw, fp, 10 * 1024 * 1024)
<add> for chunk_data in response.iter_content(chunk_size):
<add> progress_bar.update(len(chunk_data))
<add> fp.write(chunk_data)
<add>
<add> progress_bar.close()
<add> atexit.unregister(remove_partial_cached_file)
<add>
<add> return FILEPATH, False
<ide>
<ide>
<ide> def get_json():
<del> try:
<del> return open(TEMPFILE, "r")
<del> except IOError:
<del> return download_json()
<add> if not os.path.isfile(FILEPATH):
<add> return download_json(), False
<add>
<add> print("Using data from existing cached file %s" % (FILEPATH))
<add> return FILEPATH, True
<ide>
<ide>
<ide> # Prices and sizes are in different dicts and categorized by sku
<ide> def get_all_prices():
<ide> current_sku = ""
<ide> current_rate_code = ""
<ide> amazonEC2_offer_code = "JRTCKXETXF"
<del> json_file = get_json()
<del> parser = ijson.parse(json_file)
<del> # use parser because file is very large
<del> for prefix, event, value in parser:
<del> if "products" in prefix:
<del> continue
<del> if (prefix, event) == ("terms.OnDemand", "map_key"):
<del> current_sku = value
<del> prices[current_sku] = {}
<del> elif (prefix, event) == (
<del> f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions",
<del> "map_key",
<del> ):
<del> current_rate_code = value
<del> elif (prefix, event) == (
<del> f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions"
<del> f".{current_rate_code}.unit",
<del> "string",
<del> ):
<del> prices[current_sku]["unit"] = value
<del> elif (prefix, event) == (
<del> f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions"
<del> f".{current_rate_code}.pricePerUnit.USD",
<del> "string",
<del> ):
<del> prices[current_sku]["price"] = value
<add> json_file, from_file = get_json()
<add> with open(json_file, 'r') as f:
<add> parser = ijson.parse(f)
<add> # use parser because file is very large
<add> for prefix, event, value in parser:
<add> if "products" in prefix:
<add> continue
<add> if (prefix, event) == ("terms.OnDemand", "map_key"):
<add> current_sku = value
<add> prices[current_sku] = {}
<add> elif (prefix, event) == (
<add> f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions",
<add> "map_key",
<add> ):
<add> current_rate_code = value
<add> elif (prefix, event) == (
<add> f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions"
<add> f".{current_rate_code}.unit",
<add> "string",
<add> ):
<add> prices[current_sku]["unit"] = value
<add> elif (prefix, event) == (
<add> f"terms.OnDemand.{current_sku}.{current_sku}.{amazonEC2_offer_code}.priceDimensions"
<add> f".{current_rate_code}.pricePerUnit.USD",
<add> "string",
<add> ):
<add> prices[current_sku]["price"] = value
<ide> return prices
<ide>
<ide>
<ide> def get_all_prices():
<ide> def scrape_ec2_pricing():
<ide> skus = {}
<ide> prices = get_all_prices()
<del> json_file = get_json()
<del> parser = ijson.parse(json_file)
<del> current_sku = ""
<del>
<del> for prefix, event, value in parser:
<del> if "terms" in prefix:
<del> break
<del> if (prefix, event) == ("products", "map_key"):
<del> current_sku = value
<del> skus[current_sku] = {'sku': value}
<del> elif (prefix, event) == (f'products.{current_sku}.productFamily', 'string'):
<del> skus[current_sku]['family'] = value
<del> elif (prefix, event) == (f'products.{current_sku}.attributes.location', 'string'):
<del> skus[current_sku]['locationName'] = value
<del> elif (prefix, event) == (f'products.{current_sku}.attributes.locationType', 'string'):
<del> skus[current_sku]['locationType'] = value
<del> elif (prefix, event) == (f'products.{current_sku}.attributes.instanceType', 'string'):
<del> skus[current_sku]['size'] = value
<del> elif (prefix, event) == (f'products.{current_sku}.attributes.operatingSystem', 'string'):
<del> skus[current_sku]['os'] = value
<del> elif (prefix, event) == (f'products.{current_sku}.attributes.usagetype', 'string'):
<del> skus[current_sku]['usage_type'] = value
<del> elif (prefix, event) == (f'products.{current_sku}.attributes.preInstalledSw', 'string'):
<del> skus[current_sku]['preInstalledSw'] = value
<del> elif (prefix, event) == (f'products.{current_sku}.attributes.regionCode', 'string'):
<del> skus[current_sku]['location'] = value
<del> # only get prices of compute instances atm
<del> elif (prefix, event) == (f"products.{current_sku}", "end_map"):
<del> if (
<del> "Compute Instance" not in skus[current_sku]["family"]
<del> and "Dedicated Host" not in skus[current_sku]["family"]
<del> ):
<del> del skus[current_sku]
<add> json_file, from_file = get_json()
<add> with open(json_file, 'r') as f:
<add> parser = ijson.parse(f)
<add> current_sku = ""
<add>
<add> for prefix, event, value in parser:
<add> if "terms" in prefix:
<add> break
<add> if (prefix, event) == ("products", "map_key"):
<add> current_sku = value
<add> skus[current_sku] = {'sku': value}
<add> elif (prefix, event) == (f'products.{current_sku}.productFamily', 'string'):
<add> skus[current_sku]['family'] = value
<add> elif (prefix, event) == (f'products.{current_sku}.attributes.location', 'string'):
<add> skus[current_sku]['locationName'] = value
<add> elif (prefix, event) == (f'products.{current_sku}.attributes.locationType', 'string'):
<add> skus[current_sku]['locationType'] = value
<add> elif (prefix, event) == (f'products.{current_sku}.attributes.instanceType', 'string'):
<add> skus[current_sku]['size'] = value
<add> elif (prefix, event) == (f'products.{current_sku}.attributes.operatingSystem', 'string'):
<add> skus[current_sku]['os'] = value
<add> elif (prefix, event) == (f'products.{current_sku}.attributes.usagetype', 'string'):
<add> skus[current_sku]['usage_type'] = value
<add> elif (prefix, event) == (f'products.{current_sku}.attributes.preInstalledSw', 'string'):
<add> skus[current_sku]['preInstalledSw'] = value
<add> elif (prefix, event) == (f'products.{current_sku}.attributes.regionCode', 'string'):
<add> skus[current_sku]['location'] = value
<add> # only get prices of compute instances atm
<add> elif (prefix, event) == (f"products.{current_sku}", "end_map"):
<add> if (
<add> "Compute Instance" not in skus[current_sku]["family"]
<add> and "Dedicated Host" not in skus[current_sku]["family"]
<add> ):
<add> del skus[current_sku]
<ide> ec2_linux = defaultdict(OrderedDict)
<ide> ec2_windows = defaultdict(OrderedDict)
<ide> ec2_rhel = defaultdict(OrderedDict) | 1 |
Python | Python | fix yaml parser bug | 9277f438cb85e8205cfe0149142d2f2b4d11a31c | <ide><path>djangorestframework/parsers.py
<ide> def parse(self, stream):
<ide> {'detail': 'JSON parse error - %s' % unicode(exc)})
<ide>
<ide>
<del>if yaml:
<del> class YAMLParser(BaseParser):
<del> """
<del> Parses YAML-serialized data.
<del> """
<add>class YAMLParser(BaseParser):
<add> """
<add> Parses YAML-serialized data.
<add> """
<ide>
<del> media_type = 'application/yaml'
<add> media_type = 'application/yaml'
<ide>
<del> def parse(self, stream):
<del> """
<del> Returns a 2-tuple of `(data, files)`.
<add> def parse(self, stream):
<add> """
<add> Returns a 2-tuple of `(data, files)`.
<ide>
<del> `data` will be an object which is the parsed content of the response.
<del> `files` will always be `None`.
<del> """
<del> try:
<del> return (yaml.safe_load(stream), None)
<del> except ValueError, exc:
<del> raise ErrorResponse(status.HTTP_400_BAD_REQUEST,
<del> {'detail': 'YAML parse error - %s' % unicode(exc)})
<del>else:
<del> YAMLParser = None
<add> `data` will be an object which is the parsed content of the response.
<add> `files` will always be `None`.
<add> """
<add> try:
<add> return (yaml.safe_load(stream), None)
<add> except (ValueError, yaml.parser.ParserError), exc:
<add> content = {'detail': 'YAML parse error - %s' % unicode(exc)}
<add> raise ErrorResponse(status.HTTP_400_BAD_REQUEST, content)
<ide>
<ide>
<ide> class PlainTextParser(BaseParser):
<ide> def _type_convert(self, value):
<ide> XMLParser
<ide> )
<ide>
<del>if YAMLParser:
<del> DEFAULT_PARSERS += (YAMLParser,)
<add>if yaml:
<add> DEFAULT_PARSERS += (YAMLParser, )
<add>else:
<add> YAMLParser = None
<add>
<ide><path>djangorestframework/renderers.py
<ide> def render(self, obj=None, media_type=None):
<ide> return dict2xml(obj)
<ide>
<ide>
<del>if yaml:
<del> class YAMLRenderer(BaseRenderer):
<del> """
<del> Renderer which serializes to YAML.
<del> """
<add>class YAMLRenderer(BaseRenderer):
<add> """
<add> Renderer which serializes to YAML.
<add> """
<ide>
<del> media_type = 'application/yaml'
<del> format = 'yaml'
<add> media_type = 'application/yaml'
<add> format = 'yaml'
<ide>
<del> def render(self, obj=None, media_type=None):
<del> """
<del> Renders *obj* into serialized YAML.
<del> """
<del> if obj is None:
<del> return ''
<add> def render(self, obj=None, media_type=None):
<add> """
<add> Renders *obj* into serialized YAML.
<add> """
<add> if obj is None:
<add> return ''
<ide>
<del> return yaml.safe_dump(obj)
<del>else:
<del> YAMLRenderer = None
<add> return yaml.safe_dump(obj)
<ide>
<ide>
<ide> class TemplateRenderer(BaseRenderer):
<ide> class DocumentingPlainTextRenderer(DocumentingTemplateRenderer):
<ide> XMLRenderer
<ide> )
<ide>
<del>if YAMLRenderer:
<del> DEFAULT_RENDERERS += (YAMLRenderer,)
<add>if yaml:
<add> DEFAULT_RENDERERS += (YAMLRenderer, )
<add>else:
<add> YAMLRenderer = None | 2 |
Python | Python | use filelock to ensure distributed barriers | c547f15a1741cadfca96225e042007484d373191 | <ide><path>examples/language-modeling/run_language_modeling.py
<ide> class DataTrainingArguments:
<ide> def get_dataset(args: DataTrainingArguments, tokenizer: PreTrainedTokenizer, evaluate=False, local_rank=-1):
<ide> file_path = args.eval_data_file if evaluate else args.train_data_file
<ide> if args.line_by_line:
<del> return LineByLineTextDataset(
<del> tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, local_rank=local_rank
<del> )
<add> return LineByLineTextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size)
<ide> else:
<del> return TextDataset(
<del> tokenizer=tokenizer, file_path=file_path, block_size=args.block_size, local_rank=local_rank,
<del> )
<add> return TextDataset(tokenizer=tokenizer, file_path=file_path, block_size=args.block_size)
<ide>
<ide>
<ide> def main():
<ide><path>examples/multiple-choice/run_multiple_choice.py
<ide> def main():
<ide> max_seq_length=data_args.max_seq_length,
<ide> overwrite_cache=data_args.overwrite_cache,
<ide> mode=Split.train,
<del> local_rank=training_args.local_rank,
<ide> )
<ide> if training_args.do_train
<ide> else None
<ide> def main():
<ide> max_seq_length=data_args.max_seq_length,
<ide> overwrite_cache=data_args.overwrite_cache,
<ide> mode=Split.dev,
<del> local_rank=training_args.local_rank,
<ide> )
<ide> if training_args.do_eval
<ide> else None
<ide><path>examples/multiple-choice/utils_multiple_choice.py
<ide> from typing import List, Optional
<ide>
<ide> import tqdm
<add>from filelock import FileLock
<ide>
<ide> from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available
<ide>
<ide> class Split(Enum):
<ide> if is_torch_available():
<ide> import torch
<ide> from torch.utils.data.dataset import Dataset
<del> from transformers import torch_distributed_zero_first
<ide>
<ide> class MultipleChoiceDataset(Dataset):
<ide> """
<ide> def __init__(
<ide> max_seq_length: Optional[int] = None,
<ide> overwrite_cache=False,
<ide> mode: Split = Split.train,
<del> local_rank=-1,
<ide> ):
<ide> processor = processors[task]()
<ide>
<ide> cached_features_file = os.path.join(
<ide> data_dir,
<ide> "cached_{}_{}_{}_{}".format(mode.value, tokenizer.__class__.__name__, str(max_seq_length), task,),
<ide> )
<del> with torch_distributed_zero_first(local_rank):
<del> # Make sure only the first process in distributed training processes the dataset,
<del> # and the others will use the cache.
<add>
<add> # Make sure only the first process in distributed training processes the dataset,
<add> # and the others will use the cache.
<add> lock_path = cached_features_file + ".lock"
<add> with FileLock(lock_path):
<ide>
<ide> if os.path.exists(cached_features_file) and not overwrite_cache:
<ide> logger.info(f"Loading features from cached file {cached_features_file}")
<ide> def __init__(
<ide> pad_token=tokenizer.pad_token_id,
<ide> pad_token_segment_id=tokenizer.pad_token_type_id,
<ide> )
<del> if local_rank in [-1, 0]:
<del> logger.info("Saving features into cached file %s", cached_features_file)
<del> torch.save(self.features, cached_features_file)
<add> logger.info("Saving features into cached file %s", cached_features_file)
<add> torch.save(self.features, cached_features_file)
<ide>
<ide> def __len__(self):
<ide> return len(self.features)
<ide><path>examples/token-classification/run_ner.py
<ide> def main():
<ide> max_seq_length=data_args.max_seq_length,
<ide> overwrite_cache=data_args.overwrite_cache,
<ide> mode=Split.train,
<del> local_rank=training_args.local_rank,
<ide> )
<ide> if training_args.do_train
<ide> else None
<ide> def main():
<ide> max_seq_length=data_args.max_seq_length,
<ide> overwrite_cache=data_args.overwrite_cache,
<ide> mode=Split.dev,
<del> local_rank=training_args.local_rank,
<ide> )
<ide> if training_args.do_eval
<ide> else None
<ide> def compute_metrics(p: EvalPrediction) -> Dict:
<ide> max_seq_length=data_args.max_seq_length,
<ide> overwrite_cache=data_args.overwrite_cache,
<ide> mode=Split.test,
<del> local_rank=training_args.local_rank,
<ide> )
<ide>
<ide> predictions, label_ids, metrics = trainer.predict(test_dataset)
<ide><path>examples/token-classification/utils_ner.py
<ide> from enum import Enum
<ide> from typing import List, Optional, Union
<ide>
<add>from filelock import FileLock
<add>
<ide> from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available
<ide>
<ide>
<ide> class Split(Enum):
<ide> import torch
<ide> from torch import nn
<ide> from torch.utils.data.dataset import Dataset
<del> from transformers import torch_distributed_zero_first
<ide>
<ide> class NerDataset(Dataset):
<ide> """
<ide> def __init__(
<ide> max_seq_length: Optional[int] = None,
<ide> overwrite_cache=False,
<ide> mode: Split = Split.train,
<del> local_rank=-1,
<ide> ):
<ide> # Load data features from cache or dataset file
<ide> cached_features_file = os.path.join(
<ide> data_dir, "cached_{}_{}_{}".format(mode.value, tokenizer.__class__.__name__, str(max_seq_length)),
<ide> )
<ide>
<del> with torch_distributed_zero_first(local_rank):
<del> # Make sure only the first process in distributed training processes the dataset,
<del> # and the others will use the cache.
<add> # Make sure only the first process in distributed training processes the dataset,
<add> # and the others will use the cache.
<add> lock_path = cached_features_file + ".lock"
<add> with FileLock(lock_path):
<ide>
<ide> if os.path.exists(cached_features_file) and not overwrite_cache:
<ide> logger.info(f"Loading features from cached file {cached_features_file}")
<ide> def __init__(
<ide> pad_token_segment_id=tokenizer.pad_token_type_id,
<ide> pad_token_label_id=self.pad_token_label_id,
<ide> )
<del> if local_rank in [-1, 0]:
<del> logger.info(f"Saving features into cached file {cached_features_file}")
<del> torch.save(self.features, cached_features_file)
<add> logger.info(f"Saving features into cached file {cached_features_file}")
<add> torch.save(self.features, cached_features_file)
<ide>
<ide> def __len__(self):
<ide> return len(self.features)
<ide><path>src/transformers/data/datasets/language_modeling.py
<ide> import time
<ide>
<ide> import torch
<add>from filelock import FileLock
<ide> from torch.utils.data.dataset import Dataset
<ide>
<ide> from ...tokenization_utils import PreTrainedTokenizer
<del>from ...trainer import torch_distributed_zero_first
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide> class TextDataset(Dataset):
<ide> """
<ide>
<ide> def __init__(
<del> self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int, overwrite_cache=False, local_rank=-1,
<add> self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int, overwrite_cache=False,
<ide> ):
<ide> assert os.path.isfile(file_path)
<ide>
<ide> def __init__(
<ide> directory, "cached_lm_{}_{}_{}".format(tokenizer.__class__.__name__, str(block_size), filename,),
<ide> )
<ide>
<del> with torch_distributed_zero_first(local_rank):
<del> # Make sure only the first process in distributed training processes the dataset,
<del> # and the others will use the cache.
<add> # Make sure only the first process in distributed training processes the dataset,
<add> # and the others will use the cache.
<add> lock_path = cached_features_file + ".lock"
<add> with FileLock(lock_path):
<ide>
<ide> if os.path.exists(cached_features_file) and not overwrite_cache:
<ide> start = time.time()
<ide> class LineByLineTextDataset(Dataset):
<ide> soon.
<ide> """
<ide>
<del> def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int, local_rank=-1):
<add> def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int):
<ide> assert os.path.isfile(file_path)
<ide> # Here, we do not cache the features, operating under the assumption
<ide> # that we will soon use fast multithreaded tokenizers from the | 6 |
Python | Python | convert all models | a84adddd1b8c3db75855d86a86a709c0e021fdb3 | <ide><path>pytorch_transformers/convert_pytorch_checkpoint_to_tf2.py
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<add>import os
<ide> import argparse
<ide> import tensorflow as tf
<ide>
<del>from pytorch_transformers import is_torch_available
<add>from pytorch_transformers import is_torch_available, cached_path
<ide>
<ide> from pytorch_transformers import (BertConfig, TFBertForPreTraining, load_bert_pt_weights_in_tf2,
<ide> GPT2Config, TFGPT2LMHeadModel, load_gpt2_pt_weights_in_tf2,
<ide> if is_torch_available():
<ide> import torch
<ide> import numpy as np
<del> from pytorch_transformers import BertForPreTraining, GPT2LMHeadModel, XLNetLMHeadModel, XLMWithLMHeadModel
<add> from pytorch_transformers import (BertForPreTraining, BERT_PRETRAINED_MODEL_ARCHIVE_MAP, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
<add> GPT2LMHeadModel, GPT2_PRETRAINED_MODEL_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
<add> XLNetLMHeadModel, XLNET_PRETRAINED_MODEL_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
<add> XLMWithLMHeadModel, XLM_PRETRAINED_MODEL_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,)
<ide> else:
<del> BertForPreTraining, GPT2LMHeadModel = None, None
<add> (BertForPreTraining, BERT_PRETRAINED_MODEL_ARCHIVE_MAP, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
<add> GPT2LMHeadModel, GPT2_PRETRAINED_MODEL_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
<add> XLNetLMHeadModel, XLNET_PRETRAINED_MODEL_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
<add> XLMWithLMHeadModel, XLM_PRETRAINED_MODEL_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,) = (
<add> None, None, None,
<add> None, None, None,
<add> None, None, None,
<add> None, None, None,)
<ide>
<ide>
<ide> import logging
<ide> logging.basicConfig(level=logging.INFO)
<ide>
<ide> MODEL_CLASSES = {
<del> 'bert': (BertConfig, TFBertForPreTraining, load_bert_pt_weights_in_tf2, BertForPreTraining),
<del> 'gpt2': (GPT2Config, TFGPT2LMHeadModel, load_gpt2_pt_weights_in_tf2, GPT2LMHeadModel),
<del> 'xlnet': (XLNetConfig, TFXLNetLMHeadModel, load_xlnet_pt_weights_in_tf2, XLNetLMHeadModel),
<del> 'xlm': (XLMConfig, TFXLMWithLMHeadModel, load_xlm_pt_weights_in_tf2, XLMWithLMHeadModel),
<add> 'bert': (BertConfig, TFBertForPreTraining, load_bert_pt_weights_in_tf2, BertForPreTraining, BERT_PRETRAINED_MODEL_ARCHIVE_MAP, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP),
<add> 'gpt2': (GPT2Config, TFGPT2LMHeadModel, load_gpt2_pt_weights_in_tf2, GPT2LMHeadModel, GPT2_PRETRAINED_MODEL_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP),
<add> 'xlnet': (XLNetConfig, TFXLNetLMHeadModel, load_xlnet_pt_weights_in_tf2, XLNetLMHeadModel, XLNET_PRETRAINED_MODEL_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP),
<add> 'xlm': (XLMConfig, TFXLMWithLMHeadModel, load_xlm_pt_weights_in_tf2, XLMWithLMHeadModel, XLM_PRETRAINED_MODEL_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP),
<ide> }
<ide>
<ide> def convert_pt_checkpoint_to_tf(model_type, pytorch_checkpoint_path, config_file, tf_dump_path, compare_with_pt_model=False):
<ide> if model_type not in MODEL_CLASSES:
<ide> raise ValueError("Unrecognized model type, should be one of {}.".format(list(MODEL_CLASSES.keys())))
<ide>
<del> config_class, model_class, loading_fct, pt_model_class = MODEL_CLASSES[model_type]
<add> config_class, model_class, loading_fct, pt_model_class, aws_model_maps, aws_config_map = MODEL_CLASSES[model_type]
<ide>
<ide> # Initialise TF model
<ide> config = config_class.from_json_file(config_file)
<ide> def convert_pt_checkpoint_to_tf(model_type, pytorch_checkpoint_path, config_file
<ide> tfo = tf_model(tf_inputs, training=False) # build the network
<ide>
<ide> pt_model = pt_model_class.from_pretrained(None,
<del> config=config,
<del> state_dict=torch.load(pytorch_checkpoint_path,
<add> config=config,
<add> state_dict=torch.load(pytorch_checkpoint_path,
<ide> map_location='cpu'))
<ide> pt_inputs = torch.tensor(inputs_list)
<ide> with torch.no_grad():
<ide> def convert_pt_checkpoint_to_tf(model_type, pytorch_checkpoint_path, config_file
<ide> np_tf = tfo[0].numpy()
<ide> diff = np.amax(np.abs(np_pt - np_tf))
<ide> print("Max absolute difference between models outputs {}".format(diff))
<add> assert diff <= 1e-3, "Error, model absolute difference is >1e-3"
<ide>
<ide> # Save pytorch-model
<ide> print("Save TensorFlow model to {}".format(tf_dump_path))
<del> tf_model.save_weights(tf_dump_path)
<add> tf_model.save_weights(tf_dump_path, save_format='h5')
<add>
<add>
<add>def convert_all_pt_checkpoints_to_tf(args_model_type, tf_dump_path, compare_with_pt_model=False):
<add> assert os.path.isdir(args.tf_dump_path), "--tf_dump_path should be a directory"
<add>
<add> if args_model_type is None:
<add> model_types = list(MODEL_CLASSES.keys())
<add> else:
<add> model_types = [args_model_type]
<add>
<add> for j, model_type in enumerate(model_types, start=1):
<add> print("=" * 100)
<add> print(" Converting model type {}/{}: {}".format(j, len(model_types), model_type))
<add> print("=" * 100)
<add> if model_type not in MODEL_CLASSES:
<add> raise ValueError("Unrecognized model type {}, should be one of {}.".format(model_type, list(MODEL_CLASSES.keys())))
<add>
<add> config_class, model_class, loading_fct, pt_model_class, aws_model_maps, aws_config_map = MODEL_CLASSES[model_type]
<add>
<add> for i, shortcut_name in enumerate(aws_config_map.keys(), start=1):
<add> print("-" * 100)
<add> print(" Converting checkpoint {}/{}: {}".format(i, len(aws_config_map), shortcut_name))
<add> print("-" * 100)
<add> config_file = cached_path(aws_config_map[shortcut_name], force_download=True)
<add> model_file = cached_path(aws_model_maps[shortcut_name], force_download=True)
<add>
<add> convert_pt_checkpoint_to_tf(model_type,
<add> model_file,
<add> config_file,
<add> os.path.join(tf_dump_path, shortcut_name + '-tf_model.h5'),
<add> compare_with_pt_model=compare_with_pt_model)
<ide>
<ide>
<ide> if __name__ == "__main__":
<ide> parser = argparse.ArgumentParser()
<ide> ## Required parameters
<del> parser.add_argument("--model_type",
<add> parser.add_argument("--tf_dump_path",
<ide> default = None,
<ide> type = str,
<ide> required = True,
<del> help = "Model type selcted in the list of {}.".format(list(MODEL_CLASSES.keys())))
<add> help = "Path to the output Tensorflow dump file.")
<add> parser.add_argument("--model_type",
<add> default = None,
<add> type = str,
<add> help = "Model type selected in the list of {}. If not given, will download and convert all the models from AWS.".format(list(MODEL_CLASSES.keys())))
<ide> parser.add_argument("--pytorch_checkpoint_path",
<ide> default = None,
<ide> type = str,
<del> required = True,
<del> help = "Path to the PyTorch checkpoint path.")
<add> help = "Path to the PyTorch checkpoint path or shortcut name to download from AWS. "
<add> "If not given, will download and convert all the checkpoints from AWS.")
<ide> parser.add_argument("--config_file",
<ide> default = None,
<ide> type = str,
<del> required = True,
<ide> help = "The config json file corresponding to the pre-trained model. \n"
<del> "This specifies the model architecture.")
<del> parser.add_argument("--tf_dump_path",
<del> default = None,
<del> type = str,
<del> required = True,
<del> help = "Path to the output Tensorflow dump file.")
<add> "This specifies the model architecture. If not given and "
<add> "--pytorch_checkpoint_path is not given or is a shortcut name"
<add> "use the configuration associated to teh shortcut name on the AWS")
<ide> parser.add_argument("--compare_with_pt_model",
<ide> action='store_true',
<ide> help = "Compare Tensorflow and PyTorch model predictions.")
<ide> args = parser.parse_args()
<del> convert_pt_checkpoint_to_tf(args.model_type.lower(),
<del> args.pytorch_checkpoint_path,
<del> args.config_file,
<del> args.tf_dump_path,
<del> compare_with_pt_model=args.compare_with_pt_model)
<add>
<add> if args.pytorch_checkpoint_path is not None:
<add> convert_pt_checkpoint_to_tf(args.model_type.lower(),
<add> args.pytorch_checkpoint_path,
<add> args.config_file,
<add> args.tf_dump_path,
<add> compare_with_pt_model=args.compare_with_pt_model)
<add> else:
<add> convert_all_pt_checkpoints_to_tf(args.model_type.lower() if args.model_type is not None else None,
<add> args.tf_dump_path,
<add> compare_with_pt_model=args.compare_with_pt_model)
<ide><path>pytorch_transformers/modeling_tf_transfo_xl.py
<add># coding=utf-8
<add># Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
<add># Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>""" TF 2.0 Transformer XL model.
<add>"""
<add>
<add>from __future__ import absolute_import, division, print_function, unicode_literals
<add>
<add>import os
<add>import json
<add>import math
<add>import logging
<add>import collections
<add>import sys
<add>from io import open
<add>
<add>import numpy as np
<add>import tensorflow as tf
<add>
<add>from .configuration_transfo_xl import TransfoXLConfig
<add>from .modeling_tf_utils import TFPreTrainedModel, TFConv1D, TFSequenceSummary
<add>from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax, sample_logits
<add>from .file_utils import add_start_docstrings
<add>from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model
<add>
<add>logger = logging.getLogger(__name__)
<add>
<add>TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP = {
<add> 'transfo-xl-wt103': "https://s3.amazonaws.com/models.huggingface.co/bert/transfo-xl-wt103-tf_model.h5",
<add>}
<add>
<add>def load_transfo_xl_pt_weights_in_tf2(tf_model, pytorch_checkpoint_path):
<add> # build the network
<add> inputs_list = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
<add> tf_inputs = tf.constant(inputs_list)
<add> tfo = tf_model(tf_inputs, training=False)
<add> return load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=tf_inputs)
<add>
<add>
<add>class PositionalEmbedding(nn.Module):
<add> def __init__(self, demb):
<add> super(PositionalEmbedding, self).__init__()
<add>
<add> self.demb = demb
<add>
<add> inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))
<add> self.register_buffer('inv_freq', inv_freq)
<add>
<add> def forward(self, pos_seq, bsz=None):
<add> sinusoid_inp = torch.ger(pos_seq, self.inv_freq)
<add> pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)
<add>
<add> if bsz is not None:
<add> return pos_emb[:,None,:].expand(-1, bsz, -1)
<add> else:
<add> return pos_emb[:,None,:]
<add>
<add>
<add>
<add>class PositionwiseFF(nn.Module):
<add> def __init__(self, d_model, d_inner, dropout, pre_lnorm=False):
<add> super(PositionwiseFF, self).__init__()
<add>
<add> self.d_model = d_model
<add> self.d_inner = d_inner
<add> self.dropout = dropout
<add>
<add> self.CoreNet = nn.Sequential(
<add> nn.Linear(d_model, d_inner), nn.ReLU(inplace=True),
<add> nn.Dropout(dropout),
<add> nn.Linear(d_inner, d_model),
<add> nn.Dropout(dropout),
<add> )
<add>
<add> self.layer_norm = nn.LayerNorm(d_model)
<add>
<add> self.pre_lnorm = pre_lnorm
<add>
<add> def forward(self, inp):
<add> if self.pre_lnorm:
<add> ##### layer normalization + positionwise feed-forward
<add> core_out = self.CoreNet(self.layer_norm(inp))
<add>
<add> ##### residual connection
<add> output = core_out + inp
<add> else:
<add> ##### positionwise feed-forward
<add> core_out = self.CoreNet(inp)
<add>
<add> ##### residual connection + layer normalization
<add> output = self.layer_norm(inp + core_out)
<add>
<add> return output
<add>
<add>
<add>
<add>class MultiHeadAttn(nn.Module):
<add> def __init__(self, n_head, d_model, d_head, dropout, dropatt=0,
<add> pre_lnorm=False, r_r_bias=None, r_w_bias=None, output_attentions=False):
<add> super(MultiHeadAttn, self).__init__()
<add>
<add> self.output_attentions = output_attentions
<add> self.n_head = n_head
<add> self.d_model = d_model
<add> self.d_head = d_head
<add> self.dropout = dropout
<add>
<add> self.q_net = nn.Linear(d_model, n_head * d_head, bias=False)
<add> self.kv_net = nn.Linear(d_model, 2 * n_head * d_head, bias=False)
<add>
<add> self.drop = nn.Dropout(dropout)
<add> self.dropatt = nn.Dropout(dropatt)
<add> self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)
<add>
<add> self.layer_norm = nn.LayerNorm(d_model)
<add>
<add> self.scale = 1 / (d_head ** 0.5)
<add>
<add> self.pre_lnorm = pre_lnorm
<add>
<add> if r_r_bias is None or r_w_bias is None: # Biases are not shared
<add> self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
<add> self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
<add> else:
<add> self.r_r_bias = r_r_bias
<add> self.r_w_bias = r_w_bias
<add>
<add> def forward(self, h, attn_mask=None, mems=None, head_mask=None):
<add> ##### multihead attention
<add> # [hlen x bsz x n_head x d_head]
<add>
<add> if mems is not None:
<add> c = torch.cat([mems, h], 0)
<add> else:
<add> c = h
<add>
<add> if self.pre_lnorm:
<add> ##### layer normalization
<add> c = self.layer_norm(c)
<add>
<add> head_q = self.q_net(h)
<add> head_k, head_v = torch.chunk(self.kv_net(c), 2, -1)
<add>
<add> head_q = head_q.view(h.size(0), h.size(1), self.n_head, self.d_head)
<add> head_k = head_k.view(c.size(0), c.size(1), self.n_head, self.d_head)
<add> head_v = head_v.view(c.size(0), c.size(1), self.n_head, self.d_head)
<add>
<add> # [qlen x klen x bsz x n_head]
<add> attn_score = torch.einsum('ibnd,jbnd->ijbn', (head_q, head_k))
<add> attn_score.mul_(self.scale)
<add> if attn_mask is not None and torch.sum(attn_mask).item():
<add> attn_mask = (attn_mask == 1) # Switch to bool
<add> if attn_mask.dim() == 2:
<add> attn_score.masked_fill_(attn_mask[None,:,:,None], -float('inf'))
<add> elif attn_mask.dim() == 3:
<add> attn_score.masked_fill_(attn_mask[:,:,:,None], -float('inf'))
<add>
<add> # [qlen x klen x bsz x n_head]
<add> attn_prob = F.softmax(attn_score, dim=1)
<add> attn_prob = self.dropatt(attn_prob)
<add>
<add> # Mask heads if we want to
<add> if head_mask is not None:
<add> attn_prob = attn_prob * head_mask
<add>
<add> # [qlen x klen x bsz x n_head] + [klen x bsz x n_head x d_head] -> [qlen x bsz x n_head x d_head]
<add> attn_vec = torch.einsum('ijbn,jbnd->ibnd', (attn_prob, head_v))
<add> attn_vec = attn_vec.contiguous().view(
<add> attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)
<add>
<add> ##### linear projection
<add> attn_out = self.o_net(attn_vec)
<add> attn_out = self.drop(attn_out)
<add>
<add> if self.pre_lnorm:
<add> ##### residual connection
<add> outputs = [h + attn_out]
<add> else:
<add> ##### residual connection + layer normalization
<add> outputs = [self.layer_norm(h + attn_out)]
<add>
<add> if self.output_attentions:
<add> outputs.append(attn_prob)
<add>
<add> return outputs
<add>
<add>class RelMultiHeadAttn(nn.Module):
<add> def __init__(self, n_head, d_model, d_head, dropout, dropatt=0,
<add> tgt_len=None, ext_len=None, mem_len=None, pre_lnorm=False,
<add> r_r_bias=None, r_w_bias=None, output_attentions=False):
<add> super(RelMultiHeadAttn, self).__init__()
<add>
<add> self.output_attentions = output_attentions
<add> self.n_head = n_head
<add> self.d_model = d_model
<add> self.d_head = d_head
<add> self.dropout = dropout
<add>
<add> self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False)
<add>
<add> self.drop = nn.Dropout(dropout)
<add> self.dropatt = nn.Dropout(dropatt)
<add> self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)
<add>
<add> self.layer_norm = nn.LayerNorm(d_model)
<add>
<add> self.scale = 1 / (d_head ** 0.5)
<add>
<add> self.pre_lnorm = pre_lnorm
<add>
<add> if r_r_bias is None or r_w_bias is None: # Biases are not shared
<add> self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
<add> self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
<add> else:
<add> self.r_r_bias = r_r_bias
<add> self.r_w_bias = r_w_bias
<add>
<add> def _parallelogram_mask(self, h, w, left=False):
<add> mask = torch.ones((h, w)).byte()
<add> m = min(h, w)
<add> mask[:m,:m] = torch.triu(mask[:m,:m])
<add> mask[-m:,-m:] = torch.tril(mask[-m:,-m:])
<add>
<add> if left:
<add> return mask
<add> else:
<add> return mask.flip(0)
<add>
<add> def _shift(self, x, qlen, klen, mask, left=False):
<add> if qlen > 1:
<add> zero_pad = torch.zeros((x.size(0), qlen-1, x.size(2), x.size(3)),
<add> device=x.device, dtype=x.dtype)
<add> else:
<add> zero_pad = torch.zeros(0, device=x.device, dtype=x.dtype)
<add>
<add> if left:
<add> mask = mask.flip(1)
<add> x_padded = torch.cat([zero_pad, x], dim=1).expand(qlen, -1, -1, -1)
<add> else:
<add> x_padded = torch.cat([x, zero_pad], dim=1).expand(qlen, -1, -1, -1)
<add>
<add> x = x_padded.masked_select(mask[:,:,None,None]) \
<add> .view(qlen, klen, x.size(2), x.size(3))
<add>
<add> return x
<add>
<add> def _rel_shift(self, x, zero_triu=False):
<add> zero_pad_shape = (x.size(0), 1) + x.size()[2:]
<add> zero_pad = torch.zeros(zero_pad_shape, device=x.device, dtype=x.dtype)
<add> x_padded = torch.cat([zero_pad, x], dim=1)
<add>
<add> x_padded_shape = (x.size(1) + 1, x.size(0)) + x.size()[2:]
<add> x_padded = x_padded.view(*x_padded_shape)
<add>
<add> x = x_padded[1:].view_as(x)
<add>
<add> if zero_triu:
<add> ones = torch.ones((x.size(0), x.size(1)))
<add> x = x * torch.tril(ones, x.size(1) - x.size(0))[:,:,None,None]
<add>
<add> return x
<add>
<add> def forward(self, w, r, attn_mask=None, mems=None):
<add> raise NotImplementedError
<add>
<add>class RelPartialLearnableMultiHeadAttn(RelMultiHeadAttn):
<add> def __init__(self, *args, **kwargs):
<add> super(RelPartialLearnableMultiHeadAttn, self).__init__(*args, **kwargs)
<add>
<add> self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False)
<add>
<add> def forward(self, w, r, attn_mask=None, mems=None, head_mask=None):
<add> qlen, rlen, bsz = w.size(0), r.size(0), w.size(1)
<add>
<add> if mems is not None:
<add> cat = torch.cat([mems, w], 0)
<add> if self.pre_lnorm:
<add> w_heads = self.qkv_net(self.layer_norm(cat))
<add> else:
<add> w_heads = self.qkv_net(cat)
<add> r_head_k = self.r_net(r)
<add>
<add> w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
<add> w_head_q = w_head_q[-qlen:]
<add> else:
<add> if self.pre_lnorm:
<add> w_heads = self.qkv_net(self.layer_norm(w))
<add> else:
<add> w_heads = self.qkv_net(w)
<add> r_head_k = self.r_net(r)
<add>
<add> w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
<add>
<add> klen = w_head_k.size(0)
<add>
<add> w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
<add> w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
<add> w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
<add>
<add> r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head
<add>
<add> #### compute attention score
<add> rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
<add> AC = torch.einsum('ibnd,jbnd->ijbn', (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head
<add>
<add> rr_head_q = w_head_q + self.r_r_bias
<add> BD = torch.einsum('ibnd,jnd->ijbn', (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head
<add> BD = self._rel_shift(BD)
<add>
<add> # [qlen x klen x bsz x n_head]
<add> attn_score = AC + BD
<add> attn_score.mul_(self.scale)
<add>
<add> #### compute attention probability
<add> if attn_mask is not None and torch.sum(attn_mask).item():
<add> attn_mask = (attn_mask == 1) # Switch to bool
<add> if attn_mask.dim() == 2:
<add> attn_score = attn_score.float().masked_fill(
<add> attn_mask[None,:,:,None], -1e30).type_as(attn_score)
<add> elif attn_mask.dim() == 3:
<add> attn_score = attn_score.float().masked_fill(
<add> attn_mask[:,:,:,None], -1e30).type_as(attn_score)
<add>
<add> # [qlen x klen x bsz x n_head]
<add> attn_prob = F.softmax(attn_score, dim=1)
<add> attn_prob = self.dropatt(attn_prob)
<add>
<add> # Mask heads if we want to
<add> if head_mask is not None:
<add> attn_prob = attn_prob * head_mask
<add>
<add> #### compute attention vector
<add> attn_vec = torch.einsum('ijbn,jbnd->ibnd', (attn_prob, w_head_v))
<add>
<add> # [qlen x bsz x n_head x d_head]
<add> attn_vec = attn_vec.contiguous().view(
<add> attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)
<add>
<add> ##### linear projection
<add> attn_out = self.o_net(attn_vec)
<add> attn_out = self.drop(attn_out)
<add>
<add> if self.pre_lnorm:
<add> ##### residual connection
<add> outputs = [w + attn_out]
<add> else:
<add> ##### residual connection + layer normalization
<add> outputs = [self.layer_norm(w + attn_out)]
<add>
<add> if self.output_attentions:
<add> outputs.append(attn_prob)
<add>
<add> return outputs
<add>
<add>class RelLearnableMultiHeadAttn(RelMultiHeadAttn):
<add> def __init__(self, *args, **kwargs):
<add> super(RelLearnableMultiHeadAttn, self).__init__(*args, **kwargs)
<add>
<add> def forward(self, w, r_emb, r_w_bias, r_bias, attn_mask=None, mems=None, head_mask=None):
<add> # r_emb: [klen, n_head, d_head], used for term B
<add> # r_w_bias: [n_head, d_head], used for term C
<add> # r_bias: [klen, n_head], used for term D
<add>
<add> qlen, bsz = w.size(0), w.size(1)
<add>
<add> if mems is not None:
<add> cat = torch.cat([mems, w], 0)
<add> if self.pre_lnorm:
<add> w_heads = self.qkv_net(self.layer_norm(cat))
<add> else:
<add> w_heads = self.qkv_net(cat)
<add> w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
<add>
<add> w_head_q = w_head_q[-qlen:]
<add> else:
<add> if self.pre_lnorm:
<add> w_heads = self.qkv_net(self.layer_norm(w))
<add> else:
<add> w_heads = self.qkv_net(w)
<add> w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
<add>
<add> klen = w_head_k.size(0)
<add>
<add> w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head)
<add> w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head)
<add> w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head)
<add>
<add> if klen > r_emb.size(0):
<add> r_emb_pad = r_emb[0:1].expand(klen-r_emb.size(0), -1, -1)
<add> r_emb = torch.cat([r_emb_pad, r_emb], 0)
<add> r_bias_pad = r_bias[0:1].expand(klen-r_bias.size(0), -1)
<add> r_bias = torch.cat([r_bias_pad, r_bias], 0)
<add> else:
<add> r_emb = r_emb[-klen:]
<add> r_bias = r_bias[-klen:]
<add>
<add> #### compute attention score
<add> rw_head_q = w_head_q + r_w_bias[None] # qlen x bsz x n_head x d_head
<add>
<add> AC = torch.einsum('ibnd,jbnd->ijbn', (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head
<add> B_ = torch.einsum('ibnd,jnd->ijbn', (w_head_q, r_emb)) # qlen x klen x bsz x n_head
<add> D_ = r_bias[None, :, None] # 1 x klen x 1 x n_head
<add> BD = self._rel_shift(B_ + D_)
<add>
<add> # [qlen x klen x bsz x n_head]
<add> attn_score = AC + BD
<add> attn_score.mul_(self.scale)
<add>
<add> #### compute attention probability
<add> if attn_mask is not None and torch.sum(attn_mask).item():
<add> attn_mask = (attn_mask == 1) # Switch to bool
<add> if attn_mask.dim() == 2:
<add> attn_score.masked_fill_(attn_mask[None,:,:,None], -float('inf'))
<add> elif attn_mask.dim() == 3:
<add> attn_score.masked_fill_(attn_mask[:,:,:,None], -float('inf'))
<add>
<add> # [qlen x klen x bsz x n_head]
<add> attn_prob = F.softmax(attn_score, dim=1)
<add> attn_prob = self.dropatt(attn_prob)
<add>
<add> if head_mask is not None:
<add> attn_prob = attn_prob * head_mask
<add>
<add> #### compute attention vector
<add> attn_vec = torch.einsum('ijbn,jbnd->ibnd', (attn_prob, w_head_v))
<add>
<add> # [qlen x bsz x n_head x d_head]
<add> attn_vec = attn_vec.contiguous().view(
<add> attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)
<add>
<add> ##### linear projection
<add> attn_out = self.o_net(attn_vec)
<add> attn_out = self.drop(attn_out)
<add>
<add> if self.pre_lnorm:
<add> ##### residual connection
<add> outputs = [w + attn_out]
<add> else:
<add> ##### residual connection + layer normalization
<add> outputs = [self.layer_norm(w + attn_out)]
<add>
<add> if self.output_attentions:
<add> outputs.append(attn_prob)
<add>
<add> return outputs
<add>
<add>
<add>
<add>class DecoderLayer(nn.Module):
<add> def __init__(self, n_head, d_model, d_head, d_inner, dropout, **kwargs):
<add> super(DecoderLayer, self).__init__()
<add>
<add> self.dec_attn = MultiHeadAttn(n_head, d_model, d_head, dropout, **kwargs)
<add> self.pos_ff = PositionwiseFF(d_model, d_inner, dropout,
<add> pre_lnorm=kwargs.get('pre_lnorm'))
<add>
<add> def forward(self, dec_inp, dec_attn_mask=None, mems=None, head_mask=None):
<add>
<add> attn_outputs = self.dec_attn(dec_inp, attn_mask=dec_attn_mask,
<add> mems=mems, head_mask=head_mask)
<add> ff_output = self.pos_ff(attn_outputs[0])
<add>
<add> outputs = [ff_output] + attn_outputs[1:]
<add>
<add> return outputs
<add>
<add>class RelLearnableDecoderLayer(nn.Module):
<add> def __init__(self, n_head, d_model, d_head, d_inner, dropout,
<add> **kwargs):
<add> super(RelLearnableDecoderLayer, self).__init__()
<add>
<add> self.dec_attn = RelLearnableMultiHeadAttn(n_head, d_model, d_head, dropout,
<add> **kwargs)
<add> self.pos_ff = PositionwiseFF(d_model, d_inner, dropout,
<add> pre_lnorm=kwargs.get('pre_lnorm'))
<add>
<add> def forward(self, dec_inp, r_emb, r_w_bias, r_bias, dec_attn_mask=None, mems=None, head_mask=None):
<add>
<add> attn_outputs = self.dec_attn(dec_inp, r_emb, r_w_bias, r_bias,
<add> attn_mask=dec_attn_mask,
<add> mems=mems, head_mask=head_mask)
<add> ff_output = self.pos_ff(attn_outputs[0])
<add>
<add> outputs = [ff_output] + attn_outputs[1:]
<add>
<add> return outputs
<add>
<add>class RelPartialLearnableDecoderLayer(nn.Module):
<add> def __init__(self, n_head, d_model, d_head, d_inner, dropout,
<add> **kwargs):
<add> super(RelPartialLearnableDecoderLayer, self).__init__()
<add>
<add> self.dec_attn = RelPartialLearnableMultiHeadAttn(n_head, d_model,
<add> d_head, dropout, **kwargs)
<add> self.pos_ff = PositionwiseFF(d_model, d_inner, dropout,
<add> pre_lnorm=kwargs.get('pre_lnorm'))
<add>
<add> def forward(self, dec_inp, r, dec_attn_mask=None, mems=None, head_mask=None):
<add>
<add> attn_outputs = self.dec_attn(dec_inp, r,
<add> attn_mask=dec_attn_mask,
<add> mems=mems, head_mask=head_mask)
<add> ff_output = self.pos_ff(attn_outputs[0])
<add>
<add> outputs = [ff_output] + attn_outputs[1:]
<add>
<add> return outputs
<add>
<add>
<add>
<add>class AdaptiveEmbedding(nn.Module):
<add> def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1,
<add> sample_softmax=False):
<add> super(AdaptiveEmbedding, self).__init__()
<add>
<add> self.n_token = n_token
<add> self.d_embed = d_embed
<add>
<add> self.cutoffs = cutoffs + [n_token]
<add> self.div_val = div_val
<add> self.d_proj = d_proj
<add>
<add> self.emb_scale = d_proj ** 0.5
<add>
<add> self.cutoff_ends = [0] + self.cutoffs
<add>
<add> self.emb_layers = nn.ModuleList()
<add> self.emb_projs = nn.ParameterList()
<add> if div_val == 1:
<add> self.emb_layers.append(
<add> nn.Embedding(n_token, d_embed, sparse=sample_softmax>0)
<add> )
<add> if d_proj != d_embed:
<add> self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
<add> else:
<add> for i in range(len(self.cutoffs)):
<add> l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i+1]
<add> d_emb_i = d_embed // (div_val ** i)
<add> self.emb_layers.append(nn.Embedding(r_idx-l_idx, d_emb_i))
<add> self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
<add>
<add> def forward(self, inp):
<add> if self.div_val == 1:
<add> embed = self.emb_layers[0](inp)
<add> if self.d_proj != self.d_embed:
<add> embed = F.linear(embed, self.emb_projs[0])
<add> else:
<add> param = next(self.parameters())
<add> inp_flat = inp.view(-1)
<add> emb_flat = torch.zeros([inp_flat.size(0), self.d_proj],
<add> dtype=param.dtype, device=param.device)
<add> for i in range(len(self.cutoffs)):
<add> l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
<add>
<add> mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
<add> indices_i = mask_i.nonzero().squeeze()
<add>
<add> if indices_i.numel() == 0:
<add> continue
<add>
<add> inp_i = inp_flat.index_select(0, indices_i) - l_idx
<add> emb_i = self.emb_layers[i](inp_i)
<add> emb_i = F.linear(emb_i, self.emb_projs[i])
<add>
<add> emb_flat.index_copy_(0, indices_i, emb_i)
<add>
<add> embed_shape = inp.size() + (self.d_proj,)
<add> embed = emb_flat.view(embed_shape)
<add>
<add> embed.mul_(self.emb_scale)
<add>
<add> return embed
<add>
<add>
<add>class TransfoXLPreTrainedModel(PreTrainedModel):
<add> """ An abstract class to handle weights initialization and
<add> a simple interface for dowloading and loading pretrained models.
<add> """
<add> config_class = TransfoXLConfig
<add> pretrained_model_archive_map = TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP
<add> load_tf_weights = load_tf_weights_in_transfo_xl
<add> base_model_prefix = "transformer"
<add>
<add> def _init_weight(self, weight):
<add> if self.config.init == 'uniform':
<add> nn.init.uniform_(weight, -self.config.init_range, self.config.init_range)
<add> elif self.config.init == 'normal':
<add> nn.init.normal_(weight, 0.0, self.config.init_std)
<add>
<add> def _init_bias(self, bias):
<add> nn.init.constant_(bias, 0.0)
<add>
<add> def _init_weights(self, m):
<add> """ Initialize the weights.
<add> """
<add> classname = m.__class__.__name__
<add> if classname.find('Linear') != -1:
<add> if hasattr(m, 'weight') and m.weight is not None:
<add> self._init_weight(m.weight)
<add> if hasattr(m, 'bias') and m.bias is not None:
<add> self._init_bias(m.bias)
<add> elif classname.find('AdaptiveEmbedding') != -1:
<add> if hasattr(m, 'emb_projs'):
<add> for i in range(len(m.emb_projs)):
<add> if m.emb_projs[i] is not None:
<add> nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std)
<add> elif classname.find('Embedding') != -1:
<add> if hasattr(m, 'weight'):
<add> self._init_weight(m.weight)
<add> elif classname.find('ProjectedAdaptiveLogSoftmax') != -1:
<add> if hasattr(m, 'cluster_weight') and m.cluster_weight is not None:
<add> self._init_weight(m.cluster_weight)
<add> if hasattr(m, 'cluster_bias') and m.cluster_bias is not None:
<add> self._init_bias(m.cluster_bias)
<add> if hasattr(m, 'out_projs'):
<add> for i in range(len(m.out_projs)):
<add> if m.out_projs[i] is not None:
<add> nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std)
<add> elif classname.find('LayerNorm') != -1:
<add> if hasattr(m, 'weight'):
<add> nn.init.normal_(m.weight, 1.0, self.config.init_std)
<add> if hasattr(m, 'bias') and m.bias is not None:
<add> self._init_bias(m.bias)
<add> else:
<add> if hasattr(m, 'r_emb'):
<add> self._init_weight(m.r_emb)
<add> if hasattr(m, 'r_w_bias'):
<add> self._init_weight(m.r_w_bias)
<add> if hasattr(m, 'r_r_bias'):
<add> self._init_weight(m.r_r_bias)
<add> if hasattr(m, 'r_bias'):
<add> self._init_bias(m.r_bias)
<add>
<add> def set_num_special_tokens(self, num_special_tokens):
<add> pass
<add>
<add>
<add>TRANSFO_XL_START_DOCSTRING = r""" The Transformer-XL model was proposed in
<add> `Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context`_
<add> by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
<add> It's a causal (uni-directional) transformer with relative positioning (sinusoïdal) embeddings which can reuse
<add> previously computed hidden-states to attend to longer context (memory).
<add> This model also uses adaptive softmax inputs and outputs (tied).
<add>
<add> This model is a PyTorch `torch.nn.Module`_ sub-class. Use it as a regular PyTorch Module and
<add> refer to the PyTorch documentation for all matter related to general usage and behavior.
<add>
<add> .. _`Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context`:
<add> https://arxiv.org/abs/1901.02860
<add>
<add> .. _`torch.nn.Module`:
<add> https://pytorch.org/docs/stable/nn.html#module
<add>
<add> Parameters:
<add> config (:class:`~pytorch_transformers.TransfoXLConfig`): Model configuration class with all the parameters of the model.
<add> Initializing with a config file does not load the weights associated with the model, only the configuration.
<add> Check out the :meth:`~pytorch_transformers.PreTrainedModel.from_pretrained` method to load the model weights.
<add>"""
<add>
<add>TRANSFO_XL_INPUTS_DOCSTRING = r"""
<add> Inputs:
<add> **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
<add> Indices of input sequence tokens in the vocabulary.
<add> Transformer-XL is a model with relative position embeddings so you can either pad the inputs on
<add> the right or on the left.
<add> Indices can be obtained using :class:`pytorch_transformers.TransfoXLTokenizer`.
<add> See :func:`pytorch_transformers.PreTrainedTokenizer.encode` and
<add> :func:`pytorch_transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.
<add> **mems**: (`optional`)
<add> list of ``torch.FloatTensor`` (one for each layer):
<add> that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
<add> (see `mems` output below). Can be used to speed up sequential decoding and attend to longer context.
<add> **head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:
<add> Mask to nullify selected heads of the self-attention modules.
<add> Mask values selected in ``[0, 1]``:
<add> ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.
<add>"""
<add>
<add>@add_start_docstrings("The bare Bert Model transformer outputing raw hidden-states without any specific head on top.",
<add> TRANSFO_XL_START_DOCSTRING, TRANSFO_XL_INPUTS_DOCSTRING)
<add>class TransfoXLModel(TransfoXLPreTrainedModel):
<add> r"""
<add> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
<add> **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``
<add> Sequence of hidden-states at the last layer of the model.
<add> **mems**:
<add> list of ``torch.FloatTensor`` (one for each layer):
<add> that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
<add> (see `mems` input above). Can be used to speed up sequential decoding and attend to longer context.
<add> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
<add> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
<add> of shape ``(batch_size, sequence_length, hidden_size)``:
<add> Hidden-states of the model at the output of each layer plus the initial embedding outputs.
<add> **attentions**: (`optional`, returned when ``config.output_attentions=True``)
<add> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
<add> Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
<add>
<add> Examples::
<add>
<add> tokenizer = TransfoXLTokenizer.from_pretrained('transfo-xl-wt103')
<add> model = TransfoXLModel.from_pretrained('transfo-xl-wt103')
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> outputs = model(input_ids)
<add> last_hidden_states, mems = outputs[:2]
<add>
<add> """
<add> def __init__(self, config):
<add> super(TransfoXLModel, self).__init__(config)
<add> self.output_attentions = config.output_attentions
<add> self.output_hidden_states = config.output_hidden_states
<add>
<add> self.n_token = config.n_token
<add>
<add> self.d_embed = config.d_embed
<add> self.d_model = config.d_model
<add> self.n_head = config.n_head
<add> self.d_head = config.d_head
<add>
<add> self.word_emb = AdaptiveEmbedding(config.n_token, config.d_embed, config.d_model, config.cutoffs,
<add> div_val=config.div_val)
<add>
<add> self.drop = nn.Dropout(config.dropout)
<add>
<add> self.n_layer = config.n_layer
<add>
<add> self.tgt_len = config.tgt_len
<add> self.mem_len = config.mem_len
<add> self.ext_len = config.ext_len
<add> self.max_klen = config.tgt_len + config.ext_len + config.mem_len
<add>
<add> self.attn_type = config.attn_type
<add>
<add> if not config.untie_r:
<add> self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
<add> self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
<add>
<add> self.layers = nn.ModuleList()
<add> if config.attn_type == 0: # the default attention
<add> for i in range(config.n_layer):
<add> self.layers.append(
<add> RelPartialLearnableDecoderLayer(
<add> config.n_head, config.d_model, config.d_head, config.d_inner, config.dropout,
<add> tgt_len=config.tgt_len, ext_len=config.ext_len, mem_len=config.mem_len,
<add> dropatt=config.dropatt, pre_lnorm=config.pre_lnorm,
<add> r_w_bias=None if config.untie_r else self.r_w_bias,
<add> r_r_bias=None if config.untie_r else self.r_r_bias,
<add> output_attentions=self.output_attentions)
<add> )
<add> elif config.attn_type == 1: # learnable embeddings
<add> for i in range(config.n_layer):
<add> self.layers.append(
<add> RelLearnableDecoderLayer(
<add> config.n_head, config.d_model, config.d_head, config.d_inner, config.dropout,
<add> tgt_len=config.tgt_len, ext_len=config.ext_len, mem_len=config.mem_len,
<add> dropatt=config.dropatt, pre_lnorm=config.pre_lnorm,
<add> r_w_bias=None if config.untie_r else self.r_w_bias,
<add> r_r_bias=None if config.untie_r else self.r_r_bias,
<add> output_attentions=self.output_attentions)
<add> )
<add> elif config.attn_type in [2, 3]: # absolute embeddings
<add> for i in range(config.n_layer):
<add> self.layers.append(
<add> DecoderLayer(
<add> config.n_head, config.d_model, config.d_head, config.d_inner, config.dropout,
<add> dropatt=config.dropatt, pre_lnorm=config.pre_lnorm,
<add> r_w_bias=None if config.untie_r else self.r_w_bias,
<add> r_r_bias=None if config.untie_r else self.r_r_bias,
<add> output_attentions=self.output_attentions)
<add> )
<add>
<add> self.same_length = config.same_length
<add> self.clamp_len = config.clamp_len
<add>
<add> if self.attn_type == 0: # default attention
<add> self.pos_emb = PositionalEmbedding(self.d_model)
<add> elif self.attn_type == 1: # learnable
<add> self.r_emb = nn.Parameter(torch.FloatTensor(
<add> self.n_layer, self.max_klen, self.n_head, self.d_head))
<add> self.r_bias = nn.Parameter(torch.FloatTensor(
<add> self.n_layer, self.max_klen, self.n_head))
<add> elif self.attn_type == 2: # absolute standard
<add> self.pos_emb = PositionalEmbedding(self.d_model)
<add> elif self.attn_type == 3: # absolute deeper SA
<add> self.r_emb = nn.Parameter(torch.FloatTensor(
<add> self.n_layer, self.max_klen, self.n_head, self.d_head))
<add>
<add> self.init_weights()
<add>
<add> def _resize_token_embeddings(self, new_num_tokens):
<add> return self.word_emb
<add>
<add> def backward_compatible(self):
<add> self.sample_softmax = -1
<add>
<add> def reset_length(self, tgt_len, ext_len, mem_len):
<add> self.tgt_len = tgt_len
<add> self.mem_len = mem_len
<add> self.ext_len = ext_len
<add>
<add> def _prune_heads(self, heads):
<add> logger.info("Head pruning is not implemented for Transformer-XL model")
<add> pass
<add>
<add> def init_mems(self, data):
<add> if self.mem_len > 0:
<add> mems = []
<add> param = next(self.parameters())
<add> for i in range(self.n_layer):
<add> empty = torch.zeros(self.mem_len, data.size(1), self.config.d_model,
<add> dtype=param.dtype, device=param.device)
<add> mems.append(empty)
<add>
<add> return mems
<add> else:
<add> return None
<add>
<add> def _update_mems(self, hids, mems, qlen, mlen):
<add> # does not deal with None
<add> if mems is None: return None
<add>
<add> # mems is not None
<add> assert len(hids) == len(mems), 'len(hids) != len(mems)'
<add>
<add> # There are `mlen + qlen` steps that can be cached into mems
<add> # For the next step, the last `ext_len` of the `qlen` tokens
<add> # will be used as the extended context. Hence, we only cache
<add> # the tokens from `mlen + qlen - self.ext_len - self.mem_len`
<add> # to `mlen + qlen - self.ext_len`.
<add> with torch.no_grad():
<add> new_mems = []
<add> end_idx = mlen + max(0, qlen - 0 - self.ext_len)
<add> beg_idx = max(0, end_idx - self.mem_len)
<add> for i in range(len(hids)):
<add>
<add> cat = torch.cat([mems[i], hids[i]], dim=0)
<add> new_mems.append(cat[beg_idx:end_idx].detach())
<add>
<add> return new_mems
<add>
<add> def _forward(self, dec_inp, mems=None, head_mask=None):
<add> qlen, bsz = dec_inp.size()
<add>
<add> # Prepare head mask if needed
<add> # 1.0 in head_mask indicate we keep the head
<add> # attention_probs has shape bsz x n_heads x N x N
<add> # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
<add> # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
<add> if head_mask is not None:
<add> if head_mask.dim() == 1:
<add> head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0)
<add> head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1)
<add> elif head_mask.dim() == 2:
<add> head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1)
<add> head_mask = head_mask.to(dtype=next(self.parameters()).dtype) # switch to fload if need + fp16 compatibility
<add> else:
<add> head_mask = [None] * self.n_layer
<add>
<add> word_emb = self.word_emb(dec_inp)
<add>
<add> mlen = mems[0].size(0) if mems is not None else 0
<add> klen = mlen + qlen
<add> if self.same_length:
<add> all_ones = word_emb.new_ones((qlen, klen), dtype=torch.uint8)
<add> mask_len = klen - self.mem_len
<add> if mask_len > 0:
<add> mask_shift_len = qlen - mask_len
<add> else:
<add> mask_shift_len = qlen
<add> dec_attn_mask = (torch.triu(all_ones, 1+mlen)
<add> + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1
<add> else:
<add> dec_attn_mask = torch.triu(
<add> word_emb.new_ones((qlen, klen), dtype=torch.uint8), diagonal=1+mlen)[:,:,None]
<add>
<add> hids = []
<add> attentions = []
<add> if self.attn_type == 0: # default
<add> pos_seq = torch.arange(klen-1, -1, -1.0, device=word_emb.device,
<add> dtype=word_emb.dtype)
<add> if self.clamp_len > 0:
<add> pos_seq.clamp_(max=self.clamp_len)
<add> pos_emb = self.pos_emb(pos_seq)
<add>
<add> core_out = self.drop(word_emb)
<add> pos_emb = self.drop(pos_emb)
<add>
<add> for i, layer in enumerate(self.layers):
<add> hids.append(core_out)
<add> mems_i = None if mems is None else mems[i]
<add> layer_outputs = layer(core_out, pos_emb, dec_attn_mask=dec_attn_mask,
<add> mems=mems_i, head_mask=head_mask[i])
<add> core_out = layer_outputs[0]
<add> if self.output_attentions:
<add> attentions.append(layer_outputs[1])
<add> elif self.attn_type == 1: # learnable
<add> core_out = self.drop(word_emb)
<add> for i, layer in enumerate(self.layers):
<add> hids.append(core_out)
<add> if self.clamp_len > 0:
<add> r_emb = self.r_emb[i][-self.clamp_len :]
<add> r_bias = self.r_bias[i][-self.clamp_len :]
<add> else:
<add> r_emb, r_bias = self.r_emb[i], self.r_bias[i]
<add>
<add> mems_i = None if mems is None else mems[i]
<add> layer_outputs = layer(core_out, r_emb, self.r_w_bias[i],
<add> r_bias, dec_attn_mask=dec_attn_mask,
<add> mems=mems_i, head_mask=head_mask[i])
<add> core_out = layer_outputs[0]
<add> if self.output_attentions:
<add> attentions.append(layer_outputs[1])
<add> elif self.attn_type == 2: # absolute
<add> pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device,
<add> dtype=word_emb.dtype)
<add> if self.clamp_len > 0:
<add> pos_seq.clamp_(max=self.clamp_len)
<add> pos_emb = self.pos_emb(pos_seq)
<add>
<add> core_out = self.drop(word_emb + pos_emb[-qlen:])
<add>
<add> for i, layer in enumerate(self.layers):
<add> hids.append(core_out)
<add> mems_i = None if mems is None else mems[i]
<add> if mems_i is not None and i == 0:
<add> mems_i += pos_emb[:mlen]
<add> layer_outputs = layer(core_out, dec_attn_mask=dec_attn_mask,
<add> mems=mems_i, head_mask=head_mask[i])
<add> core_out = layer_outputs[0]
<add> if self.output_attentions:
<add> attentions.append(layer_outputs[1])
<add> elif self.attn_type == 3:
<add> core_out = self.drop(word_emb)
<add>
<add> for i, layer in enumerate(self.layers):
<add> hids.append(core_out)
<add> mems_i = None if mems is None else mems[i]
<add> if mems_i is not None and mlen > 0:
<add> cur_emb = self.r_emb[i][:-qlen]
<add> cur_size = cur_emb.size(0)
<add> if cur_size < mlen:
<add> cur_emb_pad = cur_emb[0:1].expand(mlen-cur_size, -1, -1)
<add> cur_emb = torch.cat([cur_emb_pad, cur_emb], 0)
<add> else:
<add> cur_emb = cur_emb[-mlen:]
<add> mems_i += cur_emb.view(mlen, 1, -1)
<add> core_out += self.r_emb[i][-qlen:].view(qlen, 1, -1)
<add>
<add> layer_outputs = layer(core_out, dec_attn_mask=dec_attn_mask,
<add> mems=mems_i, head_mask=head_mask[i])
<add> core_out = layer_outputs[0]
<add> if self.output_attentions:
<add> attentions.append(layer_outputs[1])
<add>
<add> core_out = self.drop(core_out)
<add>
<add> new_mems = self._update_mems(hids, mems, mlen, qlen)
<add>
<add> # We transpose back here to shape [bsz, len, hidden_dim]
<add> outputs = [core_out.transpose(0, 1).contiguous(), new_mems]
<add> if self.output_hidden_states:
<add> # Add last layer and transpose to library standard shape [bsz, len, hidden_dim]
<add> hids.append(core_out)
<add> hids = list(t.transpose(0, 1).contiguous() for t in hids)
<add> outputs.append(hids)
<add> if self.output_attentions:
<add> # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
<add> attentions = list(t.permute(2, 3, 0, 1).contiguous() for t in attentions)
<add> outputs.append(attentions)
<add> return outputs # last hidden state, new_mems, (all hidden states), (all attentions)
<add>
<add> def forward(self, input_ids, mems=None, head_mask=None):
<add> # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
<add> # so we transpose here from shape [bsz, len] to shape [len, bsz]
<add> input_ids = input_ids.transpose(0, 1).contiguous()
<add>
<add> if mems is None:
<add> mems = self.init_mems(input_ids)
<add> outputs = self._forward(input_ids, mems=mems, head_mask=head_mask)
<add>
<add> return outputs # last hidden state, new_mems, (all hidden states), (all attentions)
<add>
<add>
<add>@add_start_docstrings("""The Transformer-XL Model with a language modeling head on top
<add> (adaptive softmax with weights tied to the adaptive input embeddings)""",
<add> TRANSFO_XL_START_DOCSTRING, TRANSFO_XL_INPUTS_DOCSTRING)
<add>class TransfoXLLMHeadModel(TransfoXLPreTrainedModel):
<add> r"""
<add> **lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
<add> Labels for language modeling.
<add> Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
<add> Indices are selected in ``[-1, 0, ..., config.vocab_size]``
<add> All labels set to ``-1`` are ignored (masked), the loss is only
<add> computed for labels in ``[0, ..., config.vocab_size]``
<add>
<add> Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
<add> **loss**: (`optional`, returned when ``lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
<add> Language modeling loss.
<add> **prediction_scores**: ``None`` if ``lm_labels`` is provided else ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``
<add> Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
<add> We don't output them when the loss is computed to speedup adaptive softmax decoding.
<add> **mems**:
<add> list of ``torch.FloatTensor`` (one for each layer):
<add> that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
<add> (see `mems` input above). Can be used to speed up sequential decoding and attend to longer context.
<add> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
<add> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
<add> of shape ``(batch_size, sequence_length, hidden_size)``:
<add> Hidden-states of the model at the output of each layer plus the initial embedding outputs.
<add> **attentions**: (`optional`, returned when ``config.output_attentions=True``)
<add> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
<add> Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
<add>
<add> Examples::
<add>
<add> tokenizer = TransfoXLTokenizer.from_pretrained('transfo-xl-wt103')
<add> model = TransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103')
<add> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
<add> outputs = model(input_ids)
<add> prediction_scores, mems = outputs[:2]
<add>
<add> """
<add> def __init__(self, config):
<add> super(TransfoXLLMHeadModel, self).__init__(config)
<add> self.transformer = TransfoXLModel(config)
<add> self.sample_softmax = config.sample_softmax
<add> # use sampled softmax
<add> if config.sample_softmax > 0:
<add> self.out_layer = nn.Linear(config.d_model, config.n_token)
<add> self.sampler = LogUniformSampler(config.n_token, config.sample_softmax)
<add> # use adaptive softmax (including standard softmax)
<add> else:
<add> self.crit = ProjectedAdaptiveLogSoftmax(config.n_token, config.d_embed, config.d_model,
<add> config.cutoffs, div_val=config.div_val)
<add> self.init_weights()
<add> self.tie_weights()
<add>
<add> def tie_weights(self):
<add> """
<add> Run this to be sure output and input (adaptive) softmax weights are tied
<add> """
<add> # sampled softmax
<add> if self.sample_softmax > 0:
<add> if self.config.tie_weight:
<add> self.out_layer.weight = self.transformer.word_emb.weight
<add> # adaptive softmax (including standard softmax)
<add> else:
<add> if self.config.tie_weight:
<add> for i in range(len(self.crit.out_layers)):
<add> self._tie_or_clone_weights(self.crit.out_layers[i],
<add> self.transformer.word_emb.emb_layers[i])
<add> if self.config.tie_projs:
<add> for i, tie_proj in enumerate(self.config.tie_projs):
<add> if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:
<add> if self.config.torchscript:
<add> self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[0].clone())
<add> else:
<add> self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]
<add> elif tie_proj and self.config.div_val != 1:
<add> if self.config.torchscript:
<add> self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[i].clone())
<add> else:
<add> self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]
<add>
<add> def reset_length(self, tgt_len, ext_len, mem_len):
<add> self.transformer.reset_length(tgt_len, ext_len, mem_len)
<add>
<add> def init_mems(self, data):
<add> return self.transformer.init_mems(data)
<add>
<add> def forward(self, input_ids, mems=None, head_mask=None, labels=None):
<add> bsz = input_ids.size(0)
<add> tgt_len = input_ids.size(1)
<add>
<add> transformer_outputs = self.transformer(input_ids, mems=mems, head_mask=head_mask)
<add>
<add> last_hidden = transformer_outputs[0]
<add> pred_hid = last_hidden[:, -tgt_len:]
<add> outputs = transformer_outputs[1:]
<add> if self.sample_softmax > 0 and self.training:
<add> assert self.config.tie_weight
<add> logit = sample_logits(self.transformer.word_emb, self.out_layer.bias, labels, pred_hid, self.sampler)
<add> softmax_output = -F.log_softmax(logit, -1)[:, :, 0]
<add> outputs = [softmax_output] + outputs
<add> if labels is not None:
<add> # TODO: This is not implemented
<add> raise NotImplementedError
<add> else:
<add> softmax_output = self.crit(pred_hid.view(-1, pred_hid.size(-1)), labels)
<add> if labels is None:
<add> softmax_output = softmax_output.view(bsz, tgt_len, -1)
<add> outputs = [softmax_output] + outputs
<add> else:
<add> softmax_output = softmax_output.view(bsz, tgt_len)
<add> outputs = [softmax_output, None] + outputs
<add>
<add> return outputs # (loss), logits or None if labels is not None (speed up adaptive softmax), new_mems, (all hidden states), (all attentions) | 2 |
Java | Java | use assertthat from hamcrest instead of junit 4 | d4379630e24090ce086cc7baced731a38a1753d2 | <ide><path>spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java
<ide> import org.junit.Test;
<ide>
<ide> import static org.hamcrest.Matchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide> import static org.mockito.BDDMockito.*;
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java
<ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide>
<ide> /**
<ide><path>spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java
<ide> import static java.util.Arrays.stream;
<ide> import static java.util.stream.Collectors.toCollection;
<ide> import static org.hamcrest.CoreMatchers.equalTo;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertThat;
<ide>
<ide> /**
<ide> * Integration tests that verify proper concurrency support between a
<ide><path>spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/TestPropertySourceInterfaceTests.java
<ide> import org.springframework.test.context.junit4.SpringRunner;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<del>import static org.junit.Assert.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide>
<ide> /**
<ide> * @author Sam Brannen
<ide><path>spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java
<ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide> import static org.springframework.test.context.support.TestPropertySourceUtils.*;
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/context/event/EventPublishingTestExecutionListenerIntegrationTests.java
<ide> import static java.lang.annotation.RetentionPolicy.RUNTIME;
<ide> import static org.hamcrest.CoreMatchers.equalTo;
<ide> import static org.hamcrest.CoreMatchers.startsWith;
<del>import static org.junit.Assert.assertThat;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.mockito.Mockito.mock;
<ide> import static org.mockito.Mockito.never;
<ide> import static org.mockito.Mockito.only;
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr6128/AutowiredQualifierTests.java
<ide> import org.springframework.test.context.ContextConfiguration;
<ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<ide>
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.hamcrest.core.IsEqual.*;
<del>import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> * Integration tests to verify claims made in <a
<ide><path>spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java
<ide> import org.springframework.test.context.ContextLoader;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide> import static org.springframework.test.context.support.ContextLoaderUtils.*;
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java
<ide> import org.springframework.jdbc.core.JdbcTemplate;
<ide>
<ide> import static org.hamcrest.Matchers.*;
<del>import static org.junit.Assert.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.mockito.BDDMockito.*;
<ide>
<ide> /**
<ide><path>spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java
<ide> import org.springframework.aop.support.AopUtils;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide> import static org.springframework.test.util.AopTestUtils.*;
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java
<ide>
<ide> import static java.time.Duration.*;
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide> import static org.springframework.http.MediaType.*;
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/DelegatingWebConnectionTests.java
<ide>
<ide> import static org.hamcrest.CoreMatchers.equalTo;
<ide> import static org.hamcrest.CoreMatchers.sameInstance;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.hamcrest.Matchers.*;
<ide> import static org.hamcrest.core.IsNot.not;
<del>import static org.junit.Assert.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> /**
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/HtmlUnitRequestBuilderTests.java
<ide> import org.springframework.test.web.servlet.setup.MockMvcBuilders;
<ide>
<ide> import static java.util.Arrays.asList;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.hamcrest.Matchers.contains;
<ide> import static org.hamcrest.Matchers.equalTo;
<ide> import static org.hamcrest.Matchers.isEmptyString;
<ide> import static org.hamcrest.Matchers.not;
<ide> import static org.hamcrest.Matchers.notNullValue;
<ide> import static org.hamcrest.Matchers.nullValue;
<ide> import static org.hamcrest.Matchers.sameInstance;
<del>import static org.junit.Assert.assertThat;
<ide> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
<ide>
<ide> /**
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcConnectionBuilderSupportTests.java
<ide>
<ide> import static org.hamcrest.CoreMatchers.equalTo;
<ide> import static org.hamcrest.CoreMatchers.nullValue;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.hamcrest.Matchers.notNullValue;
<del>import static org.junit.Assert.assertThat;
<ide> import static org.mockito.Mockito.mock;
<ide> import static org.mockito.Mockito.when;
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebClientBuilderTests.java
<ide> import org.springframework.web.servlet.config.annotation.EnableWebMvc;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<del>import static org.junit.Assert.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide>
<ide> /**
<ide> * Integration tests for {@link MockMvcWebClientBuilder}.
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionTests.java
<ide> import org.springframework.test.web.servlet.setup.MockMvcBuilders;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide>
<ide> /**
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockWebResponseBuilderTests.java
<ide> import org.springframework.mock.web.MockHttpServletResponse;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<del>import static org.junit.Assert.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide>
<ide> /**
<ide> * Tests for {@link MockWebResponseBuilder}.
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/MockMvcHtmlUnitDriverBuilderTests.java
<ide> import org.springframework.web.servlet.config.annotation.EnableWebMvc;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide>
<ide> /**
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/CustomRequestAttributesRequestContextHolderTests.java
<ide> import static org.hamcrest.CoreMatchers.instanceOf;
<ide> import static org.hamcrest.CoreMatchers.is;
<ide> import static org.hamcrest.CoreMatchers.nullValue;
<del>import static org.junit.Assert.assertThat;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
<ide> import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
<ide> import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java
<ide> import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
<ide> import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
<ide><path>spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java
<ide> import org.springframework.tests.beans.CollectingReaderEventListener;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<del>import static org.junit.Assert.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide>
<ide> /**
<ide> * @author Torsten Juergeleit
<ide><path>spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java
<ide> import org.springframework.transaction.event.TransactionalEventListenerFactory;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide>
<ide> /**
<ide><path>spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java
<ide> import org.springframework.beans.FatalBeanException;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.*;
<ide>
<ide> /** | 23 |
Python | Python | use a context manager for f2py functions | cd24ca1ef578924bad8c5c31f8939e64e353c256 | <ide><path>numpy/f2py/tests/test_compile_function.py
<ide> def test_f2py_init_compile(extra_args):
<ide> # util.py, but don't actually use build_module() because it has
<ide> # its own invocation of subprocess that circumvents the
<ide> # f2py.compile code block under test
<del> try:
<del> os.chdir(moddir)
<add> with util.switchdir(moddir):
<ide> ret_val = numpy.f2py.compile(
<ide> fsource,
<ide> modulename=modname,
<ide> extra_args=extra_args,
<ide> source_fn=source_fn
<del> )
<del> finally:
<del> os.chdir(cwd)
<add> )
<ide>
<del> # check for compile success return value
<del> assert_equal(ret_val, 0)
<add> # check for compile success return value
<add> assert_equal(ret_val, 0)
<ide>
<ide> # we are not currently able to import the Python-Fortran
<ide> # interface module on Windows / Appveyor, even though we do get
<ide> # successful compilation on that platform with Python 3.x
<del> if sys.platform != 'win32':
<add> if sys.platform != 'win32':
<ide> # check for sensible result of Fortran function; that means
<ide> # we can import the module name in Python and retrieve the
<ide> # result of the sum operation
<del> return_check = import_module(modname)
<del> calc_result = return_check.foo()
<del> assert_equal(calc_result, 15)
<add> return_check = import_module(modname)
<add> calc_result = return_check.foo()
<add> assert_equal(calc_result, 15)
<ide> # Removal from sys.modules, is not as such necessary. Even with
<ide> # removal, the module (dict) stays alive.
<del> del sys.modules[modname]
<add> del sys.modules[modname]
<ide>
<ide>
<ide> def test_f2py_init_compile_failure():
<ide> def test_f2py_init_compile_bad_cmd():
<ide> b'program test_f2py\nend program test_f2py',])
<ide> def test_compile_from_strings(tmpdir, fsource):
<ide> # Make sure we can compile str and bytes gh-12796
<del> cwd = os.getcwd()
<del> try:
<del> os.chdir(str(tmpdir))
<add> with util.switchdir(tmpdir):
<ide> ret_val = numpy.f2py.compile(
<del> fsource,
<del> modulename='test_compile_from_strings',
<del> extension='.f90')
<add> fsource,
<add> modulename='test_compile_from_strings',
<add> extension='.f90')
<ide> assert_equal(ret_val, 0)
<del> finally:
<del> os.chdir(cwd)
<ide><path>numpy/f2py/tests/util.py
<ide> import textwrap
<ide> import re
<ide> import pytest
<add>import contextlib
<ide>
<ide> from pathlib import Path
<ide> from numpy.compat import asbytes, asstr
<ide> def build_module(source_files, options=[], skip=[], only=[], module_name=None):
<ide>
<ide> """
<ide>
<del> code = ("import sys; sys.path = %s; import numpy.f2py as f2py2e; "
<del> "f2py2e.main()" % repr(sys.path))
<add> code = ("import sys; sys.path = %s; import numpy.f2py; "
<add> "numpy.f2py.main()" % repr(sys.path))
<ide>
<ide> d = get_module_dir()
<ide>
<ide> def getpath(*a):
<ide> # Package root
<ide> d = Path(__file__).parent.parent.resolve()
<ide> return d.joinpath(*a)
<add>
<add>@contextlib.contextmanager
<add>def switchdir(path):
<add> curpath = Path.cwd()
<add> os.chdir(path)
<add> try:
<add> yield
<add> finally:
<add> os.chdir(curpath) | 2 |
Python | Python | suppress messages from the browser | ade44385379127df5a4b75fa5c38a202fd819669 | <ide><path>test/test.py
<ide> ANAL = True
<ide> DEFAULT_MANIFEST_FILE = 'test_manifest.json'
<ide> EQLOG_FILE = 'eq.log'
<add>BROWSERLOG_FILE = 'browser.log'
<ide> REFDIR = 'ref'
<ide> TMPDIR = 'tmp'
<ide> VERBOSE = False
<ide> def __init__(self, browserRecord):
<ide> def setup(self):
<ide> self.tempDir = tempfile.mkdtemp()
<ide> self.profileDir = os.path.join(self.tempDir, "profile")
<add> self.browserLog = open(BROWSERLOG_FILE, "w")
<ide>
<ide> def teardown(self):
<ide> # If the browser is still running, wait up to ten seconds for it to quit
<ide> def teardown(self):
<ide> if self.tempDir is not None and os.path.exists(self.tempDir):
<ide> shutil.rmtree(self.tempDir)
<ide>
<add> self.browserLog.close()
<add>
<ide> def start(self, url):
<ide> raise Exception("Can't start BaseBrowserCommand")
<ide>
<ide> def start(self, url):
<ide> if platform.system() == "Darwin":
<ide> cmds.append("-foreground")
<ide> cmds.extend(["-no-remote", "-profile", self.profileDir, url])
<del> self.process = subprocess.Popen(cmds)
<add> self.process = subprocess.Popen(cmds, stdout = self.browserLog, stderr = self.browserLog)
<ide>
<ide> class ChromeBrowserCommand(BaseBrowserCommand):
<ide> def _fixupMacPath(self):
<ide> def start(self, url):
<ide> cmds = [self.path]
<ide> cmds.extend(["--user-data-dir=%s" % self.profileDir,
<ide> "--no-first-run", "--disable-sync", url])
<del> self.process = subprocess.Popen(cmds)
<add> self.process = subprocess.Popen(cmds, stdout = self.browserLog, stderr = self.browserLog)
<ide>
<ide> def makeBrowserCommand(browser):
<ide> path = browser["path"].lower() | 1 |
Python | Python | hack broken pipe error for python2 | c89fd19f660875e5c9cc7a7ec24c9f7e3977163e | <ide><path>bin/load_reddit.py
<ide> def main(path):
<ide>
<ide>
<ide> if __name__ == '__main__':
<add> import socket
<add> try:
<add> BrokenPipeError
<add> except NameError:
<add> BrokenPipeError = socket.error
<ide> try:
<ide> plac.call(main)
<ide> except BrokenPipeError: | 1 |
Java | Java | fix typos in handleradapter | 907e286e7703cf3e8c8e954774891b75d661e17d | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerAdapter.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 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> import javax.servlet.http.HttpServletResponse;
<ide>
<ide> /**
<del> * MVC framework SPI interface, allowing parameterization of core MVC workflow.
<add> * MVC framework SPI, allowing parameterization of the core MVC workflow.
<ide> *
<ide> * <p>Interface that must be implemented for each handler type to handle a request.
<ide> * This interface is used to allow the {@link DispatcherServlet} to be indefinitely
<del> * extensible. The DispatcherServlet accesses all installed handlers through this
<del> * interface, meaning that it does not contain code specific to any handler type.
<add> * extensible. The {@code DispatcherServlet} accesses all installed handlers through
<add> * this interface, meaning that it does not contain code specific to any handler type.
<ide> *
<ide> * <p>Note that a handler can be of type {@code Object}. This is to enable
<ide> * handlers from other frameworks to be integrated with this framework without
<del> * custom coding, as well as to allow for annotation handler objects that do
<del> * not obey any specific Java interface.
<add> * custom coding, as well as to allow for annotation-driven handler objects that
<add> * do not obey any specific Java interface.
<ide> *
<ide> * <p>This interface is not intended for application developers. It is available
<ide> * to handlers who want to develop their own web workflow.
<ide> *
<del> * <p>Note: HandlerAdaptger implementators may implement the
<del> * {@link org.springframework.core.Ordered} interface to be able to specify a
<del> * sorting order (and thus a priority) for getting applied by DispatcherServlet.
<add> * <p>Note: {@code HandlerAdapter} implementors may implement the {@link
<add> * org.springframework.core.Ordered} interface to be able to specify a sorting
<add> * order (and thus a priority) for getting applied by the {@code DispatcherServlet}.
<ide> * Non-Ordered instances get treated as lowest priority.
<ide> *
<ide> * @author Rod Johnson
<ide> public interface HandlerAdapter {
<ide>
<ide> /**
<del> * Given a handler instance, return whether or not this HandlerAdapter can
<del> * support it. Typical HandlerAdapters will base the decision on the handler
<add> * Given a handler instance, return whether or not this {@code HandlerAdapter}
<add> * can support it. Typical HandlerAdapters will base the decision on the handler
<ide> * type. HandlerAdapters will usually only support one handler type each.
<ide> * <p>A typical implementation:
<ide> * <p>{@code | 1 |
Javascript | Javascript | define html5 fields on input fields | fdfe8495f738c460b0f1595bc8a37a67e568ff0f | <ide><path>packages/ember-handlebars/lib/controls/text_area.js
<ide> Ember.TextArea = Ember.Component.extend(Ember.TextSupport, {
<ide> classNames: ['ember-text-area'],
<ide>
<ide> tagName: "textarea",
<del> attributeBindings: ['rows', 'cols', 'name'],
<add> attributeBindings: ['rows', 'cols', 'name', 'selectionEnd', 'selectionStart', 'wrap'],
<ide> rows: null,
<ide> cols: null,
<ide>
<ide><path>packages/ember-handlebars/lib/controls/text_field.js
<ide> Ember.TextField = Ember.Component.extend(Ember.TextSupport, {
<ide>
<ide> classNames: ['ember-text-field'],
<ide> tagName: "input",
<del> attributeBindings: ['type', 'value', 'size', 'pattern', 'name', 'min', 'max'],
<add> attributeBindings: ['type', 'value', 'size', 'pattern', 'name', 'min', 'max',
<add> 'accept', 'autocomplete', 'autosave', 'formaction',
<add> 'formenctype', 'formmethod', 'formnovalidate', 'formtarget',
<add> 'height', 'inputmode', 'list', 'multiple', 'pattern', 'step',
<add> 'width'],
<ide>
<ide> /**
<ide> The `value` attribute of the input element. As the user inputs text, this
<ide><path>packages/ember-handlebars/lib/controls/text_support.js
<ide> var get = Ember.get, set = Ember.set;
<ide> Ember.TextSupport = Ember.Mixin.create(Ember.TargetActionSupport, {
<ide> value: "",
<ide>
<del> attributeBindings: ['placeholder', 'disabled', 'maxlength', 'tabindex', 'readonly'],
<add> attributeBindings: ['placeholder', 'disabled', 'maxlength', 'tabindex', 'readonly',
<add> 'autofocus', 'form', 'selectionDirection', 'spellcheck', 'required'],
<ide> placeholder: null,
<ide> disabled: false,
<ide> maxlength: null, | 3 |
Ruby | Ruby | add tests for audit_conflicts | 84e3e0a6b87229067041da4e947ee4f352892b62 | <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb
<ide> class FooAT11 < Formula
<ide> expect(fa.problems).to be_empty
<ide> end
<ide> end
<add>
<add> describe "#audit_conflicts" do
<add> specify "it warns when conflicting with non-existing formula" do
<add> fa = formula_auditor "foo", <<~RUBY
<add> class Foo < Formula
<add> url "https://brew.sh/foo-1.0.tgz"
<add>
<add> conflicts_with "bar"
<add> end
<add> RUBY
<add>
<add> fa.audit_conflicts
<add>
<add> expect(fa.problems.first[:message])
<add> .to match("Can't find conflicting formula \"bar\"")
<add> end
<add>
<add> specify "it warns when conflicting with itself" do
<add> fa = formula_auditor "foo", <<~RUBY
<add> class Foo < Formula
<add> url "https://brew.sh/foo-1.0.tgz"
<add>
<add> conflicts_with "#{dir}/foo.rb"
<add> end
<add> RUBY
<add>
<add> fa.audit_conflicts
<add>
<add> expect(fa.problems.first[:message])
<add> .to match("Formula should not conflict with itself")
<add> end
<add>
<add> specify "it warns when another formula does not have a symmetric conflict" do
<add> formula_auditor "bar", <<~RUBY
<add> class Bar < Formula
<add> url "https://brew.sh/foo-1.0.tgz"
<add> end
<add> RUBY
<add>
<add> fa = formula_auditor "foo", <<~RUBY
<add> class Foo < Formula
<add> url "https://brew.sh/foo-1.0.tgz"
<add>
<add> conflicts_with "#{dir}/bar.rb"
<add> end
<add> RUBY
<add>
<add> fa.audit_conflicts
<add>
<add> expect(fa.problems.first[:message])
<add> .to match("Formula bar should also have a conflict declared with foo")
<add> end
<add> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | specify browsersets for testswarm directly | 53e31f478e1d88d056aa52f6575d200fe3dcf047 | <ide><path>build/tasks/testswarm.js
<ide> module.exports = function( grunt ) {
<ide> name: jobName,
<ide> runs: runs,
<ide> runMax: config.runMax,
<del> browserSets: "popular-no-old-ie"
<add> browserSets: [ "popular-no-old-ie", "ios" ]
<ide> }, function( err, passed ) {
<ide> if ( err ) {
<ide> grunt.log.error( err ); | 1 |
Javascript | Javascript | add failing spec for node.fs.write | e57c16bc2d72d23b2e897e3f79c4df607aa18a7b | <ide><path>test/mjsunit/test-fs-write.js
<add>include("mjsunit.js");
<add>
<add>var dirname = node.path.dirname(__filename);
<add>var fixtures = node.path.join(dirname, "fixtures");
<add>var path = node.path.join(fixtures, "write.txt");
<add>var expected = "hello";
<add>var found;
<add>
<add>node.fs.open(path, node.O_WRONLY | node.O_TRUNC | node.O_CREAT, 0644).addCallback(function (file) {
<add> node.fs.write(file, expected, 0, "utf8").addCallback(function() {
<add> node.fs.close(file).addCallback(function() {
<add> node.fs.cat(path, node.UTF8).addCallback(function(contents) {
<add> found = contents;
<add> node.fs.unlink(path).wait();
<add> });
<add> });
<add> });
<add>});
<add>
<add>process.addListener("exit", function () {
<add> assertEquals(expected, found);
<add>});
<add> | 1 |
PHP | PHP | use cake\http\serverrequest on tests | 69dcc122010c3a93e97221de39801554fd30be47 | <ide><path>tests/TestCase/Auth/BasicAuthenticateTest.php
<ide> use Cake\Auth\BasicAuthenticate;
<ide> use Cake\Controller\ComponentRegistry;
<ide> use Cake\Http\Response;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\I18n\Time;
<ide> use Cake\Network\Exception\UnauthorizedException;
<del>use Cake\Network\Request;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function testConstructor()
<ide> */
<ide> public function testAuthenticateNoData()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide>
<ide> $this->response->expects($this->never())
<ide> ->method('header');
<ide> public function testAuthenticateNoData()
<ide> */
<ide> public function testAuthenticateNoUsername()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => ['PHP_AUTH_PW' => 'foobar']
<ide> ]);
<ide> public function testAuthenticateNoUsername()
<ide> */
<ide> public function testAuthenticateNoPassword()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => ['PHP_AUTH_USER' => 'mariano']
<ide> ]);
<ide> public function testAuthenticateNoPassword()
<ide> */
<ide> public function testAuthenticateInjection()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => [
<ide> 'PHP_AUTH_USER' => '> 1',
<ide> public function testAuthenticateUsernameZero()
<ide> $User = TableRegistry::get('Users');
<ide> $User->updateAll(['username' => '0'], ['username' => 'mariano']);
<ide>
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = ['User' => [
<ide> 'user' => '0',
<ide> 'password' => 'password'
<ide> public function testAuthenticateUsernameZero()
<ide> */
<ide> public function testAuthenticateChallenge()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->addParams(['pass' => []]);
<ide>
<ide> try {
<ide> public function testAuthenticateChallenge()
<ide> */
<ide> public function testAuthenticateSuccess()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => [
<ide> 'PHP_AUTH_USER' => 'mariano',
<ide> public function testAuthenticateSuccess()
<ide> public function testAuthenticateFailReChallenge()
<ide> {
<ide> $this->auth->config('scope.username', 'nate');
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => [
<ide> 'PHP_AUTH_USER' => 'mariano',
<ide><path>tests/TestCase/Auth/ControllerAuthorizeTest.php
<ide> use Cake\Auth\ControllerAuthorize;
<ide> use Cake\Controller\ComponentRegistry;
<ide> use Cake\Controller\Controller;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> public function testControllerErrorOnMissingMethod()
<ide> public function testAuthorizeFailure()
<ide> {
<ide> $user = [];
<del> $request = new Request('/posts/index');
<add> $request = new ServerRequest('/posts/index');
<ide> $this->assertFalse($this->auth->authorize($user, $request));
<ide> }
<ide>
<ide> public function testAuthorizeFailure()
<ide> public function testAuthorizeSuccess()
<ide> {
<ide> $user = ['User' => ['username' => 'mark']];
<del> $request = new Request('/posts/index');
<add> $request = new ServerRequest('/posts/index');
<ide>
<ide> $this->controller->expects($this->once())
<ide> ->method('isAuthorized')
<ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php
<ide> use Cake\Controller\ComponentRegistry;
<ide> use Cake\Core\Configure;
<ide> use Cake\Http\Response;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\I18n\Time;
<ide> use Cake\Network\Exception\UnauthorizedException;
<del>use Cake\Network\Request;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function testConstructor()
<ide> */
<ide> public function testAuthenticateNoData()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide>
<ide> $this->response->expects($this->never())
<ide> ->method('header');
<ide> public function testAuthenticateNoData()
<ide> */
<ide> public function testAuthenticateWrongUsername()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->addParams(['pass' => []]);
<ide>
<ide> $data = [
<ide> public function testAuthenticateWrongUsername()
<ide> */
<ide> public function testAuthenticateChallenge()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => ['REQUEST_METHOD' => 'GET']
<ide> ]);
<ide> public function testAuthenticateChallenge()
<ide> */
<ide> public function testAuthenticateChallengeIncludesStaleAttributeOnStaleNonce()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => ['REQUEST_METHOD' => 'GET']
<ide> ]);
<ide> public function testAuthenticateChallengeIncludesStaleAttributeOnStaleNonce()
<ide> */
<ide> public function testAuthenticateFailsOnStaleNonce()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => ['REQUEST_METHOD' => 'GET']
<ide> ]);
<ide> public function testAuthenticateFailsOnStaleNonce()
<ide> */
<ide> public function testAuthenticateValidUsernamePasswordNoNonce()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => ['REQUEST_METHOD' => 'GET']
<ide> ]);
<ide> public function testAuthenticateValidUsernamePasswordNoNonce()
<ide> */
<ide> public function testAuthenticateSuccess()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => ['REQUEST_METHOD' => 'GET']
<ide> ]);
<ide> public function testAuthenticateSuccess()
<ide> */
<ide> public function testAuthenticateSuccessSimulatedRequestMethod()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'post' => ['_method' => 'PUT'],
<ide> 'environment' => ['REQUEST_METHOD' => 'GET']
<ide> public function testAuthenticateSuccessSimulatedRequestMethod()
<ide> public function testAuthenticateFailReChallenge()
<ide> {
<ide> $this->auth->config('scope.username', 'nate');
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'environment' => ['REQUEST_METHOD' => 'GET']
<ide> ]);
<ide> public function testAuthenticateFailReChallenge()
<ide> */
<ide> public function testLoginHeaders()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'environment' => ['SERVER_NAME' => 'localhost']
<ide> ]);
<ide> $this->auth = new DigestAuthenticate($this->Collection, [
<ide><path>tests/TestCase/Auth/FormAuthenticateTest.php
<ide> use Cake\Controller\ComponentRegistry;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Http\Response;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\I18n\Time;
<del>use Cake\Network\Request;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide> public function testConstructor()
<ide> */
<ide> public function testAuthenticateNoData()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [];
<ide> $this->assertFalse($this->auth->authenticate($request, $this->response));
<ide> }
<ide> public function testAuthenticateNoData()
<ide> */
<ide> public function testAuthenticateNoUsername()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = ['password' => 'foobar'];
<ide> $this->assertFalse($this->auth->authenticate($request, $this->response));
<ide> }
<ide> public function testAuthenticateNoUsername()
<ide> */
<ide> public function testAuthenticateNoPassword()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = ['username' => 'mariano'];
<ide> $this->assertFalse($this->auth->authenticate($request, $this->response));
<ide> }
<ide> public function testAuthenticateNoPassword()
<ide> */
<ide> public function testAuthenticatePasswordIsFalse()
<ide> {
<del> $request = new Request('posts/index', false);
<add> $request = new ServerRequest('posts/index', false);
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => null
<ide> public function testAuthenticatePasswordIsFalse()
<ide> */
<ide> public function testAuthenticatePasswordIsEmptyString()
<ide> {
<del> $request = new Request('posts/index', false);
<add> $request = new ServerRequest('posts/index', false);
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => ''
<ide> public function testAuthenticatePasswordIsEmptyString()
<ide> */
<ide> public function testAuthenticateFieldsAreNotString()
<ide> {
<del> $request = new Request('posts/index', false);
<add> $request = new ServerRequest('posts/index', false);
<ide> $request->data = [
<ide> 'username' => ['mariano', 'phpnut'],
<ide> 'password' => 'my password'
<ide> public function testAuthenticateFieldsAreNotString()
<ide> */
<ide> public function testAuthenticateInjection()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => '> 1',
<ide> 'password' => "' OR 1 = 1"
<ide> public function testAuthenticateInjection()
<ide> */
<ide> public function testAuthenticateSuccess()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => 'password'
<ide> public function testAuthenticateIncludesVirtualFields()
<ide> $users = TableRegistry::get('Users');
<ide> $users->entityClass('TestApp\Model\Entity\VirtualUser');
<ide>
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => 'password'
<ide> public function testPluginModel()
<ide>
<ide> $this->auth->config('userModel', 'TestPlugin.AuthUsers');
<ide>
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => 'gwoo',
<ide> 'password' => 'cake'
<ide> public function testPluginModel()
<ide> */
<ide> public function testFinder()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => 'password'
<ide> public function testFinder()
<ide> */
<ide> public function testFinderOptions()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => 'password'
<ide> public function testPasswordHasherSettings()
<ide> ['username' => 'mariano']
<ide> );
<ide>
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => 'mypass'
<ide> public function testPasswordHasherSettings()
<ide> */
<ide> public function testAuthenticateNoRehash()
<ide> {
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => 'password'
<ide> public function testAuthenticateRehash()
<ide> $password = $this->auth->passwordHasher()->hash('password');
<ide> TableRegistry::get('Users')->updateAll(['password' => $password], []);
<ide>
<del> $request = new Request('posts/index');
<add> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide> 'username' => 'mariano',
<ide> 'password' => 'password'
<ide><path>tests/TestCase/Auth/Storage/SessionStorageTest.php
<ide>
<ide> use Cake\Auth\Storage\SessionStorage;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Session;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function setUp()
<ide> parent::setUp();
<ide>
<ide> $this->session = $this->getMockBuilder(Session::class)->getMock();
<del> $this->request = new Request(['session' => $this->session]);
<add> $this->request = new ServerRequest(['session' => $this->session]);
<ide> $this->response = new Response();
<ide> $this->storage = new SessionStorage($this->request, $this->response, ['key' => 'Auth.AuthUser']);
<ide> $this->user = ['id' => 1];
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> use Cake\Event\Event;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\Routing\Router;
<ide> use Cake\Routing\Route\InflectedRoute;
<ide> public function setUp()
<ide> $routes->fallbacks(InflectedRoute::class);
<ide> });
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->env('REQUEST_METHOD', 'GET');
<ide>
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> public function testLoginRedirectDifferentBaseUrl()
<ide> $this->Auth->session->delete('Auth');
<ide>
<ide> $url = '/posts/add';
<del> $this->Auth->request = $this->Controller->request = new Request($url);
<add> $this->Auth->request = $this->Controller->request = new ServerRequest($url);
<ide> $this->Auth->request->env('REQUEST_METHOD', 'GET');
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> $this->Auth->request->url = Router::normalize($url);
<ide> public function testNoLoginRedirectForAuthenticatedUser()
<ide> public function testDefaultToLoginRedirect()
<ide> {
<ide> $url = '/party/on';
<del> $this->Auth->request = $request = new Request($url);
<add> $this->Auth->request = $request = new ServerRequest($url);
<ide> $request->env('HTTP_REFERER', false);
<ide> $request->addParams(Router::parse($url));
<ide> $request->addPaths([
<ide> public function testRedirectToUnauthorizedRedirect()
<ide> ->setMethods(['set'])
<ide> ->setConstructorArgs([$this->Controller->components()])
<ide> ->getMock();
<del> $this->Auth->request = $request = new Request([
<add> $this->Auth->request = $request = new ServerRequest([
<ide> 'url' => $url,
<ide> 'session' => $this->Auth->session
<ide> ]);
<ide> public function testRedirectToUnauthorizedRedirectLoginAction()
<ide> ->setMethods(['set'])
<ide> ->setConstructorArgs([$this->Controller->components()])
<ide> ->getMock();
<del> $this->Auth->request = $request = new Request([
<add> $this->Auth->request = $request = new ServerRequest([
<ide> 'url' => $url,
<ide> 'session' => $this->Auth->session
<ide> ]);
<ide> public function testRedirectToUnauthorizedRedirectSuppressedAuthError()
<ide> $this->Auth->session = $this->getMockBuilder('Cake\Network\Session')
<ide> ->setMethods(['flash'])
<ide> ->getMock();
<del> $this->Auth->request = $Request = new Request($url);
<add> $this->Auth->request = $Request = new ServerRequest($url);
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> $this->Auth->config('authorize', ['Controller']);
<ide> $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
<ide> public function testRedirectToUnauthorizedRedirectSuppressedAuthError()
<ide> public function testForbiddenException()
<ide> {
<ide> $url = '/party/on';
<del> $this->Auth->request = $request = new Request($url);
<add> $this->Auth->request = $request = new ServerRequest($url);
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> $this->Auth->config([
<ide> 'authorize' => ['Controller'],
<ide> public function testNoRedirectOnLoginAction()
<ide> $controller->methods = ['login'];
<ide>
<ide> $url = '/AuthTest/login';
<del> $this->Auth->request = $controller->request = new Request($url);
<add> $this->Auth->request = $controller->request = new ServerRequest($url);
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> $this->Auth->config([
<ide> 'loginAction', ['controller' => 'AuthTest', 'action' => 'login'],
<ide> public function testAdminRoute()
<ide> */
<ide> public function testAjaxLogin()
<ide> {
<del> $this->Controller->request = new Request([
<add> $this->Controller->request = new ServerRequest([
<ide> 'url' => '/ajax_auth/add',
<ide> 'environment' => ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'],
<ide> ]);
<ide> public function testAjaxLogin()
<ide> */
<ide> public function testAjaxUnauthenticated()
<ide> {
<del> $this->Controller->request = new Request([
<add> $this->Controller->request = new ServerRequest([
<ide> 'url' => '/ajax_auth/add',
<ide> 'environment' => ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'],
<ide> ]);
<ide> public function testRedirectUrlWithBaseSet()
<ide> ]);
<ide>
<ide> $url = '/users/login';
<del> $this->Auth->request = $this->Controller->request = new Request($url);
<add> $this->Auth->request = $this->Controller->request = new ServerRequest($url);
<ide> $this->Auth->request->addParams(Router::parse($url));
<ide> $this->Auth->request->url = Router::normalize($url);
<ide>
<ide><path>tests/TestCase/Controller/Component/CookieComponentTest.php
<ide> use Cake\Controller\ComponentRegistry;
<ide> use Cake\Controller\Component\CookieComponent;
<ide> use Cake\Http\Response;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\I18n\Time;
<del>use Cake\Network\Request;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Security;
<ide>
<ide> public function setUp()
<ide> parent::setUp();
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<del> ->setConstructorArgs([new Request(), new Response()])
<add> ->setConstructorArgs([new ServerRequest(), new Response()])
<ide> ->getMock();
<ide> $controller->loadComponent('Cookie');
<ide> $this->Controller = $controller;
<ide><path>tests/TestCase/Controller/Component/CsrfComponentTest.php
<ide> use Cake\Controller\Component\CsrfComponent;
<ide> use Cake\Event\Event;
<ide> use Cake\Http\Response;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\I18n\Time;
<del>use Cake\Network\Request;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> public function testSettingCookie()
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => ['REQUEST_METHOD' => 'GET'],
<ide> 'webroot' => '/dir/',
<ide> ]);
<ide> public function testSafeMethodNoCsrfRequired($method)
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method,
<ide> 'HTTP_X_CSRF_TOKEN' => 'nope',
<ide> public function testValidTokenInHeader($method)
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method,
<ide> 'HTTP_X_CSRF_TOKEN' => 'testing123',
<ide> public function testInvalidTokenInHeader($method)
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method,
<ide> 'HTTP_X_CSRF_TOKEN' => 'nope',
<ide> public function testValidTokenRequestData($method)
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method,
<ide> ],
<ide> public function testInvalidTokenRequestData($method)
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method,
<ide> ],
<ide> public function testInvalidTokenRequestDataMissing()
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => 'POST',
<ide> ],
<ide> public function testInvalidTokenMissingCookie($method)
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => [
<ide> 'REQUEST_METHOD' => $method
<ide> ],
<ide> public function testCsrfValidationSkipsRequestAction()
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => ['REQUEST_METHOD' => 'POST'],
<ide> 'params' => ['requested' => 1],
<ide> 'post' => ['_csrfToken' => 'nope'],
<ide> public function testConfigurationCookieCreate()
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => ['REQUEST_METHOD' => 'GET'],
<ide> 'webroot' => '/dir/'
<ide> ]);
<ide> public function testConfigurationValidate()
<ide> $controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['redirect'])
<ide> ->getMock();
<del> $controller->request = new Request([
<add> $controller->request = new ServerRequest([
<ide> 'environment' => ['REQUEST_METHOD' => 'POST'],
<ide> 'cookies' => ['csrfToken' => 'nope', 'token' => 'yes'],
<ide> 'post' => ['_csrfToken' => 'no match', 'token' => 'yes'],
<ide><path>tests/TestCase/Controller/Component/FlashComponentTest.php
<ide> use Cake\Controller\Component\FlashComponent;
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Session;
<ide> use Cake\TestSuite\TestCase;
<ide> use Exception;
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<ide> Configure::write('App.namespace', 'TestApp');
<del> $this->Controller = new Controller(new Request(['session' => new Session()]));
<add> $this->Controller = new Controller(new ServerRequest(['session' => new Session()]));
<ide> $this->ComponentRegistry = new ComponentRegistry($this->Controller);
<ide> $this->Flash = new FlashComponent($this->ComponentRegistry);
<ide> $this->Session = new Session();
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Datasource\ConnectionManager;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Exception\NotFoundException;
<del>use Cake\Network\Request;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide> public function setUp()
<ide>
<ide> Configure::write('App.namespace', 'TestApp');
<ide>
<del> $this->request = new Request('controller_posts/index');
<add> $this->request = new ServerRequest('controller_posts/index');
<ide> $this->request->params['pass'] = [];
<ide> $controller = new Controller($this->request);
<ide> $registry = new ComponentRegistry($controller);
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> use Cake\Controller\Component\RequestHandlerComponent;
<ide> use Cake\Core\Configure;
<ide> use Cake\Event\Event;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> public function setUp()
<ide> */
<ide> protected function _init()
<ide> {
<del> $request = new Request('controller_posts/index');
<add> $request = new ServerRequest('controller_posts/index');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['_sendHeader', 'stop'])
<ide> ->getMock();
<ide> public function testInitializeContentTypeAndExtensionMismatch()
<ide> $extensions = Router::extensions();
<ide> Router::extensions('xml', false);
<ide>
<del> $this->Controller->request = $this->getMockBuilder('Cake\Network\Request')
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['accepts'])
<ide> ->getMock();
<ide> $this->Controller->request->expects($this->any())
<ide> public function testStartupCallback()
<ide> $event = new Event('Controller.beforeRender', $this->Controller);
<ide> $_SERVER['REQUEST_METHOD'] = 'PUT';
<ide> $_SERVER['CONTENT_TYPE'] = 'application/xml';
<del> $this->Controller->request = new Request();
<add> $this->Controller->request = new ServerRequest();
<ide> $this->RequestHandler->beforeRender($event);
<ide> $this->assertTrue(is_array($this->Controller->request->data));
<ide> $this->assertFalse(is_object($this->Controller->request->data));
<ide> public function testStartupCallbackCharset()
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $_SERVER['REQUEST_METHOD'] = 'PUT';
<ide> $_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8';
<del> $this->Controller->request = new Request();
<add> $this->Controller->request = new ServerRequest();
<ide> $this->RequestHandler->startup($event);
<ide> $this->assertTrue(is_array($this->Controller->request->data));
<ide> $this->assertFalse(is_object($this->Controller->request->data));
<ide> public function testStartupCallbackCharset()
<ide> */
<ide> public function testStartupProcessData()
<ide> {
<del> $this->Controller->request = new Request();
<add> $this->Controller->request = new ServerRequest();
<ide> $this->Controller->request->env('REQUEST_METHOD', 'POST');
<ide> $this->Controller->request->env('CONTENT_TYPE', 'application/json');
<ide>
<ide> public function testStartupProcessData()
<ide> */
<ide> public function testStartupIgnoreFileAsXml()
<ide> {
<del> $this->Controller->request = new Request(['input' => '/dev/random']);
<add> $this->Controller->request = new ServerRequest(['input' => '/dev/random']);
<ide> $this->Controller->request->env('REQUEST_METHOD', 'POST');
<ide> $this->Controller->request->env('CONTENT_TYPE', 'application/xml');
<ide>
<ide> public function testStartupIgnoreFileAsXml()
<ide> public function testStartupCustomTypeProcess()
<ide> {
<ide> $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED);
<del> $this->Controller->request = new Request([
<add> $this->Controller->request = new ServerRequest([
<ide> 'input' => '"A","csv","string"'
<ide> ]);
<ide> $this->RequestHandler->addInputType('csv', ['str_getcsv']);
<ide> public function testRenderAs()
<ide> */
<ide> public function testRenderAsWithAttachment()
<ide> {
<del> $this->RequestHandler->request = $this->getMockBuilder('Cake\Network\Request')
<add> $this->RequestHandler->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['parseAccept'])
<ide> ->getMock();
<ide> $this->RequestHandler->request->expects($this->any())
<ide> public function testRespondAsWithAttachment()
<ide> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['type', 'download'])
<ide> ->getMock();
<del> $this->Controller->request = $this->getMockBuilder('Cake\Network\Request')
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['parseAccept'])
<ide> ->getMock();
<ide>
<ide> public function testResponseContentType()
<ide> */
<ide> public function testMobileDeviceDetection()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Network\Request')
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['is'])
<ide> ->getMock();
<ide> $request->expects($this->once())->method('is')
<ide> public function testAjaxRedirectAsRequestAction()
<ide> $event = new Event('Controller.beforeRedirect', $this->Controller);
<ide>
<ide> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Network\Request')
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['is'])
<ide> ->getMock();
<ide> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<ide> public function testAjaxRedirectAsRequestActionWithQueryString()
<ide> Router::connect('/:controller/:action');
<ide>
<ide> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Network\Request')
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['is'])
<ide> ->getMock();
<ide> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<ide> public function testAjaxRedirectAsRequestActionWithCookieData()
<ide> $event = new Event('Controller.beforeRedirect', $this->Controller);
<ide>
<ide> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Network\Request')
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['is'])
<ide> ->getMock();
<ide> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<ide> public function testAjaxRedirectAsRequestActionStatusCode()
<ide> $event = new Event('Controller.beforeRedirect', $this->Controller);
<ide>
<ide> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Network\Request')
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['is'])
<ide> ->getMock();
<ide> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<ide> public function testAjaxRedirectAsRequestActionStillRenderingLayout()
<ide> $event = new Event('Controller.beforeRedirect', $this->Controller);
<ide>
<ide> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Network\Request')
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['is'])
<ide> ->getMock();
<ide> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<ide> public function testBeforeRedirectCallbackWithArrayUrl()
<ide> ]);
<ide>
<ide> $RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = new Request('posts/index');
<add> $this->Controller->request = new ServerRequest('posts/index');
<ide>
<ide> ob_start();
<ide> $RequestHandler->beforeRedirect(
<ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php
<ide> use Cake\Controller\Exception\SecurityException;
<ide> use Cake\Core\Configure;
<ide> use Cake\Event\Event;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Session;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Security;
<ide> public function setUp()
<ide>
<ide> $this->server = $_SERVER;
<ide> $session = new Session();
<del> $request = $this->getMockBuilder('Cake\Network\Request')
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['here'])
<ide> ->setConstructorArgs(['posts/index'])
<ide> ->getMock();
<ide> public function validatePost($expectedException = null, $expectedExceptionMessag
<ide> */
<ide> public function testBlackholeWithBrokenCallback()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts/index',
<ide> 'session' => $this->Security->session
<ide> ]);
<ide> public function testValidatePostUrlAsHashInput()
<ide> ];
<ide> $this->assertTrue($this->validatePost());
<ide>
<del> $request = $this->getMockBuilder('Cake\Network\Request')
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['here'])
<ide> ->getMock();
<ide> $request->expects($this->at(0))
<ide><path>tests/TestCase/Controller/ComponentRegistryTest.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> class ComponentRegistryTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $controller = new Controller(new Request(), new Response());
<add> $controller = new Controller(new ServerRequest(), new Response());
<ide> $this->Components = new ComponentRegistry($controller);
<ide> }
<ide>
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> use Cake\Core\Plugin;
<ide> use Cake\Event\Event;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> public function tearDown()
<ide> */
<ide> public function testTableAutoload()
<ide> {
<del> $request = new Request('controller_posts/index');
<add> $request = new ServerRequest('controller_posts/index');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $Controller = new Controller($request, $response);
<ide> $Controller->modelClass = 'SiteArticles';
<ide> public function testTableAutoload()
<ide> */
<ide> public function testLoadModel()
<ide> {
<del> $request = new Request('controller_posts/index');
<add> $request = new ServerRequest('controller_posts/index');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $Controller = new Controller($request, $response);
<ide>
<ide> public function testConstructSetModelClass()
<ide> {
<ide> Plugin::load('TestPlugin');
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $response = new Response();
<ide> $controller = new \TestApp\Controller\PostsController($request, $response);
<ide> $this->assertEquals('Posts', $controller->modelClass);
<ide> public function testConstructClassesWithComponents()
<ide> {
<ide> Plugin::load('TestPlugin');
<ide>
<del> $Controller = new TestPluginController(new Request(), new Response());
<add> $Controller = new TestPluginController(new ServerRequest(), new Response());
<ide> $Controller->loadComponent('TestPlugin.Other');
<ide>
<ide> $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $Controller->Other);
<ide> public function testRender()
<ide> {
<ide> Plugin::load('TestPlugin');
<ide>
<del> $request = new Request('controller_posts/index');
<add> $request = new ServerRequest('controller_posts/index');
<ide> $request->params['action'] = 'index';
<ide>
<ide> $Controller = new Controller($request, new Response());
<ide> public function testRender()
<ide> */
<ide> public function testBeforeRenderCallbackChangingViewClass()
<ide> {
<del> $Controller = new Controller(new Request, new Response());
<add> $Controller = new Controller(new ServerRequest, new Response());
<ide>
<ide> $Controller->eventManager()->on('Controller.beforeRender', function (Event $event) {
<ide> $controller = $event->subject();
<ide> public function testBeforeRenderCallbackChangingViewClass()
<ide> */
<ide> public function testBeforeRenderEventCancelsRender()
<ide> {
<del> $Controller = new Controller(new Request, new Response());
<add> $Controller = new Controller(new ServerRequest, new Response());
<ide>
<ide> $Controller->eventManager()->on('Controller.beforeRender', function (Event $event) {
<ide> return false;
<ide> public function testRedirectBeforeRedirectListenerReturnResponse()
<ide> */
<ide> public function testMergeVars()
<ide> {
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $TestController = new TestController($request);
<ide>
<ide> $expected = [
<ide> public function testMergeVars()
<ide> */
<ide> public function testReferer()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Network\Request')
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['referer'])
<ide> ->getMock();
<ide> $request->expects($this->any())->method('referer')
<ide> public function testReferer()
<ide> $result = $Controller->referer(null, true);
<ide> $this->assertEquals('/posts/index', $result);
<ide>
<del> $request = $this->getMockBuilder('Cake\Network\Request')
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['referer'])
<ide> ->getMock();
<ide> $request->expects($this->any())->method('referer')
<ide> public function testReferer()
<ide> $result = $Controller->referer(['controller' => 'posts', 'action' => 'index'], true);
<ide> $this->assertEquals('/posts/index', $result);
<ide>
<del> $request = $this->getMockBuilder('Cake\Network\Request')
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['referer'])
<ide> ->getMock();
<ide>
<ide> public function testReferer()
<ide> */
<ide> public function testRefererSlash()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Network\Request')
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['referer'])
<ide> ->getMock();
<ide> $request->base = '/base';
<ide> public function testRefererSlash()
<ide> */
<ide> public function testSetAction()
<ide> {
<del> $request = new Request('controller_posts/index');
<add> $request = new ServerRequest('controller_posts/index');
<ide>
<ide> $TestController = new TestController($request);
<ide> $TestController->setAction('view', 1, 2);
<ide> public function testShutdownProcess()
<ide> */
<ide> public function testPaginate()
<ide> {
<del> $request = new Request('controller_posts/index');
<add> $request = new ServerRequest('controller_posts/index');
<ide> $request->params['pass'] = [];
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['httpCodes'])
<ide> public function testPaginate()
<ide> */
<ide> public function testPaginateUsesModelClass()
<ide> {
<del> $request = new Request('controller_posts/index');
<add> $request = new ServerRequest('controller_posts/index');
<ide> $request->params['pass'] = [];
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['httpCodes'])
<ide> public function testPaginateUsesModelClass()
<ide> */
<ide> public function testInvokeActionMissingAction()
<ide> {
<del> $url = new Request('test/missing');
<add> $url = new ServerRequest('test/missing');
<ide> $url->addParams(['controller' => 'Test', 'action' => 'missing']);
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> public function testInvokeActionMissingAction()
<ide> */
<ide> public function testInvokeActionPrivate()
<ide> {
<del> $url = new Request('test/private_m/');
<add> $url = new ServerRequest('test/private_m/');
<ide> $url->addParams(['controller' => 'Test', 'action' => 'private_m']);
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> public function testInvokeActionPrivate()
<ide> */
<ide> public function testInvokeActionProtected()
<ide> {
<del> $url = new Request('test/protected_m/');
<add> $url = new ServerRequest('test/protected_m/');
<ide> $url->addParams(['controller' => 'Test', 'action' => 'protected_m']);
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> public function testInvokeActionProtected()
<ide> */
<ide> public function testInvokeActionBaseMethods()
<ide> {
<del> $url = new Request('test/redirect/');
<add> $url = new ServerRequest('test/redirect/');
<ide> $url->addParams(['controller' => 'Test', 'action' => 'redirect']);
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> public function testInvokeActionBaseMethods()
<ide> */
<ide> public function testInvokeActionReturnValue()
<ide> {
<del> $url = new Request('test/returner/');
<add> $url = new ServerRequest('test/returner/');
<ide> $url->addParams([
<ide> 'controller' => 'Test',
<ide> 'action' => 'returner',
<ide> public function testInvokeActionReturnValue()
<ide> */
<ide> public function testInvokeActionWithPassedParams()
<ide> {
<del> $url = new Request('test/index/1/2');
<add> $url = new ServerRequest('test/index/1/2');
<ide> $url->addParams([
<ide> 'controller' => 'Test',
<ide> 'action' => 'index',
<ide> public function testInvokeActionWithPassedParams()
<ide> */
<ide> public function testViewPathConventions()
<ide> {
<del> $request = new Request('admin/posts');
<add> $request = new ServerRequest('admin/posts');
<ide> $request->addParams([
<ide> 'prefix' => 'admin'
<ide> ]);
<ide> public function testViewPathConventions()
<ide> $Controller->render();
<ide> $this->assertEquals('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->templatePath());
<ide>
<del> $request = new Request('pages/home');
<add> $request = new ServerRequest('pages/home');
<ide> $request->addParams([
<ide> 'prefix' => false
<ide> ]);
<ide> public function testViewPathConventions()
<ide> */
<ide> public function testComponents()
<ide> {
<del> $request = new Request('/');
<add> $request = new ServerRequest('/');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $controller = new TestController($request, $response);
<ide> public function testComponents()
<ide> */
<ide> public function testComponentsWithCustomRegistry()
<ide> {
<del> $request = new Request('/');
<add> $request = new ServerRequest('/');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
<ide> ->setMethods(['offsetGet'])
<ide> public function testComponentsWithCustomRegistry()
<ide> */
<ide> public function testLoadComponent()
<ide> {
<del> $request = new Request('/');
<add> $request = new ServerRequest('/');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $controller = new TestController($request, $response);
<ide> public function testLoadComponent()
<ide> */
<ide> public function testLoadComponentDuplicate()
<ide> {
<del> $request = new Request('/');
<add> $request = new ServerRequest('/');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $controller = new TestController($request, $response);
<ide> public function testLoadComponentDuplicate()
<ide> */
<ide> public function testIsAction()
<ide> {
<del> $request = new Request('/');
<add> $request = new ServerRequest('/');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $controller = new TestController($request, $response);
<ide>
<ide> public function testIsAction()
<ide> */
<ide> public function testDeclaredDeprecatedProperty()
<ide> {
<del> $controller = new TestController(new Request(), new Response());
<add> $controller = new TestController(new ServerRequest(), new Response());
<ide> $theme = $controller->theme;
<ide>
<ide> // @codingStandardsIgnoreStart
<ide><path>tests/TestCase/Error/ErrorHandlerTest.php
<ide> use Cake\Error;
<ide> use Cake\Error\ErrorHandler;
<ide> use Cake\Error\PHP7ErrorException;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Log\Log;
<ide> use Cake\Network\Exception\ForbiddenException;
<ide> use Cake\Network\Exception\NotFoundException;
<del>use Cake\Network\Request;
<ide> use Cake\Routing\Exception\MissingControllerException;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> public function setUp()
<ide> parent::setUp();
<ide> Router::reload();
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->base = '';
<ide> $request->env('HTTP_REFERER', '/referer');
<ide>
<ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> use Cake\Error\ExceptionRenderer;
<ide> use Cake\Event\Event;
<ide> use Cake\Event\EventManager;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Mailer\Exception\MissingActionException as MissingMailerActionException;
<ide> use Cake\Network\Exception\InternalErrorException;
<ide> use Cake\Network\Exception\MethodNotAllowedException;
<ide> use Cake\Network\Exception\NotFoundException;
<ide> use Cake\Network\Exception\SocketException;
<del>use Cake\Network\Request;
<ide> use Cake\ORM\Exception\MissingBehaviorException;
<ide> use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Exception\MissingControllerException;
<ide> public function setUp()
<ide> Configure::write('Config.language', 'eng');
<ide> Router::reload();
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->base = '';
<ide> Router::setRequestInfo($request);
<ide> Configure::write('debug', true);
<ide> public function testError400()
<ide> {
<ide> Router::reload();
<ide>
<del> $request = new Request('posts/view/1000');
<add> $request = new ServerRequest('posts/view/1000');
<ide> Router::setRequestInfo($request);
<ide>
<ide> $exception = new NotFoundException('Custom message');
<ide> public function testError400AsJson()
<ide> {
<ide> Router::reload();
<ide>
<del> $request = new Request('posts/view/1000?sort=title&direction=desc');
<add> $request = new ServerRequest('posts/view/1000?sort=title&direction=desc');
<ide> $request = $request->withHeader('Accept', 'application/json');
<ide> $request = $request->withHeader('Content-Type', 'application/json');
<ide> Router::setRequestInfo($request);
<ide> public function testError400NoInjection()
<ide> {
<ide> Router::reload();
<ide>
<del> $request = new Request('pages/<span id=333>pink</span></id><script>document.body.style.background = t=document.getElementById(333).innerHTML;window.alert(t);</script>');
<add> $request = new ServerRequest('pages/<span id=333>pink</span></id><script>document.body.style.background = t=document.getElementById(333).innerHTML;window.alert(t);</script>');
<ide> Router::setRequestInfo($request);
<ide>
<ide> $exception = new NotFoundException('Custom message');
<ide> public function testMissingRenderSafe()
<ide> ->setMethods(['render'])
<ide> ->getMock();
<ide> $ExceptionRenderer->controller->helpers = ['Fail', 'Boom'];
<del> $ExceptionRenderer->controller->request = new Request;
<add> $ExceptionRenderer->controller->request = new ServerRequest;
<ide> $ExceptionRenderer->controller->expects($this->at(0))
<ide> ->method('render')
<ide> ->with('missingHelper')
<ide> public function testRenderExceptionInBeforeRender()
<ide> $ExceptionRenderer->controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> ->setMethods(['beforeRender'])
<ide> ->getMock();
<del> $ExceptionRenderer->controller->request = new Request;
<add> $ExceptionRenderer->controller->request = new ServerRequest;
<ide> $ExceptionRenderer->controller->expects($this->any())
<ide> ->method('beforeRender')
<ide> ->will($this->throwException($exception));
<ide> function (Event $event) {
<ide> $event->subject()->viewBuilder()->setLayoutPath('boom');
<ide> }
<ide> );
<del> $ExceptionRenderer->controller->request = new Request;
<add> $ExceptionRenderer->controller->request = new ServerRequest;
<ide>
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $response->expects($this->once())
<ide> public function testMissingPluginRenderSafe()
<ide> ->setMethods(['render'])
<ide> ->getMock();
<ide> $ExceptionRenderer->controller->plugin = 'TestPlugin';
<del> $ExceptionRenderer->controller->request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $ExceptionRenderer->controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide>
<ide> $exception = new MissingPluginException(['plugin' => 'TestPlugin']);
<ide> $ExceptionRenderer->controller->expects($this->once())
<ide> public function testMissingPluginRenderSafeWithPlugin()
<ide> ->setMethods(['render'])
<ide> ->getMock();
<ide> $ExceptionRenderer->controller->plugin = 'TestPlugin';
<del> $ExceptionRenderer->controller->request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $ExceptionRenderer->controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide>
<ide> $exception = new MissingPluginException(['plugin' => 'TestPluginTwo']);
<ide> $ExceptionRenderer->controller->expects($this->once())
<ide><path>tests/TestCase/Http/ActionDispatcherTest.php
<ide> use Cake\Event\Event;
<ide> use Cake\Http\ActionDispatcher;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Session;
<ide> use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Filter\ControllerFactoryFilter;
<ide> public function testBeforeDispatchEventAbort()
<ide> ->method('beforeDispatch')
<ide> ->will($this->returnValue($response));
<ide>
<del> $req = new Request();
<add> $req = new ServerRequest();
<ide> $res = new Response();
<ide> $dispatcher->addFilter($filter);
<ide> $result = $dispatcher->dispatch($req, $res);
<ide> public function testDispatchAfterDispatchEventModifyResponse()
<ide> $event->data('response')->body('Filter body');
<ide> }));
<ide>
<del> $req = new Request([
<add> $req = new ServerRequest([
<ide> 'url' => '/cakes',
<ide> 'params' => [
<ide> 'plugin' => null,
<ide> public function testDispatchActionReturnResponseNoAfterDispatch()
<ide> $filter->expects($this->never())
<ide> ->method('afterDispatch');
<ide>
<del> $req = new Request([
<add> $req = new ServerRequest([
<ide> 'url' => '/cakes',
<ide> 'params' => [
<ide> 'plugin' => null,
<ide> public function testDispatchActionReturnResponseNoAfterDispatch()
<ide> public function testDispatchSetsRequestContext()
<ide> {
<ide> $this->assertNull(Router::getRequest());
<del> $req = new Request([
<add> $req = new ServerRequest([
<ide> 'url' => '/cakes',
<ide> 'params' => [
<ide> 'plugin' => null,
<ide> public function testDispatchSetsRequestContext()
<ide> */
<ide> public function testDispatchInvalidResponse()
<ide> {
<del> $req = new Request([
<add> $req = new ServerRequest([
<ide> 'url' => '/cakes',
<ide> 'params' => [
<ide> 'plugin' => null,
<ide> public function testDispatchInvalidResponse()
<ide> */
<ide> public function testDispatchAutoRender()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts',
<ide> 'params' => [
<ide> 'controller' => 'Posts',
<ide> public function testDispatchAutoRender()
<ide> */
<ide> public function testDispatchAutoRenderFalse()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'posts',
<ide> 'params' => [
<ide> 'controller' => 'Cakes',
<ide> public function testDispatchAutoRenderFalse()
<ide> */
<ide> public function testMissingController()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'some_controller/home',
<ide> 'params' => [
<ide> 'controller' => 'SomeController',
<ide> public function testMissingController()
<ide> */
<ide> public function testMissingControllerInterface()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> 'controller' => 'Interface',
<ide> public function testMissingControllerInterface()
<ide> */
<ide> public function testMissingControllerAbstract()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'abstract/index',
<ide> 'params' => [
<ide> 'controller' => 'Abstract',
<ide> public function testMissingControllerAbstract()
<ide> */
<ide> public function testMissingControllerLowercase()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'pages/home',
<ide> 'params' => [
<ide> 'plugin' => null,
<ide> public function testMissingControllerLowercase()
<ide> */
<ide> public function testStartupProcessAbort()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'cakes/index',
<ide> 'params' => [
<ide> 'plugin' => null,
<ide> public function testStartupProcessAbort()
<ide> */
<ide> public function testShutdownProcessResponse()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'cakes/index',
<ide> 'params' => [
<ide> 'plugin' => null,
<ide><path>tests/TestCase/Http/ControllerFactoryTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Http\ControllerFactory;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> public function setUp()
<ide> */
<ide> public function testApplicationController()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'cakes/index',
<ide> 'params' => [
<ide> 'controller' => 'Cakes',
<ide> public function testApplicationController()
<ide> */
<ide> public function testPrefixedAppController()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'admin/posts/index',
<ide> 'params' => [
<ide> 'prefix' => 'admin',
<ide> public function testPrefixedAppController()
<ide> */
<ide> public function testNestedPrefixedAppController()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'admin/sub/posts/index',
<ide> 'params' => [
<ide> 'prefix' => 'admin/sub',
<ide> public function testNestedPrefixedAppController()
<ide> */
<ide> public function testPluginController()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'test_plugin/test_plugin/index',
<ide> 'params' => [
<ide> 'plugin' => 'TestPlugin',
<ide> public function testPluginController()
<ide> */
<ide> public function testVendorPluginController()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'test_plugin_three/ovens/index',
<ide> 'params' => [
<ide> 'plugin' => 'Company/TestPluginThree',
<ide> public function testVendorPluginController()
<ide> */
<ide> public function testPrefixedPluginController()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'test_plugin/admin/comments',
<ide> 'params' => [
<ide> 'prefix' => 'admin',
<ide> public function testPrefixedPluginController()
<ide> */
<ide> public function testAbstractClassFailure()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'abstract/index',
<ide> 'params' => [
<ide> 'controller' => 'Abstract',
<ide> public function testAbstractClassFailure()
<ide> */
<ide> public function testInterfaceFailure()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> 'controller' => 'Interface',
<ide> public function testInterfaceFailure()
<ide> */
<ide> public function testMissingClassFailure()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> 'controller' => 'Invisible',
<ide> public function testMissingClassFailure()
<ide> */
<ide> public function testSlashedControllerFailure()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'admin/posts/index',
<ide> 'params' => [
<ide> 'controller' => 'Admin/Posts',
<ide> public function testSlashedControllerFailure()
<ide> */
<ide> public function testAbsoluteReferenceFailure()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> 'controller' => 'TestApp\Controller\CakesController',
<ide><path>tests/TestCase/Http/RequestTransformerTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Http\RequestTransformer;
<ide> use Cake\Http\ServerRequestFactory;
<del>use Cake\Network\Request;
<ide> use Cake\Network\Session;
<ide> use Cake\TestSuite\TestCase;
<ide> use Zend\Diactoros\Stream;
<ide><path>tests/TestCase/Http/ResponseTest.php
<ide> include_once CORE_TEST_CASES . DS . 'Http' . DS . 'server_mocks.php';
<ide>
<ide> use Cake\Http\Response;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Exception\NotFoundException;
<del>use Cake\Network\Request;
<ide> use Cake\TestSuite\TestCase;
<ide> use Zend\Diactoros\Stream;
<ide>
<ide> public function testCheckNotModifiedByEtagStar()
<ide> ->getMock();
<ide> $response->etag('something');
<ide> $response->expects($this->once())->method('notModified');
<del> $response->checkNotModified(new Request);
<add> $response->checkNotModified(new ServerRequest);
<ide> }
<ide>
<ide> /**
<ide> public function testCheckNotModifiedByEtagExact()
<ide> ->getMock();
<ide> $response->etag('something', true);
<ide> $response->expects($this->once())->method('notModified');
<del> $this->assertTrue($response->checkNotModified(new Request));
<add> $this->assertTrue($response->checkNotModified(new ServerRequest));
<ide> }
<ide>
<ide> /**
<ide> public function testCheckNotModifiedByEtagAndTime()
<ide> $response->etag('something', true);
<ide> $response->modified('2012-01-01 00:00:00');
<ide> $response->expects($this->once())->method('notModified');
<del> $this->assertTrue($response->checkNotModified(new Request));
<add> $this->assertTrue($response->checkNotModified(new ServerRequest));
<ide> }
<ide>
<ide> /**
<ide> public function testCheckNotModifiedByEtagAndTimeMismatch()
<ide> $response->etag('something', true);
<ide> $response->modified('2012-01-01 00:00:01');
<ide> $response->expects($this->never())->method('notModified');
<del> $this->assertFalse($response->checkNotModified(new Request));
<add> $this->assertFalse($response->checkNotModified(new ServerRequest));
<ide> }
<ide>
<ide> /**
<ide> public function testCheckNotModifiedByEtagMismatch()
<ide> $response->etag('something', true);
<ide> $response->modified('2012-01-01 00:00:00');
<ide> $response->expects($this->never())->method('notModified');
<del> $this->assertFalse($response->checkNotModified(new Request));
<add> $this->assertFalse($response->checkNotModified(new ServerRequest));
<ide> }
<ide>
<ide> /**
<ide> public function testCheckNotModifiedByTime()
<ide> ->getMock();
<ide> $response->modified('2012-01-01 00:00:00');
<ide> $response->expects($this->once())->method('notModified');
<del> $this->assertTrue($response->checkNotModified(new Request));
<add> $this->assertTrue($response->checkNotModified(new ServerRequest));
<ide> }
<ide>
<ide> /**
<ide> public function testCheckNotModifiedNoHints()
<ide> ->setMethods(['notModified'])
<ide> ->getMock();
<ide> $response->expects($this->never())->method('notModified');
<del> $this->assertFalse($response->checkNotModified(new Request));
<add> $this->assertFalse($response->checkNotModified(new ServerRequest));
<ide> }
<ide>
<ide> /**
<ide> public function testCors($request, $origin, $domains, $methods, $headers, $expec
<ide> */
<ide> public function corsData()
<ide> {
<del> $fooRequest = new Request();
<add> $fooRequest = new ServerRequest();
<ide>
<ide> $secureRequest = function () {
<del> $secureRequest = $this->getMockBuilder('Cake\Network\Request')
<add> $secureRequest = $this->getMockBuilder('Cake\Http\ServerRequest')
<ide> ->setMethods(['is'])
<ide> ->getMock();
<ide> $secureRequest->expects($this->any())
<ide><path>tests/TestCase/Http/ServerRequestTest.php
<ide> public function testParamWriting()
<ide> 'action' => 'index',
<ide> ]);
<ide>
<del> $this->assertInstanceOf('Cake\Network\Request', $request->param('some', 'thing'), 'Method has not returned $this');
<add> $this->assertInstanceOf('Cake\Http\ServerRequest', $request->param('some', 'thing'), 'Method has not returned $this');
<ide>
<ide> $request->param('Post.null', null);
<ide> $this->assertNull($request->params['Post']['null']);
<ide><path>tests/TestCase/Network/MoveToHttpTest.php
<ide> public function testResponse()
<ide> $this->assertInstanceOf('Cake\Http\Response', $response);
<ide> $this->assertInstanceOf('Cake\Network\Response', $response);
<ide> }
<add>
<ide> /**
<ide> * Tests the Cake\Http\ServerRequest loaded from Cake\Network\Request correctly
<ide> *
<ide> * @return void
<ide> */
<del>
<ide> public function testRequest()
<ide> {
<ide> $request = new NetworkRequest();
<ide><path>tests/TestCase/Routing/DispatcherFactoryTest.php
<ide> namespace Cake\Test\TestCase\Routing;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\DispatcherFactory;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function testCreate()
<ide> */
<ide> public function testCreateDispatchWithFilters()
<ide> {
<del> $url = new Request([
<add> $url = new ServerRequest([
<ide> 'url' => 'posts',
<ide> 'params' => [
<ide> 'controller' => 'Posts',
<ide><path>tests/TestCase/Routing/DispatcherFilterTest.php
<ide>
<ide> use Cake\Event\Event;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\DispatcherFilter;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function testConstructorInvalidWhen()
<ide> */
<ide> public function testMatchesWithFor()
<ide> {
<del> $request = new Request(['url' => '/articles/view']);
<add> $request = new ServerRequest(['url' => '/articles/view']);
<ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('request'));
<ide> $filter = new DispatcherFilter(['for' => '/articles']);
<ide> $this->assertTrue($filter->matches($event));
<ide>
<del> $request = new Request(['url' => '/blog/articles']);
<add> $request = new ServerRequest(['url' => '/blog/articles']);
<ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('request'));
<ide> $this->assertFalse($filter->matches($event), 'Does not start with /articles');
<ide>
<del> $request = new Request(['url' => '/articles/edit/1']);
<add> $request = new ServerRequest(['url' => '/articles/edit/1']);
<ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('request'));
<ide> $filter = new DispatcherFilter(['for' => 'preg:#^/articles/edit/\d+$#']);
<ide> $this->assertTrue($filter->matches($event));
<ide>
<del> $request = new Request(['url' => '/blog/articles/edit/1']);
<add> $request = new ServerRequest(['url' => '/blog/articles/edit/1']);
<ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('request'));
<ide> $this->assertFalse($filter->matches($event), 'Does not start with /articles');
<ide> }
<ide> public function testMatchesWithFor()
<ide> public function testMatchesWithWhen()
<ide> {
<ide> $matcher = function ($request, $response) {
<del> $this->assertInstanceOf('Cake\Network\Request', $request);
<add> $this->assertInstanceOf('Cake\Http\ServerRequest', $request);
<ide> $this->assertInstanceOf('Cake\Http\Response', $response);
<ide>
<ide> return true;
<ide> };
<ide>
<del> $request = new Request(['url' => '/articles/view']);
<add> $request = new ServerRequest(['url' => '/articles/view']);
<ide> $response = new Response();
<ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('response', 'request'));
<ide> $filter = new DispatcherFilter(['when' => $matcher]);
<ide> public function testMatchesWithWhen()
<ide> */
<ide> public function testMatchesWithForAndWhen()
<ide> {
<del> $request = new Request(['url' => '/articles/view']);
<add> $request = new ServerRequest(['url' => '/articles/view']);
<ide> $response = new Response();
<ide>
<ide> $matcher = function () {
<ide> public function testMatchesWithForAndWhen()
<ide> */
<ide> public function testImplementedEventsMethodName()
<ide> {
<del> $request = new Request(['url' => '/articles/view']);
<add> $request = new ServerRequest(['url' => '/articles/view']);
<ide> $response = new Response();
<ide>
<ide> $beforeEvent = new Event('Dispatcher.beforeDispatch', $this, compact('response', 'request'));
<ide> public function testImplementedEventsMethodName()
<ide> */
<ide> public function testHandleAppliesFor()
<ide> {
<del> $request = new Request(['url' => '/articles/view']);
<add> $request = new ServerRequest(['url' => '/articles/view']);
<ide> $response = new Response();
<ide>
<ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('response', 'request'));
<ide> public function testHandleAppliesFor()
<ide> */
<ide> public function testHandleAppliesWhen()
<ide> {
<del> $request = new Request(['url' => '/articles/view']);
<add> $request = new ServerRequest(['url' => '/articles/view']);
<ide> $response = new Response();
<ide>
<ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('response', 'request'));
<ide><path>tests/TestCase/Routing/DispatcherTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Session;
<ide> use Cake\Routing\Dispatcher;
<ide> use Cake\Routing\Filter\ControllerFactoryFilter;
<ide> public function tearDown()
<ide> */
<ide> public function testMissingController()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'some_controller/home',
<ide> 'params' => [
<ide> 'controller' => 'SomeController',
<ide> public function testMissingController()
<ide> */
<ide> public function testMissingControllerInterface()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'interface/index',
<ide> 'params' => [
<ide> 'controller' => 'Interface',
<ide> 'action' => 'index',
<ide> ]
<ide> ]);
<del> $url = new Request('dispatcher_test_interface/index');
<add> $url = new ServerRequest('dispatcher_test_interface/index');
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $this->dispatcher->dispatch($request, $response, ['return' => 1]);
<ide> }
<ide> public function testMissingControllerInterface()
<ide> */
<ide> public function testMissingControllerAbstract()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'abstract/index',
<ide> 'params' => [
<ide> 'controller' => 'Abstract',
<ide> public function testMissingControllerAbstract()
<ide> */
<ide> public function testMissingControllerLowercase()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'pages/home',
<ide> 'params' => [
<ide> 'controller' => 'somepages',
<ide> public function testMissingControllerLowercase()
<ide> */
<ide> public function testDispatchBasic()
<ide> {
<del> $url = new Request([
<add> $url = new ServerRequest([
<ide> 'url' => 'pages/home',
<ide> 'params' => [
<ide> 'controller' => 'Pages',
<ide> public function testDispatchBasic()
<ide> */
<ide> public function testDispatchActionReturnsResponse()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'some_pages/responseGenerator',
<ide> 'params' => [
<ide> 'controller' => 'SomePages',
<ide> public function testDispatchBadPluginName()
<ide> {
<ide> Plugin::load('TestPlugin');
<ide>
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'TestPlugin.Tests/index',
<ide> 'params' => [
<ide> 'plugin' => '',
<ide> public function testDispatchBadPluginName()
<ide> */
<ide> public function testDispatchBadName()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => 'TestApp%5CController%5CPostsController/index',
<ide> 'params' => [
<ide> 'plugin' => '',
<ide> public function testDispatcherFilter()
<ide> ->method('afterDispatch');
<ide> $this->dispatcher->addFilter($filter);
<ide>
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => '/',
<ide> 'params' => [
<ide> 'controller' => 'Pages',
<ide> public function testBeforeDispatchAbortDispatch()
<ide> $filter->expects($this->never())
<ide> ->method('afterDispatch');
<ide>
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => '/',
<ide> 'params' => [
<ide> 'controller' => 'Pages',
<ide> public function testAfterDispatchReplaceResponse()
<ide> ->method('afterDispatch')
<ide> ->will($this->returnValue($response));
<ide>
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'url' => '/posts',
<ide> 'params' => [
<ide> 'plugin' => null,
<ide><path>tests/TestCase/Routing/Filter/AssetFilterTest.php
<ide>
<ide> use Cake\Core\Plugin;
<ide> use Cake\Event\Event;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\Filter\AssetFilter;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function testNotModified()
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['send', 'checkNotModified'])
<ide> ->getMock();
<del> $request = new Request('test_theme/img/cake.power.gif');
<add> $request = new ServerRequest('test_theme/img/cake.power.gif');
<ide>
<ide> $response->expects($this->once())->method('checkNotModified')
<ide> ->with($request)
<ide> public function testNotModified()
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['_sendHeader', 'checkNotModified', 'send'])
<ide> ->getMock();
<del> $request = new Request('test_theme/img/cake.power.gif');
<add> $request = new ServerRequest('test_theme/img/cake.power.gif');
<ide>
<ide> $response->expects($this->once())->method('checkNotModified')
<ide> ->with($request)
<ide> public function test404OnDoubleSlash()
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['_sendHeader'])
<ide> ->getMock();
<del> $request = new Request('//index.php');
<add> $request = new ServerRequest('//index.php');
<ide> $event = new Event('Dispatcher.beforeRequest', $this, compact('request', 'response'));
<ide>
<ide> $this->assertNull($filter->beforeDispatch($event));
<ide> public function test404OnDoubleDot()
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['_sendHeader'])
<ide> ->getMock();
<del> $request = new Request('test_theme/../webroot/css/test_asset.css');
<add> $request = new ServerRequest('test_theme/../webroot/css/test_asset.css');
<ide> $event = new Event('Dispatcher.beforeRequest', $this, compact('request', 'response'));
<ide>
<ide> $this->assertNull($filter->beforeDispatch($event));
<ide> $this->assertFalse($event->isStopped());
<ide>
<del> $request = new Request('test_theme/%3e./webroot/css/test_asset.css');
<add> $request = new ServerRequest('test_theme/%3e./webroot/css/test_asset.css');
<ide> $event = new Event('Dispatcher.beforeRequest', $this, compact('request', 'response'));
<ide>
<ide> $this->assertNull($filter->beforeDispatch($event));
<ide> public function testAsset($url, $file)
<ide> $response = $this->getMockBuilder('Cake\Http\Response')
<ide> ->setMethods(['_sendHeader'])
<ide> ->getMock();
<del> $request = new Request($url);
<add> $request = new ServerRequest($url);
<ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('request', 'response'));
<ide>
<ide> $response = $filter->beforeDispatch($event);
<ide><path>tests/TestCase/Routing/Filter/ControllerFactoryFilterTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Event\Event;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\Filter\ControllerFactoryFilter;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function testBeforeDispatch()
<ide>
<ide> $filter = new ControllerFactoryFilter();
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $response = new Response();
<ide> $request->addParams(['prefix' => 'admin', 'controller' => 'Posts', 'action' => 'index']);
<ide> $event = new Event(__CLASS__, $this, compact('request', 'response'));
<ide><path>tests/TestCase/Routing/Filter/LocaleSelectorFilterTest.php
<ide> namespace Cake\Test\TestCase\Routing\Filter;
<ide>
<ide> use Cake\Event\Event;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\I18n\I18n;
<del>use Cake\Network\Request;
<ide> use Cake\Routing\Filter\LocaleSelectorFilter;
<ide> use Cake\TestSuite\TestCase;
<ide> use Locale;
<ide> public function tearDown()
<ide> public function testSimpleSelection()
<ide> {
<ide> $filter = new LocaleSelectorFilter();
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'environment' => ['HTTP_ACCEPT_LANGUAGE' => 'en-GB,en;q=0.8,es;q=0.6,da;q=0.4']
<ide> ]);
<ide> $filter->beforeDispatch(new Event('name', null, ['request' => $request]));
<ide> $this->assertEquals('en_GB', I18n::locale());
<ide>
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'environment' => ['HTTP_ACCEPT_LANGUAGE' => 'es_VE,en;q=0.8,es;q=0.6,da;q=0.4']
<ide> ]);
<ide> $filter->beforeDispatch(new Event('name', null, ['request' => $request]));
<ide> $this->assertEquals('es_VE', I18n::locale());
<ide>
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'environment' => ['HTTP_ACCEPT_LANGUAGE' => 'en;q=0.4,es;q=0.6,da;q=0.8']
<ide> ]);
<ide> $filter->beforeDispatch(new Event('name', null, ['request' => $request]));
<ide> public function testWithWhitelist()
<ide> $filter = new LocaleSelectorFilter([
<ide> 'locales' => ['en_CA', 'en_IN', 'es_VE']
<ide> ]);
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'environment' => [
<ide> 'HTTP_ACCEPT_LANGUAGE' => 'en-GB;q=0.8,es-VE;q=0.9,da-DK;q=0.4'
<ide> ]
<ide> public function testWithWhitelist()
<ide> $this->assertEquals('es_VE', I18n::locale());
<ide>
<ide> Locale::setDefault('en_US');
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'environment' => [
<ide> 'HTTP_ACCEPT_LANGUAGE' => 'en-GB;q=0.8,es-ES;q=0.9,da-DK;q=0.4'
<ide> ]
<ide><path>tests/TestCase/Routing/Filter/RoutingFilterTest.php
<ide>
<ide> use Cake\Event\Event;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\Filter\RoutingFilter;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> public function testBeforeDispatchSkipWhenControllerSet()
<ide> {
<ide> $filter = new RoutingFilter();
<ide>
<del> $request = new Request("/testcontroller/testaction/params1/params2/params3");
<add> $request = new ServerRequest("/testcontroller/testaction/params1/params2/params3");
<ide> $request->addParams(['controller' => 'articles']);
<ide> $event = new Event(__CLASS__, $this, compact('request'));
<ide> $filter->beforeDispatch($event);
<ide> public function testBeforeDispatchSetsParameters()
<ide> Router::connect('/:controller/:action/*');
<ide> $filter = new RoutingFilter();
<ide>
<del> $request = new Request("/testcontroller/testaction/params1/params2/params3");
<add> $request = new ServerRequest("/testcontroller/testaction/params1/params2/params3");
<ide> $event = new Event(__CLASS__, $this, compact('request'));
<ide> $filter->beforeDispatch($event);
<ide>
<ide> public function testBeforeDispatchRedirectRoute()
<ide> });
<ide> $filter = new RoutingFilter();
<ide>
<del> $request = new Request("/home");
<add> $request = new ServerRequest("/home");
<ide> $response = new Response();
<ide> $event = new Event(__CLASS__, $this, compact('request', 'response'));
<ide> $response = $filter->beforeDispatch($event);
<ide> public function testQueryStringOnRoot()
<ide>
<ide> $_GET = ['coffee' => 'life', 'sleep' => 'sissies'];
<ide> $filter = new RoutingFilter();
<del> $request = new Request('posts/home/?coffee=life&sleep=sissies');
<add> $request = new ServerRequest('posts/home/?coffee=life&sleep=sissies');
<ide>
<ide> $event = new Event(__CLASS__, $this, compact('request'));
<ide> $filter->beforeDispatch($event);
<ide> public function testQueryStringOnRoot()
<ide> $this->assertTrue(isset($request['url']['sleep']));
<ide> $this->assertTrue(isset($request['url']['coffee']));
<ide>
<del> $request = new Request('/?coffee=life&sleep=sissy');
<add> $request = new ServerRequest('/?coffee=life&sleep=sissy');
<ide>
<ide> $event = new Event(__CLASS__, $this, compact('request'));
<ide> $filter->beforeDispatch($event);
<ide><path>tests/TestCase/Routing/RequestActionTraitTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> public function testRequestActionParamParseAndPass()
<ide> */
<ide> public function testRequestActionBaseAndWebroot()
<ide> {
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'base' => '/subdir',
<ide> 'webroot' => '/subdir/'
<ide> ]);
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Http\ServerRequestFactory;
<del>use Cake\Network\Request;
<ide> use Cake\Routing\Router;
<ide> use Cake\Routing\Route\Route;
<ide> use Cake\TestSuite\TestCase;
<ide> public function testBaseUrlWithBasePath()
<ide> public function testCurrentUrlWithBasePath()
<ide> {
<ide> Router::fullBaseUrl('http://example.com');
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'action' => 'view',
<ide> 'plugin' => null,
<ide> public function testUrlNormalization()
<ide> $result = Router::normalize('/recipe/recipes/add');
<ide> $this->assertEquals('/recipe/recipes/add', $result);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->base = '/us';
<ide> Router::setRequestInfo($request);
<ide> $result = Router::normalize('/us/users/logout/');
<ide> $this->assertEquals('/users/logout', $result);
<ide>
<ide> Router::reload();
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->base = '/cake_12';
<ide> Router::setRequestInfo($request);
<ide> $result = Router::normalize('/cake_12/users/logout/');
<ide> public function testUrlNormalization()
<ide> $_back = Configure::read('App.fullBaseUrl');
<ide> Configure::write('App.fullBaseUrl', '/');
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->base = '/';
<ide> Router::setRequestInfo($request);
<ide> $result = Router::normalize('users/login');
<ide> $this->assertEquals('/users/login', $result);
<ide> Configure::write('App.fullBaseUrl', $_back);
<ide>
<ide> Router::reload();
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->base = 'beer';
<ide> Router::setRequestInfo($request);
<ide> $result = Router::normalize('beer/admin/beers_tags/add');
<ide> public function testUrlNormalization()
<ide> public function testUrlGenerationWithBasePath()
<ide> {
<ide> Router::connect('/:controller/:action/*');
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'action' => 'index',
<ide> 'plugin' => null,
<ide> public function testUrlGenerationBasic()
<ide>
<ide> Router::reload();
<ide> Router::connect('/:controller/:action');
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'action' => 'index',
<ide> 'plugin' => null,
<ide> public function testUrlGenerationBasic()
<ide>
<ide> Router::reload();
<ide> Router::connect('/:controller', ['action' => 'index']);
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'action' => 'index',
<ide> 'plugin' => 'myplugin',
<ide> public function testUrlGenerationWithPrefix()
<ide> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<ide> Router::extensions('rss', false);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'controller' => 'registrations',
<ide> 'action' => 'admin_index',
<ide> public function testUrlGenerationWithPrefix()
<ide> Router::connect('/admin/subscriptions/:action/*', ['controller' => 'subscribe', 'prefix' => 'admin']);
<ide> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'action' => 'index',
<ide> 'plugin' => null,
<ide> public function testUrlGenerationWithPrefix()
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> Router::reload();
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'prefix' => 'admin',
<ide> 'action' => 'index',
<ide> public function testUrlGenerationWithPrefix()
<ide> Router::reload();
<ide> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'plugin' => null,
<ide> 'controller' => 'pages',
<ide> public function testUrlGenerationWithPrefix()
<ide>
<ide> Router::reload();
<ide> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'plugin' => null,
<ide> 'controller' => 'pages',
<ide> public function testUrlGenerationWithPrefix()
<ide>
<ide> Router::reload();
<ide> Router::connect('/admin/:controller/:action/:id', ['prefix' => 'admin'], ['id' => '[0-9]+']);
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null,
<ide> public function testUrlGenerationWithPrefix()
<ide> Router::reload();
<ide> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'pages', 'action' => 'add', 'prefix' => 'admin',
<ide> public function testUrlGenerationWithPrefix()
<ide> Router::reload();
<ide> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'pages', 'action' => 'edit', 'prefix' => 'admin',
<ide> public function testUrlGenerationWithExtensionInCurrentRequest()
<ide> Router::scope('/', function ($r) {
<ide> $r->fallbacks('InflectedRoute');
<ide> });
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams(['controller' => 'Tasks', 'action' => 'index', '_ext' => 'rss']);
<ide> Router::pushRequest($request);
<ide>
<ide> public function testDuplicateNamedRouteException()
<ide> public function testUrlGenerationWithUrlFilter()
<ide> {
<ide> Router::connect('/:lang/:controller/:action/*');
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'lang' => 'en',
<ide> 'controller' => 'posts',
<ide> public function testUrlGenerationWithUrlFilter()
<ide> public function testUrlParamPersistence()
<ide> {
<ide> Router::connect('/:lang/:controller/:action/*', [], ['persist' => ['lang']]);
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'lang' => 'en',
<ide> 'controller' => 'posts',
<ide> public function testCanLeavePlugin()
<ide> {
<ide> Router::connect('/admin/:controller', ['action' => 'index', 'prefix' => 'admin']);
<ide> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'pass' => [],
<ide> public function testUrlParsing()
<ide> public function testParseRequest()
<ide> {
<ide> Router::connect('/articles/:action/*', ['controller' => 'Articles']);
<del> $request = new Request(['url' => '/articles/view/1']);
<add> $request = new ServerRequest(['url' => '/articles/view/1']);
<ide> $result = Router::parseRequest($request);
<ide> $expected = [
<ide> 'pass' => ['1'],
<ide> public function testUrlGenerationWithAutoPrefixes()
<ide> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<ide> Router::connect('/:controller/:action/*');
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'images', 'action' => 'index',
<ide> public function testGenerationWithSslOption()
<ide> {
<ide> Router::connect('/:controller/:action/*');
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->env('HTTP_HOST', 'localhost');
<ide> Router::pushRequest(
<ide> $request->addParams([
<ide> public function testGenerateWithSslInSsl()
<ide> {
<ide> Router::connect('/:controller/:action/*');
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->env('HTTP_HOST', 'localhost');
<ide> $request->env('HTTPS', 'on');
<ide> Router::pushRequest(
<ide> public function testPrefixRoutePersistence()
<ide> Router::connect('/protected/:controller/:action', ['prefix' => 'protected']);
<ide> Router::connect('/:controller/:action');
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null,
<ide> public function testPrefixOverride()
<ide> Router::connect('/admin/:controller/:action', ['prefix' => 'admin']);
<ide> Router::connect('/protected/:controller/:action', ['prefix' => 'protected']);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'images', 'action' => 'index', 'prefix' => 'protected',
<ide> public function testPrefixOverride()
<ide> $expected = '/admin/images/add';
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null,
<ide> public function testRemoveBase()
<ide> {
<ide> Router::connect('/:controller/:action');
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'controller', 'action' => 'index',
<ide> public function testParsingWithLiteralPrefixes()
<ide> Router::connect('/admin/:controller', $adminParams);
<ide> Router::connect('/admin/:controller/:action/*', $adminParams);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'controller', 'action' => 'index'
<ide> public function testParsingWithLiteralPrefixes()
<ide> Router::connect('/members/:controller/:action', $prefixParams);
<ide> Router::connect('/members/:controller/:action/*', $prefixParams);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'controller', 'action' => 'index',
<ide> public function testUrlWritingWithPrefixes()
<ide> $expected = '/company/users/login';
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null,
<ide> public function testUrlWritingWithPrefixesAndCustomRoutes()
<ide> '/admin/login',
<ide> ['controller' => 'users', 'action' => 'login', 'prefix' => 'admin']
<ide> );
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null, 'controller' => 'posts', 'action' => 'index',
<ide> public function testRegexRouteMatchUrl()
<ide> {
<ide> Router::connect('/:locale/:controller/:action/*', [], ['locale' => 'dan|eng']);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> Router::setRequestInfo(
<ide> $request->addParams([
<ide> 'plugin' => null,
<ide> public function testReverse()
<ide> $result = Router::reverse($params);
<ide> $this->assertEquals('/eng/posts/view/1?foo=bar&baz=quu', $result);
<ide>
<del> $request = new Request('/eng/posts/view/1');
<add> $request = new ServerRequest('/eng/posts/view/1');
<ide> $request->addParams([
<ide> 'lang' => 'eng',
<ide> 'controller' => 'posts',
<ide> public function testReverseWithExtension()
<ide> Router::connect('/:controller/:action/*');
<ide> Router::extensions('json', false);
<ide>
<del> $request = new Request('/posts/view/1.json');
<add> $request = new ServerRequest('/posts/view/1.json');
<ide> $request->addParams([
<ide> 'controller' => 'posts',
<ide> 'action' => 'view',
<ide> public function testSetRequestInfoLegacy()
<ide> */
<ide> public function testGetRequest()
<ide> {
<del> $requestA = new Request('/');
<del> $requestB = new Request('/posts');
<add> $requestA = new ServerRequest('/');
<add> $requestB = new ServerRequest('/posts');
<ide>
<ide> Router::pushRequest($requestA);
<ide> Router::pushRequest($requestB);
<ide> public function testUrlWithRequestAction()
<ide> Router::connect('/:controller', ['action' => 'index']);
<ide> Router::connect('/:controller/:action');
<ide>
<del> $firstRequest = new Request('/posts/index');
<add> $firstRequest = new ServerRequest('/posts/index');
<ide> $firstRequest->addParams([
<ide> 'plugin' => null,
<ide> 'controller' => 'posts',
<ide> 'action' => 'index'
<ide> ])->addPaths(['base' => '']);
<ide>
<del> $secondRequest = new Request('/posts/index');
<add> $secondRequest = new ServerRequest('/posts/index');
<ide> $secondRequest->addParams([
<ide> 'requested' => 1,
<ide> 'plugin' => null,
<ide> public function testRedirectWithAnotherRouteClass()
<ide> */
<ide> public function testParseNamedParameters()
<ide> {
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'controller' => 'posts',
<ide> 'action' => 'index',
<ide> ]);
<ide> $result = Router::parseNamedParams($request);
<ide> $this->assertSame([], $result->params['named']);
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'controller' => 'posts',
<ide> 'action' => 'index',
<ide> public function testUrlWithCollidingQueryString()
<ide> public function testSetRequestContextCakePHP()
<ide> {
<ide> Router::connect('/:controller/:action/*');
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'base' => '/subdir',
<ide> 'url' => 'articles/view/1'
<ide> ]);
<ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php
<ide> public function setUp()
<ide> DispatcherFactory::add('Routing');
<ide> DispatcherFactory::add('ControllerFactory');
<ide> $this->useHttpServer(false);
<del>
<del> // Load aliases, or tests fail in isolation.
<del> class_exists('Cake\Network\Request');
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/CellTest.php
<ide> public function setUp()
<ide> parent::setUp();
<ide> Configure::write('App.namespace', 'TestApp');
<ide> Plugin::load(['TestPlugin', 'TestTheme']);
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $this->View = new View($request, $response);
<ide> }
<ide> public function testCellInheritsHelperConfig()
<ide> */
<ide> public function testCellInheritsCustomViewClass()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $view = new CustomJsonView($request, $response);
<ide> $view->theme = 'Pretty';
<ide> public function testCellInheritsCustomViewClass()
<ide> */
<ide> public function testCellInheritsController()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $controller = new CellTraitTestController($request, $response);
<ide> $controller->viewBuilder()->setTheme('Pretty');
<ide><path>tests/TestCase/View/Form/ArrayContextTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\View\Form;
<ide>
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\Form\ArrayContext;
<ide>
<ide> class ArrayContextTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->request = new Request();
<add> $this->request = new ServerRequest();
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Form/EntityContextTest.php
<ide> use ArrayIterator;
<ide> use ArrayObject;
<ide> use Cake\Collection\Collection;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide> class EntityContextTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->request = new Request();
<add> $this->request = new ServerRequest();
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Form/FormContextTest.php
<ide> namespace Cake\Test\TestCase\View\Form;
<ide>
<ide> use Cake\Form\Form;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Validation\Validator;
<ide> use Cake\View\Form\FormContext;
<ide> class FormContextTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->request = new Request();
<add> $this->request = new ServerRequest();
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Helper/FlashHelperTest.php
<ide> namespace Cake\Test\TestCase\View\Helper;
<ide>
<ide> use Cake\Core\Plugin;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Network\Session;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\Helper\FlashHelper;
<ide> public function setUp()
<ide> parent::setUp();
<ide> $this->View = new View();
<ide> $session = new Session();
<del> $this->View->request = new Request(['session' => $session]);
<add> $this->View->request = new ServerRequest(['session' => $session]);
<ide> $this->Flash = new FlashHelper($this->View);
<ide>
<ide> $session->write([
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> use Cake\Collection\Collection;
<ide> use Cake\Core\Configure;
<ide> use Cake\Form\Form;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\Table;
<ide> use Cake\ORM\TableRegistry;
<ide> public function setUp()
<ide> $this->View = new View();
<ide>
<ide> $this->Form = new FormHelper($this->View);
<del> $request = new Request([
<add> $request = new ServerRequest([
<ide> 'webroot' => '',
<ide> 'base' => '',
<ide> 'url' => '/articles/add',
<ide> public function testAddContextProvider()
<ide> $context = 'My data';
<ide> $stub = $this->getMockBuilder('Cake\View\Form\ContextInterface')->getMock();
<ide> $this->Form->addContextProvider('test', function ($request, $data) use ($context, $stub) {
<del> $this->assertInstanceOf('Cake\Network\Request', $request);
<add> $this->assertInstanceOf('Cake\Http\ServerRequest', $request);
<ide> $this->assertEquals($context, $data['entity']);
<ide>
<ide> return $stub;
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Filesystem\File;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\Helper\HtmlHelper;
<ide> public function setUp()
<ide> ->setMethods(['append'])
<ide> ->getMock();
<ide> $this->Html = new HtmlHelper($this->View);
<del> $this->Html->request = new Request([
<add> $this->Html->request = new ServerRequest([
<ide> 'webroot' => '',
<ide> ]);
<ide> $this->Html->Url->request = $this->Html->request;
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> namespace Cake\Test\TestCase\View\Helper;
<ide>
<ide> use Cake\Core\Configure;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\I18n\I18n;
<del>use Cake\Network\Request;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\Helper\PaginatorHelper;
<ide> public function setUp()
<ide> Configure::write('Config.language', 'eng');
<ide> $this->View = new View();
<ide> $this->Paginator = new PaginatorHelper($this->View);
<del> $this->Paginator->request = new Request();
<add> $this->Paginator->request = new ServerRequest();
<ide> $this->Paginator->request->addParams([
<ide> 'paging' => [
<ide> 'Article' => [
<ide> public function testNumbersRouting()
<ide> ]
<ide> ];
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $request->addParams([
<ide> 'controller' => 'clients', 'action' => 'index', 'plugin' => null
<ide> ]);
<ide> public function testTotal()
<ide> */
<ide> public function testNoDefaultModel()
<ide> {
<del> $this->Paginator->request = new Request();
<add> $this->Paginator->request = new ServerRequest();
<ide> $this->assertNull($this->Paginator->defaultModel());
<ide>
<ide> $this->Paginator->defaultModel('Article');
<ide><path>tests/TestCase/View/Helper/UrlHelperTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\Helper\UrlHelper;
<ide> public function setUp()
<ide> Router::reload();
<ide> $this->View = new View();
<ide> $this->Helper = new UrlHelper($this->View);
<del> $this->Helper->request = new Request();
<add> $this->Helper->request = new ServerRequest();
<ide>
<ide> Configure::write('App.namespace', 'TestApp');
<ide> Plugin::load(['TestTheme']);
<ide><path>tests/TestCase/View/JsonViewTest.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /**
<ide> public static function renderWithoutViewProvider()
<ide> */
<ide> public function testRenderWithoutView($data, $serialize, $jsonOptions, $expected)
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide>
<ide> public function testRenderWithoutView($data, $serialize, $jsonOptions, $expected
<ide> */
<ide> public function testRenderSerializeNoHelpers()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide>
<ide> public function testRenderSerializeNoHelpers()
<ide> */
<ide> public function testJsonpResponse()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide>
<ide> public function testJsonpResponse()
<ide> */
<ide> public function testRenderWithView()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $Controller->name = 'Posts';
<ide><path>tests/TestCase/View/ViewBuilderTest.php
<ide> public function testArrayPropertyMerge($property, $value)
<ide> */
<ide> public function testBuildComplete()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $events = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
<ide>
<ide><path>tests/TestCase/View/ViewTest.php
<ide> use Cake\Core\Plugin;
<ide> use Cake\Event\Event;
<ide> use Cake\Event\EventListenerInterface;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\View\Helper;
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<ide>
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> $this->Controller = new Controller($request);
<ide> $this->PostsController = new ViewPostsController($request);
<ide> $this->PostsController->index();
<ide> $this->View = $this->PostsController->createView();
<ide> $this->View->viewPath = 'Posts';
<ide>
<del> $themeRequest = new Request('posts/index');
<add> $themeRequest = new ServerRequest('posts/index');
<ide> $this->ThemeController = new Controller($themeRequest);
<ide> $this->ThemePostsController = new ThemePostsController($themeRequest);
<ide> $this->ThemePostsController->index();
<ide> public function tearDown()
<ide> */
<ide> public function testGetTemplate()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $viewOptions = [
<ide> public function testPluginGetTemplate()
<ide> */
<ide> public function testPluginGetTemplateAbsoluteFail()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $viewOptions = [
<ide> public function testGetViewFileNames()
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages'
<ide> ];
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $View = new TestView(null, null, null, $viewOptions);
<ide> public function testGetViewFileNameDirectoryTraversal()
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages',
<ide> ];
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $view = new TestView(null, null, null, $viewOptions);
<ide> public function testGetLayoutFileNameDirectoryTraversal()
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages',
<ide> ];
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $view = new TestView(null, null, null, $viewOptions);
<ide> public function testMissingTemplate()
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages'
<ide> ];
<del> $request = $this->getMockBuilder('Cake\Network\Request')->getMock();
<add> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<ide> $View = new TestView($request, $response, null, $viewOptions);
<ide><path>tests/TestCase/View/XmlViewTest.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Xml;
<ide>
<ide> public function setUp()
<ide> */
<ide> public function testRenderWithoutView()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $data = ['users' => ['user' => ['user1', 'user2']]];
<ide> public function testRenderWithoutView()
<ide> */
<ide> public function testRenderSerializeNoHelpers()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $Controller->helpers = ['Html'];
<ide> public function testRenderSerializeNoHelpers()
<ide> */
<ide> public function testRenderSerializeWithOptions()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $data = [
<ide> public function testRenderSerializeWithOptions()
<ide> */
<ide> public function testRenderSerializeWithString()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $data = [
<ide> public function testRenderSerializeWithString()
<ide> */
<ide> public function testRenderWithoutViewMultiple()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $data = ['no' => 'nope', 'user' => 'fake', 'list' => ['item1', 'item2']];
<ide> public function testRenderWithoutViewMultiple()
<ide> */
<ide> public function testRenderWithoutViewMultipleAndAlias()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $data = ['original_name' => 'my epic name', 'user' => 'fake', 'list' => ['item1', 'item2']];
<ide> public function testRenderWithoutViewMultipleAndAlias()
<ide> */
<ide> public function testRenderWithSerializeTrue()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $data = ['users' => ['user' => ['user1', 'user2']]];
<ide> public function testRenderWithSerializeTrue()
<ide> */
<ide> public function testRenderWithView()
<ide> {
<del> $Request = new Request();
<add> $Request = new ServerRequest();
<ide> $Response = new Response();
<ide> $Controller = new Controller($Request, $Response);
<ide> $Controller->name = 'Posts';
<ide><path>tests/test_app/TestApp/Auth/TestAuthenticate.php
<ide> use Cake\Auth\BaseAuthenticate;
<ide> use Cake\Event\Event;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide>
<ide> /**
<ide> * TestAuthenticate class
<ide> public function implementedEvents()
<ide> * @param \Cake\Http\Response $response
<ide> * @return array
<ide> */
<del> public function authenticate(Request $request, Response $response)
<add> public function authenticate(ServerRequest $request, Response $response)
<ide> {
<ide> return ['id' => 1, 'username' => 'admad'];
<ide> }
<ide><path>tests/test_app/TestApp/Error/TestAppsExceptionRenderer.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Error\ExceptionRenderer;
<ide> use Cake\Http\Response;
<del>use Cake\Network\Request;
<add>use Cake\Http\ServerRequest;
<ide> use Cake\Routing\Router;
<ide> use TestApp\Controller\TestAppsErrorController;
<ide>
<ide> class TestAppsExceptionRenderer extends ExceptionRenderer
<ide> protected function _getController()
<ide> {
<ide> if (!$request = Router::getRequest(true)) {
<del> $request = new Request();
<add> $request = new ServerRequest();
<ide> }
<ide> $response = new Response();
<ide> try { | 47 |
Javascript | Javascript | show error messages from uglifyjs | 5d107999d539746ecf23cf2ffef8d62b53a41c2a | <ide><path>lib/optimize/UglifyJsPlugin.js
<ide> UglifyJsPlugin.prototype.apply = function(compiler) {
<ide> } else {
<ide> compilation.errors.push(new Error(file + " from UglifyJs\n" + err.message + " [" + file + ":" + err.line + "," + err.col + "]"));
<ide> }
<add> } else if (err.msg) {
<add> compilation.errors.push(new Error(file + " from UglifyJs\n" + err.msg));
<ide> } else
<ide> compilation.errors.push(new Error(file + " from UglifyJs\n" + err.stack));
<ide> } finally { | 1 |
Javascript | Javascript | clean unused import modules | 9db8910e36d610977ac473fcc326f68ff3cb03a5 | <ide><path>Examples/UIExplorer/js/AnimatedGratuitousApp/AnExBobble.js
<ide> var React = require('react');
<ide> var ReactNative = require('react-native');
<ide> var {
<ide> Animated,
<del> Image,
<ide> PanResponder,
<ide> StyleSheet,
<ide> View,
<ide><path>Examples/UIExplorer/js/AnimatedGratuitousApp/AnExChained.js
<ide> var React = require('react');
<ide> var ReactNative = require('react-native');
<ide> var {
<ide> Animated,
<del> Image,
<ide> PanResponder,
<ide> StyleSheet,
<ide> View,
<ide><path>Examples/UIExplorer/js/AnimatedGratuitousApp/AnExTilt.js
<ide> var React = require('react');
<ide> var ReactNative = require('react-native');
<ide> var {
<ide> Animated,
<del> Image,
<ide> PanResponder,
<ide> StyleSheet,
<del> View,
<ide> } = ReactNative;
<ide>
<ide> class AnExTilt extends React.Component {
<ide><path>Examples/UIExplorer/js/ImageEditingExample.js
<ide> var {
<ide> CameraRoll,
<ide> Image,
<ide> ImageEditor,
<del> NativeModules,
<ide> Platform,
<ide> ScrollView,
<ide> StyleSheet,
<ide> Text,
<ide> TouchableHighlight,
<del> UIManager,
<ide> View,
<ide> } = ReactNative;
<ide>
<ide><path>Examples/UIExplorer/js/PanResponderExample.js
<ide> var {
<ide> PanResponder,
<ide> StyleSheet,
<ide> View,
<del> processColor,
<ide> } = ReactNative;
<ide>
<ide> var CIRCLE_SIZE = 80;
<ide><path>Examples/UIExplorer/js/PickerExample.js
<ide> const UIExplorerPage = require('UIExplorerPage');
<ide> const {
<ide> Picker,
<ide> Text,
<del> TouchableWithoutFeedback,
<ide> } = ReactNative;
<ide>
<ide> const Item = Picker.Item;
<ide><path>Examples/UIExplorer/js/PickerIOSExample.js
<ide> class PickerStyleExample extends React.Component {
<ide> };
<ide>
<ide> render() {
<del> var make = CAR_MAKES_AND_MODELS[this.state.carMake];
<del> var selectionString = make.name + ' ' + make.models[this.state.modelIndex];
<ide> return (
<ide> <PickerIOS
<ide> itemStyle={{fontSize: 25, color: 'red', textAlign: 'left', fontWeight: 'bold'}}
<ide><path>Examples/UIExplorer/js/TextExample.ios.js
<ide> exports.examples = [
<ide> return <AdjustingFontSize />;
<ide> },
<ide> }];
<del>
<del>var styles = StyleSheet.create({
<del> backgroundColorText: {
<del> margin: 5,
<del> marginBottom: 0,
<del> backgroundColor: 'rgba(100, 100, 100, 0.3)'
<del> },
<del>});
<ide><path>Examples/UIExplorer/js/TimerExample.js
<ide> exports.examples = [
<ide> };
<ide>
<ide> render() {
<del> if (this.state.showTimer) {
<del> var timer = [
<del> <TimerTester ref="interval" dt={25} type="setInterval" />,
<del> <UIExplorerButton onPress={() => this.refs.interval.clear() }>
<del> Clear interval
<del> </UIExplorerButton>
<del> ];
<del> var toggleText = 'Unmount timer';
<del> } else {
<del> var timer = null;
<del> var toggleText = 'Mount new timer';
<del> }
<ide> return (
<ide> <View>
<ide> {this.state.showTimer && this._renderTimer()}
<ide><path>Examples/UIExplorer/js/TouchableExample.js
<ide> var React = require('react');
<ide> var ReactNative = require('react-native');
<ide> var {
<del> PixelRatio,
<ide> Image,
<ide> StyleSheet,
<ide> Text,
<ide> TouchableHighlight,
<ide> TouchableOpacity,
<del> UIManager,
<ide> Platform,
<ide> TouchableNativeFeedback,
<ide> View,
<ide><path>Examples/UIExplorer/js/UIExplorerExampleContainer.js
<ide> const {
<ide> const UIExplorerBlock = require('./UIExplorerBlock');
<ide> const UIExplorerPage = require('./UIExplorerPage');
<ide>
<del>const invariant = require('fbjs/lib/invariant');
<del>
<ide> class UIExplorerExampleContainer extends React.Component {
<ide> renderExample(example, i) {
<ide> // Filter platform-specific examples
<ide><path>Examples/UIExplorer/js/URIActionMap.js
<ide> */
<ide> 'use strict';
<ide>
<del>const React = require('react');
<ide> const ReactNative = require('react-native');
<ide> const UIExplorerActions = require('./UIExplorerActions');
<ide> // $FlowFixMe : This is a platform-forked component, and flow seems to only run on iOS?
<ide><path>Examples/UIExplorer/js/createExamplePage.js
<ide> const React = require('react');
<ide>
<ide> const UIExplorerExampleContainer = require('./UIExplorerExampleContainer');
<ide>
<del>import type { Example, ExampleModule } from 'ExampleTypes';
<add>import type { ExampleModule } from 'ExampleTypes';
<ide>
<ide> var createExamplePage = function(title: ?string, exampleModule: ExampleModule)
<ide> : ReactClass<any> {
<ide><path>Libraries/Components/DatePickerAndroid/DatePickerAndroid.ios.js
<ide> */
<ide> 'use strict';
<ide>
<del>var warning = require('fbjs/lib/warning');
<del>
<ide> const DatePickerAndroid = {
<ide> async open(options: Object): Promise<Object> {
<ide> return Promise.reject({
<ide><path>Libraries/Components/MapView/MapView.js
<ide> const ColorPropType = require('ColorPropType');
<ide> const EdgeInsetsPropType = require('EdgeInsetsPropType');
<ide> const Image = require('Image');
<ide> const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
<del>const Platform = require('Platform');
<ide> const React = require('React');
<ide> const StyleSheet = require('StyleSheet');
<ide> const View = require('View');
<ide><path>Libraries/Components/Picker/Picker.js
<ide> var PickerIOS = require('PickerIOS');
<ide> var PickerAndroid = require('PickerAndroid');
<ide> var Platform = require('Platform');
<ide> var React = require('React');
<del>var StyleSheet = require('StyleSheet');
<ide> var StyleSheetPropType = require('StyleSheetPropType');
<ide> var TextStylePropTypes = require('TextStylePropTypes');
<ide> var UnimplementedView = require('UnimplementedView');
<ide><path>Libraries/Components/TimePickerAndroid/TimePickerAndroid.ios.js
<ide> */
<ide> 'use strict';
<ide>
<del>var warning = require('fbjs/lib/warning');
<del>
<ide> const TimePickerAndroid = {
<ide> async open(options: Object): Promise<Object> {
<ide> return Promise.reject({
<ide><path>Libraries/Components/ToolbarAndroid/ToolbarAndroid.android.js
<ide> var ToolbarAndroid = React.createClass({
<ide> },
<ide> });
<ide>
<del>var toolbarAttributes = {
<del> ...ReactNativeViewAttributes.UIView,
<del> actions: true,
<del> logo: true,
<del> navIcon: true,
<del> overflowIcon: true,
<del> rtl: true,
<del> subtitle: true,
<del> subtitleColor: true,
<del> title: true,
<del> titleColor: true,
<del>};
<del>
<ide> var NativeToolbar = requireNativeComponent('ToolbarAndroid', ToolbarAndroid, {
<ide> nativeOnly: {
<ide> nativeActions: true,
<ide><path>Libraries/Components/WebView/WebView.android.js
<ide> var EdgeInsetsPropType = require('EdgeInsetsPropType');
<ide> var ActivityIndicator = require('ActivityIndicator');
<ide> var React = require('React');
<ide> var ReactNative = require('ReactNative');
<del>var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
<ide> var StyleSheet = require('StyleSheet');
<ide> var UIManager = require('UIManager');
<ide> var View = require('View');
<ide>
<ide> var deprecatedPropType = require('deprecatedPropType');
<ide> var keyMirror = require('fbjs/lib/keyMirror');
<del>var merge = require('merge');
<ide> var requireNativeComponent = require('requireNativeComponent');
<ide> var resolveAssetSource = require('resolveAssetSource');
<ide>
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCard.js
<ide> const NavigationPointerEventsContainer = require('NavigationPointerEventsContain
<ide> const NavigationPropTypes = require('NavigationPropTypes');
<ide> const React = require('React');
<ide> const StyleSheet = require('StyleSheet');
<del>const View = require('View');
<ide>
<ide> import type {
<ide> NavigationPanPanHandlers,
<ide><path>Libraries/Experimental/IncrementalExample.js
<ide> const IncrementalGroup = require('IncrementalGroup');
<ide> const IncrementalPresenter = require('IncrementalPresenter');
<ide>
<ide> const JSEventLoopWatchdog = require('JSEventLoopWatchdog');
<del>const StaticContainer = require('StaticContainer.react');
<ide>
<ide> const performanceNow = require('fbjs/lib/performanceNow');
<ide>
<ide> InteractionManager.setDeadline(1000);
<ide> JSEventLoopWatchdog.install({thresholdMS: 200});
<ide>
<del>const NUM_ITEMS = 20;
<del>
<ide> let totalWidgets = 0;
<ide>
<ide> class SlowWidget extends React.Component {
<ide><path>Libraries/Inspector/InspectorPanel.js
<ide> var Text = require('Text');
<ide> var View = require('View');
<ide> var ElementProperties = require('ElementProperties');
<ide> var PerformanceOverlay = require('PerformanceOverlay');
<del>var Touchable = require('Touchable');
<ide> var TouchableHighlight = require('TouchableHighlight');
<ide> var NetworkOverlay = require('NetworkOverlay');
<ide>
<ide><path>Libraries/Text/Text.js
<ide> const Touchable = require('Touchable');
<ide>
<ide> const createReactNativeComponentClass =
<ide> require('react/lib/createReactNativeComponentClass');
<del>const merge = require('merge');
<ide> const mergeFast = require('mergeFast');
<ide>
<ide> const stylePropType = StyleSheetPropType(TextStylePropTypes); | 23 |
Java | Java | limit calls to soloader | 5d79b26011bb9b5f8020b0b62f3b79d93a57bee3 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactBridge.java
<ide> import com.facebook.soloader.SoLoader;
<ide>
<ide> public class ReactBridge {
<add> private static boolean sDidInit = false;
<ide> public static void staticInit() {
<del> // Ideally we'd put this in static and only run it once, but that causes this method to get stripped
<del> SoLoader.loadLibrary("reactnativejni");
<add> // No locking required here, worst case we'll call into SoLoader twice
<add> // which will do its own locking internally
<add> if (!sDidInit) {
<add> SoLoader.loadLibrary("reactnativejni");
<add> sDidInit = true;
<add> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | pass request to .createconnection() | 2b3ba3f538e9ff22cdb4172799ee38d06818165f | <ide><path>lib/http.js
<ide> Agent.prototype.addRequest = function(req, host, port, localAddress) {
<ide> }
<ide> if (this.sockets[name].length < this.maxSockets) {
<ide> // If we are under maxSockets create a new one.
<del> req.onSocket(this.createSocket(name, host, port, localAddress));
<add> req.onSocket(this.createSocket(name, host, port, localAddress, req));
<ide> } else {
<ide> // We are over limit so we'll add it to the queue.
<ide> if (!this.requests[name]) {
<ide> Agent.prototype.addRequest = function(req, host, port, localAddress) {
<ide> this.requests[name].push(req);
<ide> }
<ide> };
<del>Agent.prototype.createSocket = function(name, host, port, localAddress) {
<add>Agent.prototype.createSocket = function(name, host, port, localAddress, req) {
<ide> var self = this;
<ide> var options = util._extend({}, self.options);
<ide> options.port = port;
<ide> options.host = host;
<ide> options.localAddress = localAddress;
<del> var s = self.createConnection(options);
<add> var s = self.createConnection.call(req, options);
<ide> if (!self.sockets[name]) {
<ide> self.sockets[name] = [];
<ide> }
<ide> Agent.prototype.removeSocket = function(s, name, host, port, localAddress) {
<ide> }
<ide> if (this.requests[name] && this.requests[name].length) {
<ide> // If we have pending requests and a socket gets closed a new one
<del> this.createSocket(name, host, port, localAddress).emit('free');
<add> this.createSocket(
<add> name,
<add> host,
<add> port,
<add> localAddress,
<add> this.requests[name][0]
<add> ).emit('free');
<ide> }
<ide> };
<ide>
<ide> function ClientRequest(options, cb) {
<ide> var self = this;
<ide> OutgoingMessage.call(self);
<ide>
<add> this.options = options;
<ide> self.agent = options.agent === undefined ? globalAgent : options.agent;
<ide>
<ide> var defaultPort = options.defaultPort || 80;
<ide> function ClientRequest(options, cb) {
<ide> self._last = true;
<ide> self.shouldKeepAlive = false;
<ide> if (options.createConnection) {
<del> self.onSocket(options.createConnection(self.socketPath));
<add> self.onSocket(options.createConnection.call(self, self.socketPath));
<ide> } else {
<ide> self.onSocket(net.createConnection(self.socketPath));
<ide> }
<ide> function ClientRequest(options, cb) {
<ide> if (options.createConnection) {
<ide> options.port = port;
<ide> options.host = host;
<del> var conn = options.createConnection(options);
<add> var conn = options.createConnection.call(self, options);
<ide> } else {
<ide> var conn = net.createConnection({
<ide> port: port,
<ide><path>lib/https.js
<ide>
<ide> var tls = require('tls');
<ide> var http = require('http');
<del>var inherits = require('util').inherits;
<add>var util = require('util');
<add>var inherits = util.inherits;
<ide>
<ide> function Server(opts, requestListener) {
<ide> if (!(this instanceof Server)) return new Server(opts, requestListener);
<ide> exports.createServer = function(opts, requestListener) {
<ide> // HTTPS agents.
<ide>
<ide> function createConnection(/* [port, host, options] */) {
<del> var options = {};
<add> var options = util._extend({}, this.options);
<ide>
<ide> if (typeof arguments[0] === 'object') {
<del> options = arguments[0];
<add> options = util._extend(options, arguments[0]);
<ide> } else if (typeof arguments[1] === 'object') {
<del> options = arguments[1];
<add> options = util._extend(options, arguments[1]);
<ide> options.port = arguments[0];
<ide> } else if (typeof arguments[2] === 'object') {
<del> options = arguments[2];
<add> options = util._extend(options, arguments[2]);
<ide> options.port = arguments[0];
<ide> options.host = arguments[1];
<ide> } else { | 2 |
Python | Python | use layer norm instead of batch norm | 4ce55313890a23a51a6ecb0e320d6a5a6d3f1d99 | <ide><path>spacy/_ml.py
<ide> def Tok2Vec(width, embed_size, preprocess=None):
<ide> >> uniqued(embed, column=5)
<ide> >> drop_layer(
<ide> Residual(
<del> (ExtractWindow(nW=1) >> BN(Maxout(width, width*3)))
<add> (ExtractWindow(nW=1) >> LN(Maxout(width, width*3)))
<ide> )
<ide> ) ** 4, pad=4
<ide> ) | 1 |
Text | Text | update automatic static optimization docs | e3a35b2a3e711972078d2a4a509530b62a51dec1 | <ide><path>docs/advanced-features/automatic-static-optimization.md
<ide> description: Next.js automatically optimizes your app to be static HTML whenever
<ide>
<ide> # Automatic Static Optimization
<ide>
<del>Next.js automatically determines that a page is static (can be prerendered) if it has no blocking data requirements. This determination is made by the absence of `getInitialProps` in the page.
<add>Next.js automatically determines that a page is static (can be prerendered) if it has no blocking data requirements. This determination is made by the absence of `getServerSideProps` and `getInitialProps` in the page.
<ide>
<ide> This feature allows Next.js to emit hybrid applications that contain **both server-rendered and statically generated pages**.
<ide>
<ide> One of the main benefits of this feature is that optimized pages require no serv
<ide>
<ide> ## How it works
<ide>
<del>If `getInitialProps` is present, Next.js will use its default behavior and render the page on-demand, per-request (meaning Server-Side Rendering).
<add>If `getServerSideProps` or `getInitialProps` is present in a page, Next.js will use its default behavior and render the page on-demand, per-request (meaning [Server-Side Rendering](/docs/basic-features/pages.md#server-side-rendering)).
<ide>
<del>If `getInitialProps` is absent, Next.js will **statically optimize** your page automatically by prerendering the page to static HTML. During prerendering, the router's `query` object will be empty since we do not have `query` information to provide during this phase. Any `query` values will be populated client-side after hydration.
<add>If the above is not the case, Next.js will **statically optimize** your page automatically by prerendering the page to static HTML.
<add>
<add>During prerendering, the router's `query` object will be empty since we do not have `query` information to provide during this phase. Any `query` values will be populated client-side after hydration.
<add>
<add>> **Note:** Parameters added with [dynamic routes](/docs/routing/dynamic-routes.md) to a page that's using [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) will always be available inside the `query` object.
<ide>
<ide> `next build` will emit `.html` files for statically optimized pages. For example, the result for the page `pages/about.js` would be:
<ide>
<ide> ```bash
<ide> .next/server/static/${BUILD_ID}/about.html
<ide> ```
<ide>
<del>And if you add `getInitialProps` to the page, it will then be JavaScript, like so:
<add>And if you add `getServerSideProps` to the page, it will then be JavaScript, like so:
<ide>
<ide> ```bash
<ide> .next/server/static/${BUILD_ID}/about.js | 1 |
Python | Python | fix weird autodetector error | 40afdaf08ca7562d8908b999511cd40a432520a9 | <ide><path>django/db/models/fields/related.py
<ide> def deconstruct(self):
<ide> if getattr(self.rel, 'through', None) is not None:
<ide> if isinstance(self.rel.through, six.string_types):
<ide> kwargs['through'] = self.rel.through
<del> else:
<add> elif not self.rel.through._meta.auto_created:
<ide> kwargs['through'] = "%s.%s" % (self.rel.through._meta.app_label, self.rel.through._meta.object_name)
<ide> # If swappable is True, then see if we're actually pointing to the target
<ide> # of a swap. | 1 |
Python | Python | remove mlsd function from hooks/ftp.py | c60e476fb24d4fa2eb192f8fce51edea4166f1d0 | <ide><path>airflow/providers/ftp/hooks/ftp.py
<ide> import datetime
<ide> import ftplib
<ide> import os.path
<del>from typing import Generator, List, Optional, Union
<add>from typing import List, Optional
<ide>
<ide> from airflow.hooks.base_hook import BaseHook
<ide>
<ide>
<del>def mlsd(conn, path: str = "", facts: Optional[Union[str, List[str]]] = None) -> Generator:
<del> """
<del> BACKPORT FROM PYTHON3 FTPLIB.
<del>
<del> List a directory in a standardized format by using MLSD
<del> command (RFC-3659). If path is omitted the current directory
<del> is assumed. "facts" is a list of strings representing the type
<del> of information desired (e.g. ["type", "size", "perm"]).
<del>
<del> Return a generator object yielding a tuple of two elements
<del> for every file found in path.
<del> First element is the file name, the second one is a dictionary
<del> including a variable number of "facts" depending on the server
<del> and whether "facts" argument has been provided.
<del> """
<del> facts = facts or []
<del> if facts:
<del> conn.sendcmd("OPTS MLST " + ";".join(facts) + ";")
<del> if path:
<del> cmd = "MLSD %s" % path
<del> else:
<del> cmd = "MLSD"
<del> lines: List = []
<del> conn.retrlines(cmd, lines.append)
<del> for line in lines:
<del> facts_found, _, name = line.rstrip(ftplib.CRLF).partition(' ')
<del> entry = {}
<del> for fact in facts_found[:-1].split(";"):
<del> key, _, value = fact.partition("=")
<del> entry[key.lower()] = value
<del> yield (name, entry)
<del>
<del>
<ide> class FTPHook(BaseHook):
<ide> """
<ide> Interact with FTP.
<ide> def describe_directory(self, path: str) -> dict:
<ide> """
<ide> conn = self.get_conn()
<ide> conn.cwd(path)
<del> try:
<del> # only works in Python 3
<del> files = dict(conn.mlsd())
<del> except AttributeError:
<del> files = dict(mlsd(conn))
<add> files = dict(conn.mlsd())
<ide> return files
<ide>
<ide> def list_directory(self, path: str) -> List[str]: | 1 |
Go | Go | fix some windows issues in libnetwork tests | 00b2c13a1bc3b38da4772949058015b13a199349 | <ide><path>libnetwork/api/api_linux_test.go
<ide> package api
<ide>
<ide> import (
<add> "bytes"
<add> "encoding/json"
<add> "errors"
<add> "fmt"
<add> "io"
<add> "net/http"
<add> "os"
<add> "regexp"
<add> "runtime"
<add> "testing"
<add>
<add> "github.com/docker/docker/libnetwork"
<add> "github.com/docker/docker/libnetwork/datastore"
<ide> "github.com/docker/docker/libnetwork/drivers/bridge"
<ide> "github.com/docker/docker/libnetwork/netlabel"
<add> "github.com/docker/docker/libnetwork/options"
<add> "github.com/docker/docker/libnetwork/testutils"
<add> "github.com/docker/docker/libnetwork/types"
<add> "github.com/docker/docker/pkg/reexec"
<add>)
<add>
<add>const (
<add> bridgeNetType = "bridge"
<add> bridgeName = "docker0"
<ide> )
<ide>
<add>func i2s(i interface{}) string {
<add> s, ok := i.(string)
<add> if !ok {
<add> panic(fmt.Sprintf("Failed i2s for %v", i))
<add> }
<add> return s
<add>}
<add>
<add>func i2e(i interface{}) *endpointResource {
<add> s, ok := i.(*endpointResource)
<add> if !ok {
<add> panic(fmt.Sprintf("Failed i2e for %v", i))
<add> }
<add> return s
<add>}
<add>
<add>func i2eL(i interface{}) []*endpointResource {
<add> s, ok := i.([]*endpointResource)
<add> if !ok {
<add> panic(fmt.Sprintf("Failed i2eL for %v", i))
<add> }
<add> return s
<add>}
<add>
<add>func i2n(i interface{}) *networkResource {
<add> s, ok := i.(*networkResource)
<add> if !ok {
<add> panic(fmt.Sprintf("Failed i2n for %v", i))
<add> }
<add> return s
<add>}
<add>
<add>func i2nL(i interface{}) []*networkResource {
<add> s, ok := i.([]*networkResource)
<add> if !ok {
<add> panic(fmt.Sprintf("Failed i2nL for %v", i))
<add> }
<add> return s
<add>}
<add>
<add>func i2sb(i interface{}) *sandboxResource {
<add> s, ok := i.(*sandboxResource)
<add> if !ok {
<add> panic(fmt.Sprintf("Failed i2sb for %v", i))
<add> }
<add> return s
<add>}
<add>
<add>func i2sbL(i interface{}) []*sandboxResource {
<add> s, ok := i.([]*sandboxResource)
<add> if !ok {
<add> panic(fmt.Sprintf("Failed i2sbL for %v", i))
<add> }
<add> return s
<add>}
<add>
<add>func createTestNetwork(t *testing.T, network string) (libnetwork.NetworkController, libnetwork.Network) {
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> netOption := options.Generic{
<add> netlabel.GenericData: options.Generic{
<add> "BridgeName": network,
<add> },
<add> }
<add> netGeneric := libnetwork.NetworkOptionGeneric(netOption)
<add> nw, err := c.NewNetwork(bridgeNetType, network, "", netGeneric)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> return c, nw
<add>}
<add>
<ide> func GetOpsMap(bridgeName, defaultMTU string) map[string]string {
<ide> if defaultMTU == "" {
<ide> return map[string]string{
<ide> func GetOpsMap(bridgeName, defaultMTU string) map[string]string {
<ide> netlabel.DriverMTU: defaultMTU,
<ide> }
<ide> }
<add>
<add>func getExposedPorts() []types.TransportPort {
<add> return []types.TransportPort{
<add> {Proto: types.TCP, Port: uint16(5000)},
<add> {Proto: types.UDP, Port: uint16(400)},
<add> {Proto: types.TCP, Port: uint16(600)},
<add> }
<add>}
<add>
<add>func getPortMapping() []types.PortBinding {
<add> return []types.PortBinding{
<add> {Proto: types.TCP, Port: uint16(230), HostPort: uint16(23000)},
<add> {Proto: types.UDP, Port: uint16(200), HostPort: uint16(22000)},
<add> {Proto: types.TCP, Port: uint16(120), HostPort: uint16(12000)},
<add> }
<add>}
<add>
<add>func TestMain(m *testing.M) {
<add> if reexec.Init() {
<add> return
<add> }
<add> os.Exit(m.Run())
<add>}
<add>
<add>func TestSandboxOptionParser(t *testing.T) {
<add> hn := "host1"
<add> dn := "docker.com"
<add> hp := "/etc/hosts"
<add> rc := "/etc/resolv.conf"
<add> dnss := []string{"8.8.8.8", "172.28.34.5"}
<add> ehs := []extraHost{{Name: "extra1", Address: "172.28.9.1"}, {Name: "extra2", Address: "172.28.9.2"}}
<add>
<add> sb := sandboxCreate{
<add> HostName: hn,
<add> DomainName: dn,
<add> HostsPath: hp,
<add> ResolvConfPath: rc,
<add> DNS: dnss,
<add> ExtraHosts: ehs,
<add> UseDefaultSandbox: true,
<add> }
<add>
<add> if len(sb.parseOptions()) != 9 {
<add> t.Fatal("Failed to generate all libnetwork.SandboxOption methods")
<add> }
<add>}
<add>
<add>func TestJson(t *testing.T) {
<add> nc := networkCreate{NetworkType: bridgeNetType}
<add> b, err := json.Marshal(nc)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> var ncp networkCreate
<add> err = json.Unmarshal(b, &ncp)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if nc.NetworkType != ncp.NetworkType {
<add> t.Fatalf("Incorrect networkCreate after json encoding/deconding: %v", ncp)
<add> }
<add>
<add> jl := endpointJoin{SandboxID: "abcdef456789"}
<add> b, err = json.Marshal(jl)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> var jld endpointJoin
<add> err = json.Unmarshal(b, &jld)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if jl.SandboxID != jld.SandboxID {
<add> t.Fatalf("Incorrect endpointJoin after json encoding/deconding: %v", jld)
<add> }
<add>}
<add>
<add>func TestCreateDeleteNetwork(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add>
<add> badBody, err := json.Marshal("bad body")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars := make(map[string]string)
<add> _, errRsp := procCreateNetwork(c, nil, badBody)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected StatusBadRequest status code, got: %v", errRsp)
<add> }
<add>
<add> incompleteBody, err := json.Marshal(networkCreate{})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> _, errRsp = procCreateNetwork(c, vars, incompleteBody)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected StatusBadRequest status code, got: %v", errRsp)
<add> }
<add>
<add> dops := GetOpsMap("abc", "")
<add> nops := map[string]string{}
<add> nc := networkCreate{Name: "network_1", NetworkType: bridgeNetType, DriverOpts: dops, NetworkOpts: nops}
<add> goodBody, err := json.Marshal(nc)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> _, errRsp = procCreateNetwork(c, vars, goodBody)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> vars[urlNwName] = ""
<add> _, errRsp = procDeleteNetwork(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add>
<add> vars[urlNwName] = "abc"
<add> _, errRsp = procDeleteNetwork(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add>
<add> vars[urlNwName] = "network_1"
<add> _, errRsp = procDeleteNetwork(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>}
<add>
<add>func TestGetNetworksAndEndpoints(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add>
<add> ops := GetOpsMap("api_test_nw", "")
<add> nc := networkCreate{Name: "sh", NetworkType: bridgeNetType, DriverOpts: ops}
<add> body, err := json.Marshal(nc)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars := make(map[string]string)
<add> inid, errRsp := procCreateNetwork(c, vars, body)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> nid, ok := inid.(string)
<add> if !ok {
<add> t.FailNow()
<add> }
<add>
<add> ec1 := endpointCreate{
<add> Name: "ep1",
<add> }
<add> b1, err := json.Marshal(ec1)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> ec2 := endpointCreate{Name: "ep2"}
<add> b2, err := json.Marshal(ec2)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars[urlNwName] = "sh"
<add> vars[urlEpName] = "ep1"
<add> ieid1, errRsp := procCreateEndpoint(c, vars, b1)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> eid1 := i2s(ieid1)
<add> vars[urlEpName] = "ep2"
<add> ieid2, errRsp := procCreateEndpoint(c, vars, b2)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> eid2 := i2s(ieid2)
<add>
<add> vars[urlNwName] = ""
<add> vars[urlEpName] = "ep1"
<add> _, errRsp = procGetEndpoint(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode)
<add> }
<add>
<add> vars = make(map[string]string)
<add> vars[urlNwName] = "sh"
<add> vars[urlEpID] = ""
<add> _, errRsp = procGetEndpoint(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode)
<add> }
<add>
<add> vars = make(map[string]string)
<add> vars[urlNwID] = ""
<add> vars[urlEpID] = eid1
<add> _, errRsp = procGetEndpoint(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode)
<add> }
<add>
<add> // nw by name and ep by id
<add> vars[urlNwName] = "sh"
<add> i1, errRsp := procGetEndpoint(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> // nw by name and ep by name
<add> delete(vars, urlEpID)
<add> vars[urlEpName] = "ep1"
<add> i2, errRsp := procGetEndpoint(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> // nw by id and ep by name
<add> delete(vars, urlNwName)
<add> vars[urlNwID] = nid
<add> i3, errRsp := procGetEndpoint(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> // nw by id and ep by id
<add> delete(vars, urlEpName)
<add> vars[urlEpID] = eid1
<add> i4, errRsp := procGetEndpoint(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> id1 := i2e(i1).ID
<add> if id1 != i2e(i2).ID || id1 != i2e(i3).ID || id1 != i2e(i4).ID {
<add> t.Fatalf("Endpoints retrieved via different query parameters differ: %v, %v, %v, %v", i1, i2, i3, i4)
<add> }
<add>
<add> vars[urlNwName] = ""
<add> _, errRsp = procGetEndpoints(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> delete(vars, urlNwName)
<add> vars[urlNwID] = "fakeID"
<add> _, errRsp = procGetEndpoints(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlNwID] = nid
<add> _, errRsp = procGetEndpoints(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> vars[urlNwName] = "sh"
<add> iepList, errRsp := procGetEndpoints(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> epList := i2eL(iepList)
<add> if len(epList) != 2 {
<add> t.Fatalf("Did not return the expected number (2) of endpoint resources: %d", len(epList))
<add> }
<add> if "sh" != epList[0].Network || "sh" != epList[1].Network {
<add> t.Fatal("Did not find expected network name in endpoint resources")
<add> }
<add>
<add> vars = make(map[string]string)
<add> vars[urlNwName] = ""
<add> _, errRsp = procGetNetwork(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> vars[urlNwName] = "shhhhh"
<add> _, errRsp = procGetNetwork(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> vars[urlNwName] = "sh"
<add> inr1, errRsp := procGetNetwork(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> nr1 := i2n(inr1)
<add>
<add> delete(vars, urlNwName)
<add> vars[urlNwID] = "acacac"
<add> _, errRsp = procGetNetwork(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure. Got: %v", errRsp)
<add> }
<add> vars[urlNwID] = nid
<add> inr2, errRsp := procGetNetwork(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("procgetNetworkByName() != procgetNetworkById(), %v vs %v", inr1, inr2)
<add> }
<add> nr2 := i2n(inr2)
<add> if nr1.Name != nr2.Name || nr1.Type != nr2.Type || nr1.ID != nr2.ID || len(nr1.Endpoints) != len(nr2.Endpoints) {
<add> t.Fatalf("Get by name and Get failure: %v", errRsp)
<add> }
<add>
<add> if len(nr1.Endpoints) != 2 {
<add> t.Fatalf("Did not find the expected number (2) of endpoint resources in the network resource: %d", len(nr1.Endpoints))
<add> }
<add> for _, er := range nr1.Endpoints {
<add> if er.ID != eid1 && er.ID != eid2 {
<add> t.Fatalf("Did not find the expected endpoint resources in the network resource: %v", nr1.Endpoints)
<add> }
<add> }
<add>
<add> iList, errRsp := procGetNetworks(c, nil, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> netList := i2nL(iList)
<add> if len(netList) != 1 {
<add> t.Fatal("Did not return the expected number of network resources")
<add> }
<add> if nid != netList[0].ID {
<add> t.Fatalf("Did not find expected network %s: %v", nid, netList)
<add> }
<add>
<add> _, errRsp = procDeleteNetwork(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlEpName] = "ep1"
<add> _, errRsp = procDeleteEndpoint(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> delete(vars, urlEpName)
<add> iepList, errRsp = procGetEndpoints(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> epList = i2eL(iepList)
<add> if len(epList) != 1 {
<add> t.Fatalf("Did not return the expected number (1) of endpoint resources: %d", len(epList))
<add> }
<add>
<add> vars[urlEpName] = "ep2"
<add> _, errRsp = procDeleteEndpoint(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> iepList, errRsp = procGetEndpoints(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> epList = i2eL(iepList)
<add> if len(epList) != 0 {
<add> t.Fatalf("Did not return the expected number (0) of endpoint resources: %d", len(epList))
<add> }
<add>
<add> _, errRsp = procDeleteNetwork(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> iList, errRsp = procGetNetworks(c, nil, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> netList = i2nL(iList)
<add> if len(netList) != 0 {
<add> t.Fatal("Did not return the expected number of network resources")
<add> }
<add>}
<add>
<add>func TestProcGetServices(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add>
<add> // Create 2 networks
<add> netName1 := "production"
<add> netOption := options.Generic{
<add> netlabel.GenericData: options.Generic{
<add> "BridgeName": netName1,
<add> },
<add> }
<add> nw1, err := c.NewNetwork(bridgeNetType, netName1, "", libnetwork.NetworkOptionGeneric(netOption))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> netName2 := "workdev"
<add> netOption = options.Generic{
<add> netlabel.GenericData: options.Generic{
<add> "BridgeName": netName2,
<add> },
<add> }
<add> nw2, err := c.NewNetwork(bridgeNetType, netName2, "", libnetwork.NetworkOptionGeneric(netOption))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars := make(map[string]string)
<add> li, errRsp := procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list := i2eL(li)
<add> if len(list) != 0 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>
<add> // Add a couple of services on one network and one on the other network
<add> ep11, err := nw1.CreateEndpoint("db-prod")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> ep12, err := nw1.CreateEndpoint("web-prod")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> ep21, err := nw2.CreateEndpoint("db-dev")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 3 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>
<add> // Filter by network
<add> vars[urlNwName] = netName1
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 2 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>
<add> vars[urlNwName] = netName2
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 1 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>
<add> vars[urlNwName] = "unknown-network"
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 0 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>
<add> // Query by name
<add> delete(vars, urlNwName)
<add> vars[urlEpName] = "db-prod"
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 1 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>
<add> vars[urlEpName] = "no-service"
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 0 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>
<add> // Query by id or partial id
<add> delete(vars, urlEpName)
<add> vars[urlEpPID] = ep12.ID()
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 1 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add> if list[0].ID != ep12.ID() {
<add> t.Fatalf("Unexpected element in response: %v", list)
<add> }
<add>
<add> vars[urlEpPID] = "non-id"
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 0 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>
<add> delete(vars, urlEpPID)
<add> err = ep11.Delete(false)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> err = ep12.Delete(false)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> err = ep21.Delete(false)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> li, errRsp = procGetServices(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> list = i2eL(li)
<add> if len(list) != 0 {
<add> t.Fatalf("Unexpected services in response: %v", list)
<add> }
<add>}
<add>
<add>func TestProcGetService(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> c, nw := createTestNetwork(t, "network")
<add> defer c.Stop()
<add> ep1, err := nw.CreateEndpoint("db")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> ep2, err := nw.CreateEndpoint("web")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars := map[string]string{urlEpID: ""}
<add> _, errRsp := procGetService(c, vars, nil)
<add> if errRsp.isOK() {
<add> t.Fatal("Expected failure, but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode)
<add> }
<add>
<add> vars[urlEpID] = "unknown-service-id"
<add> _, errRsp = procGetService(c, vars, nil)
<add> if errRsp.isOK() {
<add> t.Fatal("Expected failure, but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp)
<add> }
<add>
<add> vars[urlEpID] = ep1.ID()
<add> si, errRsp := procGetService(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> sv := i2e(si)
<add> if sv.ID != ep1.ID() {
<add> t.Fatalf("Unexpected service resource returned: %v", sv)
<add> }
<add>
<add> vars[urlEpID] = ep2.ID()
<add> si, errRsp = procGetService(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> sv = i2e(si)
<add> if sv.ID != ep2.ID() {
<add> t.Fatalf("Unexpected service resource returned: %v", sv)
<add> }
<add>}
<add>
<add>func TestProcPublishUnpublishService(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> c, _ := createTestNetwork(t, "network")
<add> defer c.Stop()
<add>
<add> vars := make(map[string]string)
<add>
<add> vbad, err := json.Marshal("bad service create data")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp := procPublishService(c, vars, vbad)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>
<add> b, err := json.Marshal(servicePublish{Name: ""})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp = procPublishService(c, vars, b)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>
<add> b, err = json.Marshal(servicePublish{Name: "db"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp = procPublishService(c, vars, b)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>
<add> b, err = json.Marshal(servicePublish{Name: "db", Network: "unknown-network"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp = procPublishService(c, vars, b)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<add> }
<add>
<add> b, err = json.Marshal(servicePublish{Name: "", Network: "network"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp = procPublishService(c, vars, b)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>
<add> b, err = json.Marshal(servicePublish{Name: "db", Network: "network"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp = procPublishService(c, vars, b)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> sp := servicePublish{
<add> Name: "web",
<add> Network: "network",
<add> }
<add> b, err = json.Marshal(sp)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> si, errRsp := procPublishService(c, vars, b)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> sid := i2s(si)
<add>
<add> vars[urlEpID] = ""
<add> _, errRsp = procUnpublishService(c, vars, nil)
<add> if errRsp.isOK() {
<add> t.Fatal("Expected failure but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>
<add> vars[urlEpID] = "unknown-service-id"
<add> _, errRsp = procUnpublishService(c, vars, nil)
<add> if errRsp.isOK() {
<add> t.Fatal("Expected failure but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<add> }
<add>
<add> vars[urlEpID] = sid
<add> _, errRsp = procUnpublishService(c, vars, nil)
<add> if !errRsp.isOK() {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> _, errRsp = procGetService(c, vars, nil)
<add> if errRsp.isOK() {
<add> t.Fatal("Expected failure, but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp)
<add> }
<add>}
<add>
<add>func TestAttachDetachBackend(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> c, nw := createTestNetwork(t, "network")
<add> defer c.Stop()
<add> ep1, err := nw.CreateEndpoint("db")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars := make(map[string]string)
<add>
<add> vbad, err := json.Marshal("bad data")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp := procAttachBackend(c, vars, vbad)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlEpName] = "endpoint"
<add> bad, err := json.Marshal(endpointJoin{})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp = procAttachBackend(c, vars, bad)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<add> }
<add>
<add> vars[urlEpID] = "db"
<add> _, errRsp = procGetSandbox(c, vars, nil)
<add> if errRsp.isOK() {
<add> t.Fatalf("Expected failure. Got %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<add> }
<add>
<add> vars[urlEpName] = "db"
<add> _, errRsp = procAttachBackend(c, vars, bad)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>
<add> cid := "abcdefghi"
<add> sbox, err := c.NewSandbox(cid)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> sid := sbox.ID()
<add> defer sbox.Delete()
<add>
<add> jl := endpointJoin{SandboxID: sid}
<add> jlb, err := json.Marshal(jl)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> _, errRsp = procAttachBackend(c, vars, jlb)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure, got: %v", errRsp)
<add> }
<add>
<add> sli, errRsp := procGetSandboxes(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure, got: %v", errRsp)
<add> }
<add> sl := i2sbL(sli)
<add> if len(sl) != 1 {
<add> t.Fatalf("Did not find expected number of sandboxes attached to the service: %d", len(sl))
<add> }
<add> if sl[0].ContainerID != cid {
<add> t.Fatalf("Did not find expected sandbox attached to the service: %v", sl[0])
<add> }
<add>
<add> _, errRsp = procUnpublishService(c, vars, nil)
<add> if errRsp.isOK() {
<add> t.Fatal("Expected failure but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusForbidden {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusForbidden, errRsp)
<add> }
<add>
<add> vars[urlEpName] = "endpoint"
<add> _, errRsp = procDetachBackend(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<add> }
<add>
<add> vars[urlEpName] = "db"
<add> _, errRsp = procDetachBackend(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>
<add> vars[urlSbID] = sid
<add> _, errRsp = procDetachBackend(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure, got: %v", errRsp)
<add> }
<add>
<add> delete(vars, urlEpID)
<add> si, errRsp := procGetSandbox(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure, got: %v", errRsp)
<add> }
<add> sb := i2sb(si)
<add> if sb.ContainerID != cid {
<add> t.Fatalf("Did not find expected sandbox. Got %v", sb)
<add> }
<add>
<add> err = ep1.Delete(false)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>}
<add>
<add>func TestDetectGetNetworksInvalidQueryComposition(t *testing.T) {
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add>
<add> vars := map[string]string{urlNwName: "x", urlNwPID: "y"}
<add> _, errRsp := procGetNetworks(c, vars, nil)
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>}
<add>
<add>func TestDetectGetEndpointsInvalidQueryComposition(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> c, _ := createTestNetwork(t, "network")
<add> defer c.Stop()
<add>
<add> vars := map[string]string{urlNwName: "network", urlEpName: "x", urlEpPID: "y"}
<add> _, errRsp := procGetEndpoints(c, vars, nil)
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>}
<add>
<add>func TestDetectGetServicesInvalidQueryComposition(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> c, _ := createTestNetwork(t, "network")
<add> defer c.Stop()
<add>
<add> vars := map[string]string{urlNwName: "network", urlEpName: "x", urlEpPID: "y"}
<add> _, errRsp := procGetServices(c, vars, nil)
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<add> }
<add>}
<add>
<add>func TestFindNetworkUtilPanic(t *testing.T) {
<add> defer checkPanic(t)
<add> findNetwork(nil, "", -1)
<add>}
<add>
<add>func TestFindNetworkUtil(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> c, nw := createTestNetwork(t, "network")
<add> defer c.Stop()
<add>
<add> nid := nw.ID()
<add>
<add> _, errRsp := findNetwork(c, "", byName)
<add> if errRsp == &successResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode)
<add> }
<add>
<add> n, errRsp := findNetwork(c, nid, byID)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> if n == nil {
<add> t.Fatal("Unexpected nil libnetwork.Network")
<add> }
<add> if nid != n.ID() {
<add> t.Fatalf("Incorrect libnetwork.Network resource. It has different id: %v", n)
<add> }
<add> if "network" != n.Name() {
<add> t.Fatalf("Incorrect libnetwork.Network resource. It has different name: %v", n)
<add> }
<add>
<add> n, errRsp = findNetwork(c, "network", byName)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> if n == nil {
<add> t.Fatal("Unexpected nil libnetwork.Network")
<add> }
<add> if nid != n.ID() {
<add> t.Fatalf("Incorrect libnetwork.Network resource. It has different id: %v", n)
<add> }
<add> if "network" != n.Name() {
<add> t.Fatalf("Incorrect libnetwork.Network resource. It has different name: %v", n)
<add> }
<add>
<add> if err := n.Delete(); err != nil {
<add> t.Fatalf("Failed to delete the network: %s", err.Error())
<add> }
<add>
<add> _, errRsp = findNetwork(c, nid, byID)
<add> if errRsp == &successResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<add> }
<add>
<add> _, errRsp = findNetwork(c, "network", byName)
<add> if errRsp == &successResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<add> }
<add>}
<add>
<add>func TestCreateDeleteEndpoints(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add>
<add> nc := networkCreate{Name: "firstNet", NetworkType: bridgeNetType}
<add> body, err := json.Marshal(nc)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars := make(map[string]string)
<add> i, errRsp := procCreateNetwork(c, vars, body)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> nid := i2s(i)
<add>
<add> vbad, err := json.Marshal("bad endpoint create data")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars[urlNwName] = "firstNet"
<add> _, errRsp = procCreateEndpoint(c, vars, vbad)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add>
<add> b, err := json.Marshal(endpointCreate{Name: ""})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars[urlNwName] = "secondNet"
<add> _, errRsp = procCreateEndpoint(c, vars, b)
<add> if errRsp == &createdResponse {
<add> t.Fatal("Expected to fail but succeeded")
<add> }
<add>
<add> vars[urlNwName] = "firstNet"
<add> _, errRsp = procCreateEndpoint(c, vars, b)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<add> }
<add>
<add> b, err = json.Marshal(endpointCreate{Name: "firstEp"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> i, errRsp = procCreateEndpoint(c, vars, b)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add> eid := i2s(i)
<add>
<add> _, errRsp = findEndpoint(c, "myNet", "firstEp", byName, byName)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<add> }
<add>
<add> ep0, errRsp := findEndpoint(c, nid, "firstEp", byID, byName)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> ep1, errRsp := findEndpoint(c, "firstNet", "firstEp", byName, byName)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> ep2, errRsp := findEndpoint(c, nid, eid, byID, byID)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> ep3, errRsp := findEndpoint(c, "firstNet", eid, byName, byID)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> if ep0.ID() != ep1.ID() || ep0.ID() != ep2.ID() || ep0.ID() != ep3.ID() {
<add> t.Fatalf("Different queries returned different endpoints: \nep0: %v\nep1: %v\nep2: %v\nep3: %v", ep0, ep1, ep2, ep3)
<add> }
<add>
<add> vars = make(map[string]string)
<add> vars[urlNwName] = ""
<add> vars[urlEpName] = "ep1"
<add> _, errRsp = procDeleteEndpoint(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlNwName] = "firstNet"
<add> vars[urlEpName] = ""
<add> _, errRsp = procDeleteEndpoint(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlEpName] = "ep2"
<add> _, errRsp = procDeleteEndpoint(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlEpName] = "firstEp"
<add> _, errRsp = procDeleteEndpoint(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> _, errRsp = findEndpoint(c, "firstNet", "firstEp", byName, byName)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>}
<add>
<add>func TestJoinLeave(t *testing.T) {
<add> if runtime.GOARCH == "arm64" {
<add> t.Skip("This test fails on arm64 foor some reason... this need to be fixed")
<add> }
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add>
<add> nb, err := json.Marshal(networkCreate{Name: "network", NetworkType: bridgeNetType})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> vars := make(map[string]string)
<add> _, errRsp := procCreateNetwork(c, vars, nb)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> eb, err := json.Marshal(endpointCreate{Name: "endpoint"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> vars[urlNwName] = "network"
<add> _, errRsp = procCreateEndpoint(c, vars, eb)
<add> if errRsp != &createdResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> vbad, err := json.Marshal("bad data")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp = procJoinEndpoint(c, vars, vbad)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlEpName] = "endpoint"
<add> bad, err := json.Marshal(endpointJoin{})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> _, errRsp = procJoinEndpoint(c, vars, bad)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> cid := "abcdefghi"
<add> sb, err := c.NewSandbox(cid)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer sb.Delete()
<add>
<add> jl := endpointJoin{SandboxID: sb.ID()}
<add> jlb, err := json.Marshal(jl)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> vars = make(map[string]string)
<add> vars[urlNwName] = ""
<add> vars[urlEpName] = ""
<add> _, errRsp = procJoinEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlNwName] = "network"
<add> vars[urlEpName] = ""
<add> _, errRsp = procJoinEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlEpName] = "epoint"
<add> _, errRsp = procJoinEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> // bad labels
<add> vars[urlEpName] = "endpoint"
<add> key, errRsp := procJoinEndpoint(c, vars, jlb)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure, got: %v", errRsp)
<add> }
<add>
<add> keyStr := i2s(key)
<add> if keyStr == "" {
<add> t.Fatal("Empty sandbox key")
<add> }
<add> _, errRsp = procDeleteEndpoint(c, vars, nil)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlNwName] = "network2"
<add> _, errRsp = procLeaveEndpoint(c, vars, vbad)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> _, errRsp = procLeaveEndpoint(c, vars, bad)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> vars = make(map[string]string)
<add> vars[urlNwName] = ""
<add> vars[urlEpName] = ""
<add> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> vars[urlNwName] = "network"
<add> vars[urlEpName] = ""
<add> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> vars[urlEpName] = "2epoint"
<add> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add> vars[urlEpName] = "epoint"
<add> vars[urlCnID] = "who"
<add> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> delete(vars, urlCnID)
<add> vars[urlEpName] = "endpoint"
<add> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> vars[urlSbID] = sb.ID()
<add> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, got: %v", errRsp)
<add> }
<add>
<add> _, errRsp = procDeleteEndpoint(c, vars, nil)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>}
<add>
<add>func TestFindEndpointUtilPanic(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add> defer checkPanic(t)
<add> c, nw := createTestNetwork(t, "network")
<add> defer c.Stop()
<add>
<add> nid := nw.ID()
<add> findEndpoint(c, nid, "", byID, -1)
<add>}
<add>
<add>func TestFindServiceUtilPanic(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add> defer checkPanic(t)
<add> c, _ := createTestNetwork(t, "network")
<add> defer c.Stop()
<add>
<add> findService(c, "random_service", -1)
<add>}
<add>
<add>func TestFindEndpointUtil(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> c, nw := createTestNetwork(t, "network")
<add> defer c.Stop()
<add>
<add> nid := nw.ID()
<add>
<add> ep, err := nw.CreateEndpoint("secondEp", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> eid := ep.ID()
<add>
<add> _, errRsp := findEndpoint(c, nid, "", byID, byName)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, but got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusBadRequest {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode)
<add> }
<add>
<add> ep0, errRsp := findEndpoint(c, nid, "secondEp", byID, byName)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> ep1, errRsp := findEndpoint(c, "network", "secondEp", byName, byName)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> ep2, errRsp := findEndpoint(c, nid, eid, byID, byID)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> ep3, errRsp := findEndpoint(c, "network", eid, byName, byID)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> ep4, errRsp := findService(c, "secondEp", byName)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> ep5, errRsp := findService(c, eid, byID)
<add> if errRsp != &successResponse {
<add> t.Fatalf("Unexpected failure: %v", errRsp)
<add> }
<add>
<add> if ep0.ID() != ep1.ID() || ep0.ID() != ep2.ID() ||
<add> ep0.ID() != ep3.ID() || ep0.ID() != ep4.ID() || ep0.ID() != ep5.ID() {
<add> t.Fatal("Different queries returned different endpoints")
<add> }
<add>
<add> ep.Delete(false)
<add>
<add> _, errRsp = findEndpoint(c, nid, "secondEp", byID, byName)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, but got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<add> }
<add>
<add> _, errRsp = findEndpoint(c, "network", "secondEp", byName, byName)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, but got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<add> }
<add>
<add> _, errRsp = findEndpoint(c, nid, eid, byID, byID)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, but got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<add> }
<add>
<add> _, errRsp = findEndpoint(c, "network", eid, byName, byID)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, but got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<add> }
<add>
<add> _, errRsp = findService(c, "secondEp", byName)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, but got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<add> }
<add>
<add> _, errRsp = findService(c, eid, byID)
<add> if errRsp == &successResponse {
<add> t.Fatalf("Expected failure, but got: %v", errRsp)
<add> }
<add> if errRsp.StatusCode != http.StatusNotFound {
<add> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<add> }
<add>}
<add>
<add>func TestEndpointToService(t *testing.T) {
<add> r := &responseStatus{Status: "this is one endpoint", StatusCode: http.StatusOK}
<add> r = endpointToService(r)
<add> if r.Status != "this is one service" {
<add> t.Fatalf("endpointToService returned unexpected status string: %s", r.Status)
<add> }
<add>
<add> r = &responseStatus{Status: "this is one network", StatusCode: http.StatusOK}
<add> r = endpointToService(r)
<add> if r.Status != "this is one network" {
<add> t.Fatalf("endpointToService returned unexpected status string: %s", r.Status)
<add> }
<add>}
<add>
<add>func checkPanic(t *testing.T) {
<add> if r := recover(); r != nil {
<add> if _, ok := r.(runtime.Error); ok {
<add> panic(r)
<add> }
<add> } else {
<add> t.Fatal("Expected to panic, but succeeded")
<add> }
<add>}
<add>
<add>func TestDetectNetworkTargetPanic(t *testing.T) {
<add> defer checkPanic(t)
<add> vars := make(map[string]string)
<add> detectNetworkTarget(vars)
<add>}
<add>
<add>func TestDetectEndpointTargetPanic(t *testing.T) {
<add> defer checkPanic(t)
<add> vars := make(map[string]string)
<add> detectEndpointTarget(vars)
<add>}
<add>
<add>func TestResponseStatus(t *testing.T) {
<add> list := []int{
<add> http.StatusBadGateway,
<add> http.StatusBadRequest,
<add> http.StatusConflict,
<add> http.StatusContinue,
<add> http.StatusExpectationFailed,
<add> http.StatusForbidden,
<add> http.StatusFound,
<add> http.StatusGatewayTimeout,
<add> http.StatusGone,
<add> http.StatusHTTPVersionNotSupported,
<add> http.StatusInternalServerError,
<add> http.StatusLengthRequired,
<add> http.StatusMethodNotAllowed,
<add> http.StatusMovedPermanently,
<add> http.StatusMultipleChoices,
<add> http.StatusNoContent,
<add> http.StatusNonAuthoritativeInfo,
<add> http.StatusNotAcceptable,
<add> http.StatusNotFound,
<add> http.StatusNotModified,
<add> http.StatusPartialContent,
<add> http.StatusPaymentRequired,
<add> http.StatusPreconditionFailed,
<add> http.StatusProxyAuthRequired,
<add> http.StatusRequestEntityTooLarge,
<add> http.StatusRequestTimeout,
<add> http.StatusRequestURITooLong,
<add> http.StatusRequestedRangeNotSatisfiable,
<add> http.StatusResetContent,
<add> http.StatusServiceUnavailable,
<add> http.StatusSwitchingProtocols,
<add> http.StatusTemporaryRedirect,
<add> http.StatusUnauthorized,
<add> http.StatusUnsupportedMediaType,
<add> http.StatusUseProxy,
<add> }
<add> for _, c := range list {
<add> r := responseStatus{StatusCode: c}
<add> if r.isOK() {
<add> t.Fatalf("isOK() returned true for code% d", c)
<add> }
<add> }
<add>
<add> r := responseStatus{StatusCode: http.StatusOK}
<add> if !r.isOK() {
<add> t.Fatal("isOK() failed")
<add> }
<add>
<add> r = responseStatus{StatusCode: http.StatusCreated}
<add> if !r.isOK() {
<add> t.Fatal("isOK() failed")
<add> }
<add>}
<add>
<add>// Local structs for end to end testing of api.go
<add>type localReader struct {
<add> data []byte
<add> beBad bool
<add>}
<add>
<add>func newLocalReader(data []byte) *localReader {
<add> lr := &localReader{data: make([]byte, len(data))}
<add> copy(lr.data, data)
<add> return lr
<add>}
<add>
<add>func (l *localReader) Read(p []byte) (n int, err error) {
<add> if l.beBad {
<add> return 0, errors.New("I am a bad reader")
<add> }
<add> if p == nil {
<add> return -1, errors.New("nil buffer passed")
<add> }
<add> if l.data == nil || len(l.data) == 0 {
<add> return 0, io.EOF
<add> }
<add> copy(p[:], l.data[:])
<add> return len(l.data), io.EOF
<add>}
<add>
<add>type localResponseWriter struct {
<add> body []byte
<add> statusCode int
<add>}
<add>
<add>func newWriter() *localResponseWriter {
<add> return &localResponseWriter{}
<add>}
<add>
<add>func (f *localResponseWriter) Header() http.Header {
<add> return make(map[string][]string, 0)
<add>}
<add>
<add>func (f *localResponseWriter) Write(data []byte) (int, error) {
<add> if data == nil {
<add> return -1, errors.New("nil data passed")
<add> }
<add>
<add> f.body = make([]byte, len(data))
<add> copy(f.body, data)
<add>
<add> return len(f.body), nil
<add>}
<add>
<add>func (f *localResponseWriter) WriteHeader(c int) {
<add> f.statusCode = c
<add>}
<add>
<add>func testWriteJSON(t *testing.T, testCode int, testData interface{}) {
<add> testDataMarshalled, err := json.Marshal(testData)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> rsp := newWriter()
<add> writeJSON(rsp, testCode, testData)
<add> if rsp.statusCode != testCode {
<add> t.Fatalf("writeJSON() failed to set the status code. Expected %d. Got %d", testCode, rsp.statusCode)
<add> }
<add> // writeJSON calls json.Encode and it appends '\n' to the result,
<add> // while json.Marshal not
<add> expected := append(testDataMarshalled, byte('\n'))
<add> if !bytes.Equal(expected, rsp.body) {
<add> t.Fatalf("writeJSON() failed to set the body. Expected %q. Got %q", expected, rsp.body)
<add> }
<add>}
<add>
<add>func TestWriteJSON(t *testing.T) {
<add> testWriteJSON(t, 55, "test data as string")
<add> testWriteJSON(t, 55, []byte("test data as bytes"))
<add>}
<add>
<add>func TestHttpHandlerUninit(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add>
<add> h := &httpHandler{c: c}
<add> h.initRouter()
<add> if h.r == nil {
<add> t.Fatal("initRouter() did not initialize the router")
<add> }
<add>
<add> rsp := newWriter()
<add> req, err := http.NewRequest("GET", "/v1.19/networks", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> handleRequest := NewHTTPHandler(nil)
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusServiceUnavailable {
<add> t.Fatalf("Expected (%d). Got (%d): %s", http.StatusServiceUnavailable, rsp.statusCode, rsp.body)
<add> }
<add>
<add> handleRequest = NewHTTPHandler(c)
<add>
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Expected (%d). Got: (%d): %s", http.StatusOK, rsp.statusCode, rsp.body)
<add> }
<add>
<add> var list []*networkResource
<add> err = json.Unmarshal(rsp.body, &list)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(list) != 0 {
<add> t.Fatalf("Expected empty list. Got %v", list)
<add> }
<add>
<add> n, err := c.NewNetwork(bridgeNetType, "didietro", "", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> nwr := buildNetworkResource(n)
<add> expected, err := json.Marshal([]*networkResource{nwr})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add> if len(rsp.body) == 0 {
<add> t.Fatal("Empty list of networks")
<add> }
<add> if bytes.Equal(rsp.body, expected) {
<add> t.Fatal("Incorrect list of networks in response's body")
<add> }
<add>}
<add>
<add>func TestHttpHandlerBadBody(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> rsp := newWriter()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add> handleRequest := NewHTTPHandler(c)
<add>
<add> req, err := http.NewRequest("POST", "/v1.19/networks", &localReader{beBad: true})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusBadRequest {
<add> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusBadRequest, rsp.statusCode, string(rsp.body))
<add> }
<add>
<add> body := []byte{}
<add> lr := newLocalReader(body)
<add> req, err = http.NewRequest("POST", "/v1.19/networks", lr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusBadRequest {
<add> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusBadRequest, rsp.statusCode, string(rsp.body))
<add> }
<add>}
<add>
<add>func TestEndToEnd(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> rsp := newWriter()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add>
<add> handleRequest := NewHTTPHandler(c)
<add>
<add> dops := GetOpsMap("cdef", "1460")
<add> nops := map[string]string{}
<add>
<add> // Create network
<add> nc := networkCreate{Name: "network-fiftyfive", NetworkType: bridgeNetType, DriverOpts: dops, NetworkOpts: nops}
<add> body, err := json.Marshal(nc)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> lr := newLocalReader(body)
<add> req, err := http.NewRequest("POST", "/v1.19/networks", lr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusCreated {
<add> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<add> }
<add> if len(rsp.body) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add>
<add> var nid string
<add> err = json.Unmarshal(rsp.body, &nid)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Query networks collection
<add> req, err = http.NewRequest("GET", "/v1.19/networks?name=", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add> var list []*networkResource
<add> err = json.Unmarshal(rsp.body, &list)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(list) != 0 {
<add> t.Fatalf("Expected empty list. Got %v", list)
<add> }
<add>
<add> req, err = http.NewRequest("GET", "/v1.19/networks", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> b0 := make([]byte, len(rsp.body))
<add> copy(b0, rsp.body)
<add>
<add> req, err = http.NewRequest("GET", "/v1.19/networks?name=network-fiftyfive", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> if !bytes.Equal(b0, rsp.body) {
<add> t.Fatal("Expected same body from GET /networks and GET /networks?name=<nw> when only network <nw> exist.")
<add> }
<add>
<add> // Query network by name
<add> req, err = http.NewRequest("GET", "/v1.19/networks?name=culo", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &list)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(list) != 0 {
<add> t.Fatalf("Expected empty list. Got %v", list)
<add> }
<add>
<add> req, err = http.NewRequest("GET", "/v1.19/networks?name=network-fiftyfive", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &list)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(list) == 0 {
<add> t.Fatal("Expected non empty list")
<add> }
<add> if list[0].Name != "network-fiftyfive" || nid != list[0].ID {
<add> t.Fatalf("Incongruent resource found: %v", list[0])
<add> }
<add>
<add> // Query network by partial id
<add> chars := []byte(nid)
<add> partial := string(chars[0 : len(chars)/2])
<add> req, err = http.NewRequest("GET", "/v1.19/networks?partial-id="+partial, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &list)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(list) == 0 {
<add> t.Fatal("Expected non empty list")
<add> }
<add> if list[0].Name != "network-fiftyfive" || nid != list[0].ID {
<add> t.Fatalf("Incongruent resource found: %v", list[0])
<add> }
<add>
<add> // Get network by id
<add> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> var nwr networkResource
<add> err = json.Unmarshal(rsp.body, &nwr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if nwr.Name != "network-fiftyfive" || nid != nwr.ID {
<add> t.Fatalf("Incongruent resource found: %v", nwr)
<add> }
<add>
<add> // Create endpoint
<add> eb, err := json.Marshal(endpointCreate{Name: "ep-TwentyTwo"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> lr = newLocalReader(eb)
<add> req, err = http.NewRequest("POST", "/v1.19/networks/"+nid+"/endpoints", lr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusCreated {
<add> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<add> }
<add> if len(rsp.body) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add>
<add> var eid string
<add> err = json.Unmarshal(rsp.body, &eid)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Query endpoint(s)
<add> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?name=bla", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add> var epList []*endpointResource
<add> err = json.Unmarshal(rsp.body, &epList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(epList) != 0 {
<add> t.Fatalf("Expected empty list. Got %v", epList)
<add> }
<add>
<add> // Query endpoint by name
<add> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?name=ep-TwentyTwo", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &epList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(epList) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add> if epList[0].Name != "ep-TwentyTwo" || eid != epList[0].ID {
<add> t.Fatalf("Incongruent resource found: %v", epList[0])
<add> }
<add>
<add> // Query endpoint by partial id
<add> chars = []byte(eid)
<add> partial = string(chars[0 : len(chars)/2])
<add> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?partial-id="+partial, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &epList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(epList) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add> if epList[0].Name != "ep-TwentyTwo" || eid != epList[0].ID {
<add> t.Fatalf("Incongruent resource found: %v", epList[0])
<add> }
<add>
<add> // Get endpoint by id
<add> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints/"+eid, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> var epr endpointResource
<add> err = json.Unmarshal(rsp.body, &epr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if epr.Name != "ep-TwentyTwo" || epr.ID != eid {
<add> t.Fatalf("Incongruent resource found: %v", epr)
<add> }
<add>
<add> // Store two container ids and one partial ids
<add> cid1 := "container10010000000"
<add> cid2 := "container20010000000"
<add> chars = []byte(cid1)
<add> cpid1 := string(chars[0 : len(chars)/2])
<add>
<add> // Create sandboxes
<add> sb1, err := json.Marshal(sandboxCreate{
<add> ContainerID: cid1,
<add> PortMapping: getPortMapping(),
<add> })
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> lr = newLocalReader(sb1)
<add> req, err = http.NewRequest("POST", "/v5.22/sandboxes", lr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusCreated {
<add> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<add> }
<add> if len(rsp.body) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add> // Get sandbox id and partial id
<add> var sid1 string
<add> err = json.Unmarshal(rsp.body, &sid1)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> sb2, err := json.Marshal(sandboxCreate{
<add> ContainerID: cid2,
<add> ExposedPorts: getExposedPorts(),
<add> })
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> lr = newLocalReader(sb2)
<add> req, err = http.NewRequest("POST", "/v5.22/sandboxes", lr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusCreated {
<add> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<add> }
<add> if len(rsp.body) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add> // Get sandbox id and partial id
<add> var sid2 string
<add> err = json.Unmarshal(rsp.body, &sid2)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> chars = []byte(sid2)
<add> spid2 := string(chars[0 : len(chars)/2])
<add>
<add> // Query sandboxes
<add> req, err = http.NewRequest("GET", "/sandboxes", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> var sbList []*sandboxResource
<add> err = json.Unmarshal(rsp.body, &sbList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(sbList) != 2 {
<add> t.Fatalf("Expected 2 elements in list. Got %v", sbList)
<add> }
<add>
<add> // Get sandbox by id
<add> req, err = http.NewRequest("GET", "/sandboxes/"+sid1, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> var sbr sandboxResource
<add> err = json.Unmarshal(rsp.body, &sbr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if sbr.ContainerID != cid1 {
<add> t.Fatalf("Incongruent resource found: %v", sbr)
<add> }
<add>
<add> // Query sandbox by partial sandbox id
<add> req, err = http.NewRequest("GET", "/sandboxes?partial-id="+spid2, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &sbList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(sbList) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add> if sbList[0].ID != sid2 {
<add> t.Fatalf("Incongruent resource found: %v", sbList[0])
<add> }
<add>
<add> // Query sandbox by container id
<add> req, err = http.NewRequest("GET", "/sandboxes?container-id="+cid2, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &sbList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(sbList) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add> if sbList[0].ContainerID != cid2 {
<add> t.Fatalf("Incongruent resource found: %v", sbList[0])
<add> }
<add>
<add> // Query sandbox by partial container id
<add> req, err = http.NewRequest("GET", "/sandboxes?partial-container-id="+cpid1, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add> if rsp.statusCode != http.StatusOK {
<add> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<add> }
<add>
<add> err = json.Unmarshal(rsp.body, &sbList)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(sbList) == 0 {
<add> t.Fatal("Empty response body")
<add> }
<add> if sbList[0].ContainerID != cid1 {
<add> t.Fatalf("Incongruent resource found: %v", sbList[0])
<add> }
<add>}
<add>
<add>func TestEndToEndErrorMessage(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> rsp := newWriter()
<add>
<add> // Cleanup local datastore file
<add> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<add>
<add> c, err := libnetwork.New()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer c.Stop()
<add> handleRequest := NewHTTPHandler(c)
<add>
<add> body := []byte{}
<add> lr := newLocalReader(body)
<add> req, err := http.NewRequest("POST", "/v1.19/networks", lr)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> handleRequest(rsp, req)
<add>
<add> if len(rsp.body) == 0 {
<add> t.Fatal("Empty response body.")
<add> }
<add> empty := []byte("\"\"")
<add> if bytes.Equal(empty, bytes.TrimSpace(rsp.body)) {
<add> t.Fatal("Empty response error message.")
<add> }
<add>}
<add>
<add>type bre struct{}
<add>
<add>func (b *bre) Error() string {
<add> return "I am a bad request error"
<add>}
<add>func (b *bre) BadRequest() {}
<add>
<add>type nfe struct{}
<add>
<add>func (n *nfe) Error() string {
<add> return "I am a not found error"
<add>}
<add>func (n *nfe) NotFound() {}
<add>
<add>type forb struct{}
<add>
<add>func (f *forb) Error() string {
<add> return "I am a bad request error"
<add>}
<add>func (f *forb) Forbidden() {}
<add>
<add>type notimpl struct{}
<add>
<add>func (nip *notimpl) Error() string {
<add> return "I am a not implemented error"
<add>}
<add>func (nip *notimpl) NotImplemented() {}
<add>
<add>type inter struct{}
<add>
<add>func (it *inter) Error() string {
<add> return "I am an internal error"
<add>}
<add>func (it *inter) Internal() {}
<add>
<add>type tout struct{}
<add>
<add>func (to *tout) Error() string {
<add> return "I am a timeout error"
<add>}
<add>func (to *tout) Timeout() {}
<add>
<add>type noserv struct{}
<add>
<add>func (nos *noserv) Error() string {
<add> return "I am a no service error"
<add>}
<add>func (nos *noserv) NoService() {}
<add>
<add>type notclassified struct{}
<add>
<add>func (noc *notclassified) Error() string {
<add> return "I am a non classified error"
<add>}
<add>
<add>func TestErrorConversion(t *testing.T) {
<add> if convertNetworkError(new(bre)).StatusCode != http.StatusBadRequest {
<add> t.Fatal("Failed to recognize BadRequest error")
<add> }
<add>
<add> if convertNetworkError(new(nfe)).StatusCode != http.StatusNotFound {
<add> t.Fatal("Failed to recognize NotFound error")
<add> }
<add>
<add> if convertNetworkError(new(forb)).StatusCode != http.StatusForbidden {
<add> t.Fatal("Failed to recognize Forbidden error")
<add> }
<add>
<add> if convertNetworkError(new(notimpl)).StatusCode != http.StatusNotImplemented {
<add> t.Fatal("Failed to recognize NotImplemented error")
<add> }
<add>
<add> if convertNetworkError(new(inter)).StatusCode != http.StatusInternalServerError {
<add> t.Fatal("Failed to recognize Internal error")
<add> }
<add>
<add> if convertNetworkError(new(tout)).StatusCode != http.StatusRequestTimeout {
<add> t.Fatal("Failed to recognize Timeout error")
<add> }
<add>
<add> if convertNetworkError(new(noserv)).StatusCode != http.StatusServiceUnavailable {
<add> t.Fatal("Failed to recognize No Service error")
<add> }
<add>
<add> if convertNetworkError(new(notclassified)).StatusCode != http.StatusInternalServerError {
<add> t.Fatal("Failed to recognize not classified error as Internal error")
<add> }
<add>}
<add>
<add>func TestFieldRegex(t *testing.T) {
<add> pr := regexp.MustCompile(regex)
<add> qr := regexp.MustCompile(`^` + qregx + `$`) // mux compiles it like this
<add>
<add> if pr.MatchString("") {
<add> t.Fatal("Unexpected match")
<add> }
<add> if !qr.MatchString("") {
<add> t.Fatal("Unexpected match failure")
<add> }
<add>
<add> if pr.MatchString(":") {
<add> t.Fatal("Unexpected match")
<add> }
<add> if qr.MatchString(":") {
<add> t.Fatal("Unexpected match")
<add> }
<add>
<add> if pr.MatchString(".") {
<add> t.Fatal("Unexpected match")
<add> }
<add> if qr.MatchString(".") {
<add> t.Fatal("Unexpected match")
<add> }
<add>}
<ide><path>libnetwork/api/api_test.go
<del>package api
<del>
<del>import (
<del> "bytes"
<del> "encoding/json"
<del> "errors"
<del> "fmt"
<del> "io"
<del> "net/http"
<del> "os"
<del> "regexp"
<del> "runtime"
<del> "testing"
<del>
<del> "github.com/docker/docker/pkg/reexec"
<del> "github.com/docker/docker/libnetwork"
<del> "github.com/docker/docker/libnetwork/datastore"
<del> "github.com/docker/docker/libnetwork/netlabel"
<del> "github.com/docker/docker/libnetwork/options"
<del> "github.com/docker/docker/libnetwork/testutils"
<del> "github.com/docker/docker/libnetwork/types"
<del>)
<del>
<del>const (
<del> bridgeNetType = "bridge"
<del> bridgeName = "docker0"
<del>)
<del>
<del>func i2s(i interface{}) string {
<del> s, ok := i.(string)
<del> if !ok {
<del> panic(fmt.Sprintf("Failed i2s for %v", i))
<del> }
<del> return s
<del>}
<del>
<del>func i2e(i interface{}) *endpointResource {
<del> s, ok := i.(*endpointResource)
<del> if !ok {
<del> panic(fmt.Sprintf("Failed i2e for %v", i))
<del> }
<del> return s
<del>}
<del>
<del>func i2eL(i interface{}) []*endpointResource {
<del> s, ok := i.([]*endpointResource)
<del> if !ok {
<del> panic(fmt.Sprintf("Failed i2eL for %v", i))
<del> }
<del> return s
<del>}
<del>
<del>func i2n(i interface{}) *networkResource {
<del> s, ok := i.(*networkResource)
<del> if !ok {
<del> panic(fmt.Sprintf("Failed i2n for %v", i))
<del> }
<del> return s
<del>}
<del>
<del>func i2nL(i interface{}) []*networkResource {
<del> s, ok := i.([]*networkResource)
<del> if !ok {
<del> panic(fmt.Sprintf("Failed i2nL for %v", i))
<del> }
<del> return s
<del>}
<del>
<del>func i2sb(i interface{}) *sandboxResource {
<del> s, ok := i.(*sandboxResource)
<del> if !ok {
<del> panic(fmt.Sprintf("Failed i2sb for %v", i))
<del> }
<del> return s
<del>}
<del>
<del>func i2sbL(i interface{}) []*sandboxResource {
<del> s, ok := i.([]*sandboxResource)
<del> if !ok {
<del> panic(fmt.Sprintf("Failed i2sbL for %v", i))
<del> }
<del> return s
<del>}
<del>
<del>func createTestNetwork(t *testing.T, network string) (libnetwork.NetworkController, libnetwork.Network) {
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> netOption := options.Generic{
<del> netlabel.GenericData: options.Generic{
<del> "BridgeName": network,
<del> },
<del> }
<del> netGeneric := libnetwork.NetworkOptionGeneric(netOption)
<del> nw, err := c.NewNetwork(bridgeNetType, network, "", netGeneric)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> return c, nw
<del>}
<del>
<del>func getExposedPorts() []types.TransportPort {
<del> return []types.TransportPort{
<del> {Proto: types.TCP, Port: uint16(5000)},
<del> {Proto: types.UDP, Port: uint16(400)},
<del> {Proto: types.TCP, Port: uint16(600)},
<del> }
<del>}
<del>
<del>func getPortMapping() []types.PortBinding {
<del> return []types.PortBinding{
<del> {Proto: types.TCP, Port: uint16(230), HostPort: uint16(23000)},
<del> {Proto: types.UDP, Port: uint16(200), HostPort: uint16(22000)},
<del> {Proto: types.TCP, Port: uint16(120), HostPort: uint16(12000)},
<del> }
<del>}
<del>
<del>func TestMain(m *testing.M) {
<del> if reexec.Init() {
<del> return
<del> }
<del> os.Exit(m.Run())
<del>}
<del>
<del>func TestSandboxOptionParser(t *testing.T) {
<del> hn := "host1"
<del> dn := "docker.com"
<del> hp := "/etc/hosts"
<del> rc := "/etc/resolv.conf"
<del> dnss := []string{"8.8.8.8", "172.28.34.5"}
<del> ehs := []extraHost{{Name: "extra1", Address: "172.28.9.1"}, {Name: "extra2", Address: "172.28.9.2"}}
<del>
<del> sb := sandboxCreate{
<del> HostName: hn,
<del> DomainName: dn,
<del> HostsPath: hp,
<del> ResolvConfPath: rc,
<del> DNS: dnss,
<del> ExtraHosts: ehs,
<del> UseDefaultSandbox: true,
<del> }
<del>
<del> if len(sb.parseOptions()) != 9 {
<del> t.Fatal("Failed to generate all libnetwork.SandboxOption methods")
<del> }
<del>}
<del>
<del>func TestJson(t *testing.T) {
<del> nc := networkCreate{NetworkType: bridgeNetType}
<del> b, err := json.Marshal(nc)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> var ncp networkCreate
<del> err = json.Unmarshal(b, &ncp)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if nc.NetworkType != ncp.NetworkType {
<del> t.Fatalf("Incorrect networkCreate after json encoding/deconding: %v", ncp)
<del> }
<del>
<del> jl := endpointJoin{SandboxID: "abcdef456789"}
<del> b, err = json.Marshal(jl)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> var jld endpointJoin
<del> err = json.Unmarshal(b, &jld)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if jl.SandboxID != jld.SandboxID {
<del> t.Fatalf("Incorrect endpointJoin after json encoding/deconding: %v", jld)
<del> }
<del>}
<del>
<del>func TestCreateDeleteNetwork(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del>
<del> badBody, err := json.Marshal("bad body")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars := make(map[string]string)
<del> _, errRsp := procCreateNetwork(c, nil, badBody)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected StatusBadRequest status code, got: %v", errRsp)
<del> }
<del>
<del> incompleteBody, err := json.Marshal(networkCreate{})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> _, errRsp = procCreateNetwork(c, vars, incompleteBody)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected StatusBadRequest status code, got: %v", errRsp)
<del> }
<del>
<del> dops := GetOpsMap("abc", "")
<del> nops := map[string]string{}
<del> nc := networkCreate{Name: "network_1", NetworkType: bridgeNetType, DriverOpts: dops, NetworkOpts: nops}
<del> goodBody, err := json.Marshal(nc)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> _, errRsp = procCreateNetwork(c, vars, goodBody)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> vars[urlNwName] = ""
<del> _, errRsp = procDeleteNetwork(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del>
<del> vars[urlNwName] = "abc"
<del> _, errRsp = procDeleteNetwork(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del>
<del> vars[urlNwName] = "network_1"
<del> _, errRsp = procDeleteNetwork(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>}
<del>
<del>func TestGetNetworksAndEndpoints(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del>
<del> ops := GetOpsMap("api_test_nw", "")
<del> nc := networkCreate{Name: "sh", NetworkType: bridgeNetType, DriverOpts: ops}
<del> body, err := json.Marshal(nc)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars := make(map[string]string)
<del> inid, errRsp := procCreateNetwork(c, vars, body)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> nid, ok := inid.(string)
<del> if !ok {
<del> t.FailNow()
<del> }
<del>
<del> ec1 := endpointCreate{
<del> Name: "ep1",
<del> }
<del> b1, err := json.Marshal(ec1)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> ec2 := endpointCreate{Name: "ep2"}
<del> b2, err := json.Marshal(ec2)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars[urlNwName] = "sh"
<del> vars[urlEpName] = "ep1"
<del> ieid1, errRsp := procCreateEndpoint(c, vars, b1)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> eid1 := i2s(ieid1)
<del> vars[urlEpName] = "ep2"
<del> ieid2, errRsp := procCreateEndpoint(c, vars, b2)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> eid2 := i2s(ieid2)
<del>
<del> vars[urlNwName] = ""
<del> vars[urlEpName] = "ep1"
<del> _, errRsp = procGetEndpoint(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode)
<del> }
<del>
<del> vars = make(map[string]string)
<del> vars[urlNwName] = "sh"
<del> vars[urlEpID] = ""
<del> _, errRsp = procGetEndpoint(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode)
<del> }
<del>
<del> vars = make(map[string]string)
<del> vars[urlNwID] = ""
<del> vars[urlEpID] = eid1
<del> _, errRsp = procGetEndpoint(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected to fail with http.StatusBadRequest, but got: %d", errRsp.StatusCode)
<del> }
<del>
<del> // nw by name and ep by id
<del> vars[urlNwName] = "sh"
<del> i1, errRsp := procGetEndpoint(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> // nw by name and ep by name
<del> delete(vars, urlEpID)
<del> vars[urlEpName] = "ep1"
<del> i2, errRsp := procGetEndpoint(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> // nw by id and ep by name
<del> delete(vars, urlNwName)
<del> vars[urlNwID] = nid
<del> i3, errRsp := procGetEndpoint(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> // nw by id and ep by id
<del> delete(vars, urlEpName)
<del> vars[urlEpID] = eid1
<del> i4, errRsp := procGetEndpoint(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> id1 := i2e(i1).ID
<del> if id1 != i2e(i2).ID || id1 != i2e(i3).ID || id1 != i2e(i4).ID {
<del> t.Fatalf("Endpoints retrieved via different query parameters differ: %v, %v, %v, %v", i1, i2, i3, i4)
<del> }
<del>
<del> vars[urlNwName] = ""
<del> _, errRsp = procGetEndpoints(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> delete(vars, urlNwName)
<del> vars[urlNwID] = "fakeID"
<del> _, errRsp = procGetEndpoints(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlNwID] = nid
<del> _, errRsp = procGetEndpoints(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> vars[urlNwName] = "sh"
<del> iepList, errRsp := procGetEndpoints(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> epList := i2eL(iepList)
<del> if len(epList) != 2 {
<del> t.Fatalf("Did not return the expected number (2) of endpoint resources: %d", len(epList))
<del> }
<del> if "sh" != epList[0].Network || "sh" != epList[1].Network {
<del> t.Fatal("Did not find expected network name in endpoint resources")
<del> }
<del>
<del> vars = make(map[string]string)
<del> vars[urlNwName] = ""
<del> _, errRsp = procGetNetwork(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> vars[urlNwName] = "shhhhh"
<del> _, errRsp = procGetNetwork(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> vars[urlNwName] = "sh"
<del> inr1, errRsp := procGetNetwork(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> nr1 := i2n(inr1)
<del>
<del> delete(vars, urlNwName)
<del> vars[urlNwID] = "acacac"
<del> _, errRsp = procGetNetwork(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure. Got: %v", errRsp)
<del> }
<del> vars[urlNwID] = nid
<del> inr2, errRsp := procGetNetwork(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("procgetNetworkByName() != procgetNetworkById(), %v vs %v", inr1, inr2)
<del> }
<del> nr2 := i2n(inr2)
<del> if nr1.Name != nr2.Name || nr1.Type != nr2.Type || nr1.ID != nr2.ID || len(nr1.Endpoints) != len(nr2.Endpoints) {
<del> t.Fatalf("Get by name and Get failure: %v", errRsp)
<del> }
<del>
<del> if len(nr1.Endpoints) != 2 {
<del> t.Fatalf("Did not find the expected number (2) of endpoint resources in the network resource: %d", len(nr1.Endpoints))
<del> }
<del> for _, er := range nr1.Endpoints {
<del> if er.ID != eid1 && er.ID != eid2 {
<del> t.Fatalf("Did not find the expected endpoint resources in the network resource: %v", nr1.Endpoints)
<del> }
<del> }
<del>
<del> iList, errRsp := procGetNetworks(c, nil, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> netList := i2nL(iList)
<del> if len(netList) != 1 {
<del> t.Fatal("Did not return the expected number of network resources")
<del> }
<del> if nid != netList[0].ID {
<del> t.Fatalf("Did not find expected network %s: %v", nid, netList)
<del> }
<del>
<del> _, errRsp = procDeleteNetwork(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlEpName] = "ep1"
<del> _, errRsp = procDeleteEndpoint(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> delete(vars, urlEpName)
<del> iepList, errRsp = procGetEndpoints(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> epList = i2eL(iepList)
<del> if len(epList) != 1 {
<del> t.Fatalf("Did not return the expected number (1) of endpoint resources: %d", len(epList))
<del> }
<del>
<del> vars[urlEpName] = "ep2"
<del> _, errRsp = procDeleteEndpoint(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> iepList, errRsp = procGetEndpoints(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> epList = i2eL(iepList)
<del> if len(epList) != 0 {
<del> t.Fatalf("Did not return the expected number (0) of endpoint resources: %d", len(epList))
<del> }
<del>
<del> _, errRsp = procDeleteNetwork(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> iList, errRsp = procGetNetworks(c, nil, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> netList = i2nL(iList)
<del> if len(netList) != 0 {
<del> t.Fatal("Did not return the expected number of network resources")
<del> }
<del>}
<del>
<del>func TestProcGetServices(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del>
<del> // Create 2 networks
<del> netName1 := "production"
<del> netOption := options.Generic{
<del> netlabel.GenericData: options.Generic{
<del> "BridgeName": netName1,
<del> },
<del> }
<del> nw1, err := c.NewNetwork(bridgeNetType, netName1, "", libnetwork.NetworkOptionGeneric(netOption))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> netName2 := "workdev"
<del> netOption = options.Generic{
<del> netlabel.GenericData: options.Generic{
<del> "BridgeName": netName2,
<del> },
<del> }
<del> nw2, err := c.NewNetwork(bridgeNetType, netName2, "", libnetwork.NetworkOptionGeneric(netOption))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars := make(map[string]string)
<del> li, errRsp := procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list := i2eL(li)
<del> if len(list) != 0 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>
<del> // Add a couple of services on one network and one on the other network
<del> ep11, err := nw1.CreateEndpoint("db-prod")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> ep12, err := nw1.CreateEndpoint("web-prod")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> ep21, err := nw2.CreateEndpoint("db-dev")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 3 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>
<del> // Filter by network
<del> vars[urlNwName] = netName1
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 2 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>
<del> vars[urlNwName] = netName2
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 1 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>
<del> vars[urlNwName] = "unknown-network"
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 0 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>
<del> // Query by name
<del> delete(vars, urlNwName)
<del> vars[urlEpName] = "db-prod"
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 1 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>
<del> vars[urlEpName] = "no-service"
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 0 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>
<del> // Query by id or partial id
<del> delete(vars, urlEpName)
<del> vars[urlEpPID] = ep12.ID()
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 1 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del> if list[0].ID != ep12.ID() {
<del> t.Fatalf("Unexpected element in response: %v", list)
<del> }
<del>
<del> vars[urlEpPID] = "non-id"
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 0 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>
<del> delete(vars, urlEpPID)
<del> err = ep11.Delete(false)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> err = ep12.Delete(false)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> err = ep21.Delete(false)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> li, errRsp = procGetServices(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> list = i2eL(li)
<del> if len(list) != 0 {
<del> t.Fatalf("Unexpected services in response: %v", list)
<del> }
<del>}
<del>
<del>func TestProcGetService(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> c, nw := createTestNetwork(t, "network")
<del> defer c.Stop()
<del> ep1, err := nw.CreateEndpoint("db")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> ep2, err := nw.CreateEndpoint("web")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars := map[string]string{urlEpID: ""}
<del> _, errRsp := procGetService(c, vars, nil)
<del> if errRsp.isOK() {
<del> t.Fatal("Expected failure, but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode)
<del> }
<del>
<del> vars[urlEpID] = "unknown-service-id"
<del> _, errRsp = procGetService(c, vars, nil)
<del> if errRsp.isOK() {
<del> t.Fatal("Expected failure, but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp)
<del> }
<del>
<del> vars[urlEpID] = ep1.ID()
<del> si, errRsp := procGetService(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> sv := i2e(si)
<del> if sv.ID != ep1.ID() {
<del> t.Fatalf("Unexpected service resource returned: %v", sv)
<del> }
<del>
<del> vars[urlEpID] = ep2.ID()
<del> si, errRsp = procGetService(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> sv = i2e(si)
<del> if sv.ID != ep2.ID() {
<del> t.Fatalf("Unexpected service resource returned: %v", sv)
<del> }
<del>}
<del>
<del>func TestProcPublishUnpublishService(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> c, _ := createTestNetwork(t, "network")
<del> defer c.Stop()
<del>
<del> vars := make(map[string]string)
<del>
<del> vbad, err := json.Marshal("bad service create data")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp := procPublishService(c, vars, vbad)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>
<del> b, err := json.Marshal(servicePublish{Name: ""})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp = procPublishService(c, vars, b)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>
<del> b, err = json.Marshal(servicePublish{Name: "db"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp = procPublishService(c, vars, b)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>
<del> b, err = json.Marshal(servicePublish{Name: "db", Network: "unknown-network"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp = procPublishService(c, vars, b)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<del> }
<del>
<del> b, err = json.Marshal(servicePublish{Name: "", Network: "network"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp = procPublishService(c, vars, b)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>
<del> b, err = json.Marshal(servicePublish{Name: "db", Network: "network"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp = procPublishService(c, vars, b)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> sp := servicePublish{
<del> Name: "web",
<del> Network: "network",
<del> }
<del> b, err = json.Marshal(sp)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> si, errRsp := procPublishService(c, vars, b)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> sid := i2s(si)
<del>
<del> vars[urlEpID] = ""
<del> _, errRsp = procUnpublishService(c, vars, nil)
<del> if errRsp.isOK() {
<del> t.Fatal("Expected failure but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>
<del> vars[urlEpID] = "unknown-service-id"
<del> _, errRsp = procUnpublishService(c, vars, nil)
<del> if errRsp.isOK() {
<del> t.Fatal("Expected failure but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<del> }
<del>
<del> vars[urlEpID] = sid
<del> _, errRsp = procUnpublishService(c, vars, nil)
<del> if !errRsp.isOK() {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> _, errRsp = procGetService(c, vars, nil)
<del> if errRsp.isOK() {
<del> t.Fatal("Expected failure, but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d. (%v)", http.StatusNotFound, errRsp.StatusCode, errRsp)
<del> }
<del>}
<del>
<del>func TestAttachDetachBackend(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> c, nw := createTestNetwork(t, "network")
<del> defer c.Stop()
<del> ep1, err := nw.CreateEndpoint("db")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars := make(map[string]string)
<del>
<del> vbad, err := json.Marshal("bad data")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp := procAttachBackend(c, vars, vbad)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlEpName] = "endpoint"
<del> bad, err := json.Marshal(endpointJoin{})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp = procAttachBackend(c, vars, bad)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<del> }
<del>
<del> vars[urlEpID] = "db"
<del> _, errRsp = procGetSandbox(c, vars, nil)
<del> if errRsp.isOK() {
<del> t.Fatalf("Expected failure. Got %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<del> }
<del>
<del> vars[urlEpName] = "db"
<del> _, errRsp = procAttachBackend(c, vars, bad)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>
<del> cid := "abcdefghi"
<del> sbox, err := c.NewSandbox(cid)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> sid := sbox.ID()
<del> defer sbox.Delete()
<del>
<del> jl := endpointJoin{SandboxID: sid}
<del> jlb, err := json.Marshal(jl)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> _, errRsp = procAttachBackend(c, vars, jlb)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure, got: %v", errRsp)
<del> }
<del>
<del> sli, errRsp := procGetSandboxes(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure, got: %v", errRsp)
<del> }
<del> sl := i2sbL(sli)
<del> if len(sl) != 1 {
<del> t.Fatalf("Did not find expected number of sandboxes attached to the service: %d", len(sl))
<del> }
<del> if sl[0].ContainerID != cid {
<del> t.Fatalf("Did not find expected sandbox attached to the service: %v", sl[0])
<del> }
<del>
<del> _, errRsp = procUnpublishService(c, vars, nil)
<del> if errRsp.isOK() {
<del> t.Fatal("Expected failure but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusForbidden {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusForbidden, errRsp)
<del> }
<del>
<del> vars[urlEpName] = "endpoint"
<del> _, errRsp = procDetachBackend(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusNotFound, errRsp)
<del> }
<del>
<del> vars[urlEpName] = "db"
<del> _, errRsp = procDetachBackend(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>
<del> vars[urlSbID] = sid
<del> _, errRsp = procDetachBackend(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure, got: %v", errRsp)
<del> }
<del>
<del> delete(vars, urlEpID)
<del> si, errRsp := procGetSandbox(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure, got: %v", errRsp)
<del> }
<del> sb := i2sb(si)
<del> if sb.ContainerID != cid {
<del> t.Fatalf("Did not find expected sandbox. Got %v", sb)
<del> }
<del>
<del> err = ep1.Delete(false)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>}
<del>
<del>func TestDetectGetNetworksInvalidQueryComposition(t *testing.T) {
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del>
<del> vars := map[string]string{urlNwName: "x", urlNwPID: "y"}
<del> _, errRsp := procGetNetworks(c, vars, nil)
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>}
<del>
<del>func TestDetectGetEndpointsInvalidQueryComposition(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> c, _ := createTestNetwork(t, "network")
<del> defer c.Stop()
<del>
<del> vars := map[string]string{urlNwName: "network", urlEpName: "x", urlEpPID: "y"}
<del> _, errRsp := procGetEndpoints(c, vars, nil)
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>}
<del>
<del>func TestDetectGetServicesInvalidQueryComposition(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> c, _ := createTestNetwork(t, "network")
<del> defer c.Stop()
<del>
<del> vars := map[string]string{urlNwName: "network", urlEpName: "x", urlEpPID: "y"}
<del> _, errRsp := procGetServices(c, vars, nil)
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d. Got: %v", http.StatusBadRequest, errRsp)
<del> }
<del>}
<del>
<del>func TestFindNetworkUtilPanic(t *testing.T) {
<del> defer checkPanic(t)
<del> findNetwork(nil, "", -1)
<del>}
<del>
<del>func TestFindNetworkUtil(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> c, nw := createTestNetwork(t, "network")
<del> defer c.Stop()
<del>
<del> nid := nw.ID()
<del>
<del> _, errRsp := findNetwork(c, "", byName)
<del> if errRsp == &successResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode)
<del> }
<del>
<del> n, errRsp := findNetwork(c, nid, byID)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> if n == nil {
<del> t.Fatal("Unexpected nil libnetwork.Network")
<del> }
<del> if nid != n.ID() {
<del> t.Fatalf("Incorrect libnetwork.Network resource. It has different id: %v", n)
<del> }
<del> if "network" != n.Name() {
<del> t.Fatalf("Incorrect libnetwork.Network resource. It has different name: %v", n)
<del> }
<del>
<del> n, errRsp = findNetwork(c, "network", byName)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> if n == nil {
<del> t.Fatal("Unexpected nil libnetwork.Network")
<del> }
<del> if nid != n.ID() {
<del> t.Fatalf("Incorrect libnetwork.Network resource. It has different id: %v", n)
<del> }
<del> if "network" != n.Name() {
<del> t.Fatalf("Incorrect libnetwork.Network resource. It has different name: %v", n)
<del> }
<del>
<del> if err := n.Delete(); err != nil {
<del> t.Fatalf("Failed to delete the network: %s", err.Error())
<del> }
<del>
<del> _, errRsp = findNetwork(c, nid, byID)
<del> if errRsp == &successResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<del> }
<del>
<del> _, errRsp = findNetwork(c, "network", byName)
<del> if errRsp == &successResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<del> }
<del>}
<del>
<del>func TestCreateDeleteEndpoints(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del>
<del> nc := networkCreate{Name: "firstNet", NetworkType: bridgeNetType}
<del> body, err := json.Marshal(nc)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars := make(map[string]string)
<del> i, errRsp := procCreateNetwork(c, vars, body)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> nid := i2s(i)
<del>
<del> vbad, err := json.Marshal("bad endpoint create data")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars[urlNwName] = "firstNet"
<del> _, errRsp = procCreateEndpoint(c, vars, vbad)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del>
<del> b, err := json.Marshal(endpointCreate{Name: ""})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars[urlNwName] = "secondNet"
<del> _, errRsp = procCreateEndpoint(c, vars, b)
<del> if errRsp == &createdResponse {
<del> t.Fatal("Expected to fail but succeeded")
<del> }
<del>
<del> vars[urlNwName] = "firstNet"
<del> _, errRsp = procCreateEndpoint(c, vars, b)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<del> }
<del>
<del> b, err = json.Marshal(endpointCreate{Name: "firstEp"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> i, errRsp = procCreateEndpoint(c, vars, b)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del> eid := i2s(i)
<del>
<del> _, errRsp = findEndpoint(c, "myNet", "firstEp", byName, byName)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure but succeeded: %v", errRsp)
<del> }
<del>
<del> ep0, errRsp := findEndpoint(c, nid, "firstEp", byID, byName)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> ep1, errRsp := findEndpoint(c, "firstNet", "firstEp", byName, byName)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> ep2, errRsp := findEndpoint(c, nid, eid, byID, byID)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> ep3, errRsp := findEndpoint(c, "firstNet", eid, byName, byID)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> if ep0.ID() != ep1.ID() || ep0.ID() != ep2.ID() || ep0.ID() != ep3.ID() {
<del> t.Fatalf("Different queries returned different endpoints: \nep0: %v\nep1: %v\nep2: %v\nep3: %v", ep0, ep1, ep2, ep3)
<del> }
<del>
<del> vars = make(map[string]string)
<del> vars[urlNwName] = ""
<del> vars[urlEpName] = "ep1"
<del> _, errRsp = procDeleteEndpoint(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlNwName] = "firstNet"
<del> vars[urlEpName] = ""
<del> _, errRsp = procDeleteEndpoint(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlEpName] = "ep2"
<del> _, errRsp = procDeleteEndpoint(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlEpName] = "firstEp"
<del> _, errRsp = procDeleteEndpoint(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> _, errRsp = findEndpoint(c, "firstNet", "firstEp", byName, byName)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>}
<del>
<del>func TestJoinLeave(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del>
<del> nb, err := json.Marshal(networkCreate{Name: "network", NetworkType: bridgeNetType})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> vars := make(map[string]string)
<del> _, errRsp := procCreateNetwork(c, vars, nb)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> eb, err := json.Marshal(endpointCreate{Name: "endpoint"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> vars[urlNwName] = "network"
<del> _, errRsp = procCreateEndpoint(c, vars, eb)
<del> if errRsp != &createdResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> vbad, err := json.Marshal("bad data")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp = procJoinEndpoint(c, vars, vbad)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlEpName] = "endpoint"
<del> bad, err := json.Marshal(endpointJoin{})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> _, errRsp = procJoinEndpoint(c, vars, bad)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> cid := "abcdefghi"
<del> sb, err := c.NewSandbox(cid)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer sb.Delete()
<del>
<del> jl := endpointJoin{SandboxID: sb.ID()}
<del> jlb, err := json.Marshal(jl)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> vars = make(map[string]string)
<del> vars[urlNwName] = ""
<del> vars[urlEpName] = ""
<del> _, errRsp = procJoinEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlNwName] = "network"
<del> vars[urlEpName] = ""
<del> _, errRsp = procJoinEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlEpName] = "epoint"
<del> _, errRsp = procJoinEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> // bad labels
<del> vars[urlEpName] = "endpoint"
<del> key, errRsp := procJoinEndpoint(c, vars, jlb)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure, got: %v", errRsp)
<del> }
<del>
<del> keyStr := i2s(key)
<del> if keyStr == "" {
<del> t.Fatal("Empty sandbox key")
<del> }
<del> _, errRsp = procDeleteEndpoint(c, vars, nil)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlNwName] = "network2"
<del> _, errRsp = procLeaveEndpoint(c, vars, vbad)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> _, errRsp = procLeaveEndpoint(c, vars, bad)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> vars = make(map[string]string)
<del> vars[urlNwName] = ""
<del> vars[urlEpName] = ""
<del> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> vars[urlNwName] = "network"
<del> vars[urlEpName] = ""
<del> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> vars[urlEpName] = "2epoint"
<del> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del> vars[urlEpName] = "epoint"
<del> vars[urlCnID] = "who"
<del> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> delete(vars, urlCnID)
<del> vars[urlEpName] = "endpoint"
<del> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> vars[urlSbID] = sb.ID()
<del> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> _, errRsp = procLeaveEndpoint(c, vars, jlb)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, got: %v", errRsp)
<del> }
<del>
<del> _, errRsp = procDeleteEndpoint(c, vars, nil)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>}
<del>
<del>func TestFindEndpointUtilPanic(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del> defer checkPanic(t)
<del> c, nw := createTestNetwork(t, "network")
<del> defer c.Stop()
<del>
<del> nid := nw.ID()
<del> findEndpoint(c, nid, "", byID, -1)
<del>}
<del>
<del>func TestFindServiceUtilPanic(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del> defer checkPanic(t)
<del> c, _ := createTestNetwork(t, "network")
<del> defer c.Stop()
<del>
<del> findService(c, "random_service", -1)
<del>}
<del>
<del>func TestFindEndpointUtil(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> c, nw := createTestNetwork(t, "network")
<del> defer c.Stop()
<del>
<del> nid := nw.ID()
<del>
<del> ep, err := nw.CreateEndpoint("secondEp", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> eid := ep.ID()
<del>
<del> _, errRsp := findEndpoint(c, nid, "", byID, byName)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, but got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusBadRequest {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusBadRequest, errRsp.StatusCode)
<del> }
<del>
<del> ep0, errRsp := findEndpoint(c, nid, "secondEp", byID, byName)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> ep1, errRsp := findEndpoint(c, "network", "secondEp", byName, byName)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> ep2, errRsp := findEndpoint(c, nid, eid, byID, byID)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> ep3, errRsp := findEndpoint(c, "network", eid, byName, byID)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> ep4, errRsp := findService(c, "secondEp", byName)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> ep5, errRsp := findService(c, eid, byID)
<del> if errRsp != &successResponse {
<del> t.Fatalf("Unexpected failure: %v", errRsp)
<del> }
<del>
<del> if ep0.ID() != ep1.ID() || ep0.ID() != ep2.ID() ||
<del> ep0.ID() != ep3.ID() || ep0.ID() != ep4.ID() || ep0.ID() != ep5.ID() {
<del> t.Fatal("Different queries returned different endpoints")
<del> }
<del>
<del> ep.Delete(false)
<del>
<del> _, errRsp = findEndpoint(c, nid, "secondEp", byID, byName)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, but got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<del> }
<del>
<del> _, errRsp = findEndpoint(c, "network", "secondEp", byName, byName)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, but got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<del> }
<del>
<del> _, errRsp = findEndpoint(c, nid, eid, byID, byID)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, but got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<del> }
<del>
<del> _, errRsp = findEndpoint(c, "network", eid, byName, byID)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, but got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<del> }
<del>
<del> _, errRsp = findService(c, "secondEp", byName)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, but got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<del> }
<del>
<del> _, errRsp = findService(c, eid, byID)
<del> if errRsp == &successResponse {
<del> t.Fatalf("Expected failure, but got: %v", errRsp)
<del> }
<del> if errRsp.StatusCode != http.StatusNotFound {
<del> t.Fatalf("Expected %d, but got: %d", http.StatusNotFound, errRsp.StatusCode)
<del> }
<del>}
<del>
<del>func TestEndpointToService(t *testing.T) {
<del> r := &responseStatus{Status: "this is one endpoint", StatusCode: http.StatusOK}
<del> r = endpointToService(r)
<del> if r.Status != "this is one service" {
<del> t.Fatalf("endpointToService returned unexpected status string: %s", r.Status)
<del> }
<del>
<del> r = &responseStatus{Status: "this is one network", StatusCode: http.StatusOK}
<del> r = endpointToService(r)
<del> if r.Status != "this is one network" {
<del> t.Fatalf("endpointToService returned unexpected status string: %s", r.Status)
<del> }
<del>}
<del>
<del>func checkPanic(t *testing.T) {
<del> if r := recover(); r != nil {
<del> if _, ok := r.(runtime.Error); ok {
<del> panic(r)
<del> }
<del> } else {
<del> t.Fatal("Expected to panic, but succeeded")
<del> }
<del>}
<del>
<del>func TestDetectNetworkTargetPanic(t *testing.T) {
<del> defer checkPanic(t)
<del> vars := make(map[string]string)
<del> detectNetworkTarget(vars)
<del>}
<del>
<del>func TestDetectEndpointTargetPanic(t *testing.T) {
<del> defer checkPanic(t)
<del> vars := make(map[string]string)
<del> detectEndpointTarget(vars)
<del>}
<del>
<del>func TestResponseStatus(t *testing.T) {
<del> list := []int{
<del> http.StatusBadGateway,
<del> http.StatusBadRequest,
<del> http.StatusConflict,
<del> http.StatusContinue,
<del> http.StatusExpectationFailed,
<del> http.StatusForbidden,
<del> http.StatusFound,
<del> http.StatusGatewayTimeout,
<del> http.StatusGone,
<del> http.StatusHTTPVersionNotSupported,
<del> http.StatusInternalServerError,
<del> http.StatusLengthRequired,
<del> http.StatusMethodNotAllowed,
<del> http.StatusMovedPermanently,
<del> http.StatusMultipleChoices,
<del> http.StatusNoContent,
<del> http.StatusNonAuthoritativeInfo,
<del> http.StatusNotAcceptable,
<del> http.StatusNotFound,
<del> http.StatusNotModified,
<del> http.StatusPartialContent,
<del> http.StatusPaymentRequired,
<del> http.StatusPreconditionFailed,
<del> http.StatusProxyAuthRequired,
<del> http.StatusRequestEntityTooLarge,
<del> http.StatusRequestTimeout,
<del> http.StatusRequestURITooLong,
<del> http.StatusRequestedRangeNotSatisfiable,
<del> http.StatusResetContent,
<del> http.StatusServiceUnavailable,
<del> http.StatusSwitchingProtocols,
<del> http.StatusTemporaryRedirect,
<del> http.StatusUnauthorized,
<del> http.StatusUnsupportedMediaType,
<del> http.StatusUseProxy,
<del> }
<del> for _, c := range list {
<del> r := responseStatus{StatusCode: c}
<del> if r.isOK() {
<del> t.Fatalf("isOK() returned true for code% d", c)
<del> }
<del> }
<del>
<del> r := responseStatus{StatusCode: http.StatusOK}
<del> if !r.isOK() {
<del> t.Fatal("isOK() failed")
<del> }
<del>
<del> r = responseStatus{StatusCode: http.StatusCreated}
<del> if !r.isOK() {
<del> t.Fatal("isOK() failed")
<del> }
<del>}
<del>
<del>// Local structs for end to end testing of api.go
<del>type localReader struct {
<del> data []byte
<del> beBad bool
<del>}
<del>
<del>func newLocalReader(data []byte) *localReader {
<del> lr := &localReader{data: make([]byte, len(data))}
<del> copy(lr.data, data)
<del> return lr
<del>}
<del>
<del>func (l *localReader) Read(p []byte) (n int, err error) {
<del> if l.beBad {
<del> return 0, errors.New("I am a bad reader")
<del> }
<del> if p == nil {
<del> return -1, errors.New("nil buffer passed")
<del> }
<del> if l.data == nil || len(l.data) == 0 {
<del> return 0, io.EOF
<del> }
<del> copy(p[:], l.data[:])
<del> return len(l.data), io.EOF
<del>}
<del>
<del>type localResponseWriter struct {
<del> body []byte
<del> statusCode int
<del>}
<del>
<del>func newWriter() *localResponseWriter {
<del> return &localResponseWriter{}
<del>}
<del>
<del>func (f *localResponseWriter) Header() http.Header {
<del> return make(map[string][]string, 0)
<del>}
<del>
<del>func (f *localResponseWriter) Write(data []byte) (int, error) {
<del> if data == nil {
<del> return -1, errors.New("nil data passed")
<del> }
<del>
<del> f.body = make([]byte, len(data))
<del> copy(f.body, data)
<del>
<del> return len(f.body), nil
<del>}
<del>
<del>func (f *localResponseWriter) WriteHeader(c int) {
<del> f.statusCode = c
<del>}
<del>
<del>func testWriteJSON(t *testing.T, testCode int, testData interface{}) {
<del> testDataMarshalled, err := json.Marshal(testData)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> rsp := newWriter()
<del> writeJSON(rsp, testCode, testData)
<del> if rsp.statusCode != testCode {
<del> t.Fatalf("writeJSON() failed to set the status code. Expected %d. Got %d", testCode, rsp.statusCode)
<del> }
<del> // writeJSON calls json.Encode and it appends '\n' to the result,
<del> // while json.Marshal not
<del> expected := append(testDataMarshalled, byte('\n'))
<del> if !bytes.Equal(expected, rsp.body) {
<del> t.Fatalf("writeJSON() failed to set the body. Expected %q. Got %q", expected, rsp.body)
<del> }
<del>}
<del>
<del>func TestWriteJSON(t *testing.T) {
<del> testWriteJSON(t, 55, "test data as string")
<del> testWriteJSON(t, 55, []byte("test data as bytes"))
<del>}
<del>
<del>func TestHttpHandlerUninit(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del>
<del> h := &httpHandler{c: c}
<del> h.initRouter()
<del> if h.r == nil {
<del> t.Fatal("initRouter() did not initialize the router")
<del> }
<del>
<del> rsp := newWriter()
<del> req, err := http.NewRequest("GET", "/v1.19/networks", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> handleRequest := NewHTTPHandler(nil)
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusServiceUnavailable {
<del> t.Fatalf("Expected (%d). Got (%d): %s", http.StatusServiceUnavailable, rsp.statusCode, rsp.body)
<del> }
<del>
<del> handleRequest = NewHTTPHandler(c)
<del>
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Expected (%d). Got: (%d): %s", http.StatusOK, rsp.statusCode, rsp.body)
<del> }
<del>
<del> var list []*networkResource
<del> err = json.Unmarshal(rsp.body, &list)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(list) != 0 {
<del> t.Fatalf("Expected empty list. Got %v", list)
<del> }
<del>
<del> n, err := c.NewNetwork(bridgeNetType, "didietro", "", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> nwr := buildNetworkResource(n)
<del> expected, err := json.Marshal([]*networkResource{nwr})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del> if len(rsp.body) == 0 {
<del> t.Fatal("Empty list of networks")
<del> }
<del> if bytes.Equal(rsp.body, expected) {
<del> t.Fatal("Incorrect list of networks in response's body")
<del> }
<del>}
<del>
<del>func TestHttpHandlerBadBody(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> rsp := newWriter()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del> handleRequest := NewHTTPHandler(c)
<del>
<del> req, err := http.NewRequest("POST", "/v1.19/networks", &localReader{beBad: true})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusBadRequest {
<del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusBadRequest, rsp.statusCode, string(rsp.body))
<del> }
<del>
<del> body := []byte{}
<del> lr := newLocalReader(body)
<del> req, err = http.NewRequest("POST", "/v1.19/networks", lr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusBadRequest {
<del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusBadRequest, rsp.statusCode, string(rsp.body))
<del> }
<del>}
<del>
<del>func TestEndToEnd(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> rsp := newWriter()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del>
<del> handleRequest := NewHTTPHandler(c)
<del>
<del> dops := GetOpsMap("cdef", "1460")
<del> nops := map[string]string{}
<del>
<del> // Create network
<del> nc := networkCreate{Name: "network-fiftyfive", NetworkType: bridgeNetType, DriverOpts: dops, NetworkOpts: nops}
<del> body, err := json.Marshal(nc)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> lr := newLocalReader(body)
<del> req, err := http.NewRequest("POST", "/v1.19/networks", lr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusCreated {
<del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<del> }
<del> if len(rsp.body) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del>
<del> var nid string
<del> err = json.Unmarshal(rsp.body, &nid)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> // Query networks collection
<del> req, err = http.NewRequest("GET", "/v1.19/networks?name=", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del> var list []*networkResource
<del> err = json.Unmarshal(rsp.body, &list)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(list) != 0 {
<del> t.Fatalf("Expected empty list. Got %v", list)
<del> }
<del>
<del> req, err = http.NewRequest("GET", "/v1.19/networks", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> b0 := make([]byte, len(rsp.body))
<del> copy(b0, rsp.body)
<del>
<del> req, err = http.NewRequest("GET", "/v1.19/networks?name=network-fiftyfive", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> if !bytes.Equal(b0, rsp.body) {
<del> t.Fatal("Expected same body from GET /networks and GET /networks?name=<nw> when only network <nw> exist.")
<del> }
<del>
<del> // Query network by name
<del> req, err = http.NewRequest("GET", "/v1.19/networks?name=culo", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> err = json.Unmarshal(rsp.body, &list)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(list) != 0 {
<del> t.Fatalf("Expected empty list. Got %v", list)
<del> }
<del>
<del> req, err = http.NewRequest("GET", "/v1.19/networks?name=network-fiftyfive", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> err = json.Unmarshal(rsp.body, &list)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(list) == 0 {
<del> t.Fatal("Expected non empty list")
<del> }
<del> if list[0].Name != "network-fiftyfive" || nid != list[0].ID {
<del> t.Fatalf("Incongruent resource found: %v", list[0])
<del> }
<del>
<del> // Query network by partial id
<del> chars := []byte(nid)
<del> partial := string(chars[0 : len(chars)/2])
<del> req, err = http.NewRequest("GET", "/v1.19/networks?partial-id="+partial, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> err = json.Unmarshal(rsp.body, &list)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(list) == 0 {
<del> t.Fatal("Expected non empty list")
<del> }
<del> if list[0].Name != "network-fiftyfive" || nid != list[0].ID {
<del> t.Fatalf("Incongruent resource found: %v", list[0])
<del> }
<del>
<del> // Get network by id
<del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> var nwr networkResource
<del> err = json.Unmarshal(rsp.body, &nwr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if nwr.Name != "network-fiftyfive" || nid != nwr.ID {
<del> t.Fatalf("Incongruent resource found: %v", nwr)
<del> }
<del>
<del> // Create endpoint
<del> eb, err := json.Marshal(endpointCreate{Name: "ep-TwentyTwo"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> lr = newLocalReader(eb)
<del> req, err = http.NewRequest("POST", "/v1.19/networks/"+nid+"/endpoints", lr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusCreated {
<del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<del> }
<del> if len(rsp.body) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del>
<del> var eid string
<del> err = json.Unmarshal(rsp.body, &eid)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> // Query endpoint(s)
<del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?name=bla", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del> var epList []*endpointResource
<del> err = json.Unmarshal(rsp.body, &epList)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(epList) != 0 {
<del> t.Fatalf("Expected empty list. Got %v", epList)
<del> }
<del>
<del> // Query endpoint by name
<del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?name=ep-TwentyTwo", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> err = json.Unmarshal(rsp.body, &epList)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(epList) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del> if epList[0].Name != "ep-TwentyTwo" || eid != epList[0].ID {
<del> t.Fatalf("Incongruent resource found: %v", epList[0])
<del> }
<del>
<del> // Query endpoint by partial id
<del> chars = []byte(eid)
<del> partial = string(chars[0 : len(chars)/2])
<del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints?partial-id="+partial, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> err = json.Unmarshal(rsp.body, &epList)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(epList) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del> if epList[0].Name != "ep-TwentyTwo" || eid != epList[0].ID {
<del> t.Fatalf("Incongruent resource found: %v", epList[0])
<del> }
<del>
<del> // Get endpoint by id
<del> req, err = http.NewRequest("GET", "/v1.19/networks/"+nid+"/endpoints/"+eid, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> var epr endpointResource
<del> err = json.Unmarshal(rsp.body, &epr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if epr.Name != "ep-TwentyTwo" || epr.ID != eid {
<del> t.Fatalf("Incongruent resource found: %v", epr)
<del> }
<del>
<del> // Store two container ids and one partial ids
<del> cid1 := "container10010000000"
<del> cid2 := "container20010000000"
<del> chars = []byte(cid1)
<del> cpid1 := string(chars[0 : len(chars)/2])
<del>
<del> // Create sandboxes
<del> sb1, err := json.Marshal(sandboxCreate{
<del> ContainerID: cid1,
<del> PortMapping: getPortMapping(),
<del> })
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> lr = newLocalReader(sb1)
<del> req, err = http.NewRequest("POST", "/v5.22/sandboxes", lr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusCreated {
<del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<del> }
<del> if len(rsp.body) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del> // Get sandbox id and partial id
<del> var sid1 string
<del> err = json.Unmarshal(rsp.body, &sid1)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> sb2, err := json.Marshal(sandboxCreate{
<del> ContainerID: cid2,
<del> ExposedPorts: getExposedPorts(),
<del> })
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> lr = newLocalReader(sb2)
<del> req, err = http.NewRequest("POST", "/v5.22/sandboxes", lr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusCreated {
<del> t.Fatalf("Unexpected status code. Expected (%d). Got (%d): %s.", http.StatusCreated, rsp.statusCode, string(rsp.body))
<del> }
<del> if len(rsp.body) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del> // Get sandbox id and partial id
<del> var sid2 string
<del> err = json.Unmarshal(rsp.body, &sid2)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> chars = []byte(sid2)
<del> spid2 := string(chars[0 : len(chars)/2])
<del>
<del> // Query sandboxes
<del> req, err = http.NewRequest("GET", "/sandboxes", nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Expected StatusOK. Got (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> var sbList []*sandboxResource
<del> err = json.Unmarshal(rsp.body, &sbList)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(sbList) != 2 {
<del> t.Fatalf("Expected 2 elements in list. Got %v", sbList)
<del> }
<del>
<del> // Get sandbox by id
<del> req, err = http.NewRequest("GET", "/sandboxes/"+sid1, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> var sbr sandboxResource
<del> err = json.Unmarshal(rsp.body, &sbr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if sbr.ContainerID != cid1 {
<del> t.Fatalf("Incongruent resource found: %v", sbr)
<del> }
<del>
<del> // Query sandbox by partial sandbox id
<del> req, err = http.NewRequest("GET", "/sandboxes?partial-id="+spid2, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> err = json.Unmarshal(rsp.body, &sbList)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(sbList) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del> if sbList[0].ID != sid2 {
<del> t.Fatalf("Incongruent resource found: %v", sbList[0])
<del> }
<del>
<del> // Query sandbox by container id
<del> req, err = http.NewRequest("GET", "/sandboxes?container-id="+cid2, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> err = json.Unmarshal(rsp.body, &sbList)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(sbList) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del> if sbList[0].ContainerID != cid2 {
<del> t.Fatalf("Incongruent resource found: %v", sbList[0])
<del> }
<del>
<del> // Query sandbox by partial container id
<del> req, err = http.NewRequest("GET", "/sandboxes?partial-container-id="+cpid1, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del> if rsp.statusCode != http.StatusOK {
<del> t.Fatalf("Unexpected failure: (%d): %s", rsp.statusCode, rsp.body)
<del> }
<del>
<del> err = json.Unmarshal(rsp.body, &sbList)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if len(sbList) == 0 {
<del> t.Fatal("Empty response body")
<del> }
<del> if sbList[0].ContainerID != cid1 {
<del> t.Fatalf("Incongruent resource found: %v", sbList[0])
<del> }
<del>}
<del>
<del>func TestEndToEndErrorMessage(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> rsp := newWriter()
<del>
<del> // Cleanup local datastore file
<del> os.Remove(datastore.DefaultScopes("")[datastore.LocalScope].Client.Address)
<del>
<del> c, err := libnetwork.New()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer c.Stop()
<del> handleRequest := NewHTTPHandler(c)
<del>
<del> body := []byte{}
<del> lr := newLocalReader(body)
<del> req, err := http.NewRequest("POST", "/v1.19/networks", lr)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> handleRequest(rsp, req)
<del>
<del> if len(rsp.body) == 0 {
<del> t.Fatal("Empty response body.")
<del> }
<del> empty := []byte("\"\"")
<del> if bytes.Equal(empty, bytes.TrimSpace(rsp.body)) {
<del> t.Fatal("Empty response error message.")
<del> }
<del>}
<del>
<del>type bre struct{}
<del>
<del>func (b *bre) Error() string {
<del> return "I am a bad request error"
<del>}
<del>func (b *bre) BadRequest() {}
<del>
<del>type nfe struct{}
<del>
<del>func (n *nfe) Error() string {
<del> return "I am a not found error"
<del>}
<del>func (n *nfe) NotFound() {}
<del>
<del>type forb struct{}
<del>
<del>func (f *forb) Error() string {
<del> return "I am a bad request error"
<del>}
<del>func (f *forb) Forbidden() {}
<del>
<del>type notimpl struct{}
<del>
<del>func (nip *notimpl) Error() string {
<del> return "I am a not implemented error"
<del>}
<del>func (nip *notimpl) NotImplemented() {}
<del>
<del>type inter struct{}
<del>
<del>func (it *inter) Error() string {
<del> return "I am an internal error"
<del>}
<del>func (it *inter) Internal() {}
<del>
<del>type tout struct{}
<del>
<del>func (to *tout) Error() string {
<del> return "I am a timeout error"
<del>}
<del>func (to *tout) Timeout() {}
<del>
<del>type noserv struct{}
<del>
<del>func (nos *noserv) Error() string {
<del> return "I am a no service error"
<del>}
<del>func (nos *noserv) NoService() {}
<del>
<del>type notclassified struct{}
<del>
<del>func (noc *notclassified) Error() string {
<del> return "I am a non classified error"
<del>}
<del>
<del>func TestErrorConversion(t *testing.T) {
<del> if convertNetworkError(new(bre)).StatusCode != http.StatusBadRequest {
<del> t.Fatal("Failed to recognize BadRequest error")
<del> }
<del>
<del> if convertNetworkError(new(nfe)).StatusCode != http.StatusNotFound {
<del> t.Fatal("Failed to recognize NotFound error")
<del> }
<del>
<del> if convertNetworkError(new(forb)).StatusCode != http.StatusForbidden {
<del> t.Fatal("Failed to recognize Forbidden error")
<del> }
<del>
<del> if convertNetworkError(new(notimpl)).StatusCode != http.StatusNotImplemented {
<del> t.Fatal("Failed to recognize NotImplemented error")
<del> }
<del>
<del> if convertNetworkError(new(inter)).StatusCode != http.StatusInternalServerError {
<del> t.Fatal("Failed to recognize Internal error")
<del> }
<del>
<del> if convertNetworkError(new(tout)).StatusCode != http.StatusRequestTimeout {
<del> t.Fatal("Failed to recognize Timeout error")
<del> }
<del>
<del> if convertNetworkError(new(noserv)).StatusCode != http.StatusServiceUnavailable {
<del> t.Fatal("Failed to recognize No Service error")
<del> }
<del>
<del> if convertNetworkError(new(notclassified)).StatusCode != http.StatusInternalServerError {
<del> t.Fatal("Failed to recognize not classified error as Internal error")
<del> }
<del>}
<del>
<del>func TestFieldRegex(t *testing.T) {
<del> pr := regexp.MustCompile(regex)
<del> qr := regexp.MustCompile(`^` + qregx + `$`) // mux compiles it like this
<del>
<del> if pr.MatchString("") {
<del> t.Fatal("Unexpected match")
<del> }
<del> if !qr.MatchString("") {
<del> t.Fatal("Unexpected match failure")
<del> }
<del>
<del> if pr.MatchString(":") {
<del> t.Fatal("Unexpected match")
<del> }
<del> if qr.MatchString(":") {
<del> t.Fatal("Unexpected match")
<del> }
<del>
<del> if pr.MatchString(".") {
<del> t.Fatal("Unexpected match")
<del> }
<del> if qr.MatchString(".") {
<del> t.Fatal("Unexpected match")
<del> }
<del>}
<ide><path>libnetwork/cmd/dnet/dnet_windows.go
<ide> func setupDumpStackTrap() {
<ide> }
<ide> ev, _ := windows.UTF16PtrFromString("Global\\docker-daemon-" + fmt.Sprint(os.Getpid()))
<ide> if h, _ := windows.CreateEvent(&sa, 0, 0, ev); h != 0 {
<del> logrus.Debugf("Stackdump - waiting signal at %s", ev)
<add> logrus.Debugf("Stackdump - waiting signal at %d", *ev)
<ide> for {
<ide> windows.WaitForSingleObject(h, windows.INFINITE)
<ide> signal.DumpStacks("")
<ide><path>libnetwork/drivers/bridge/bridge.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/bridge_store.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/bridge_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/errors.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/interface.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/interface_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/link.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/link_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/network_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/port_mapping.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/port_mapping_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> type setupStep func(*networkConfiguration, *bridgeInterface) error
<ide><path>libnetwork/drivers/bridge/setup_bridgenetfiltering.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_bridgenetfiltering_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import "testing"
<ide><path>libnetwork/drivers/bridge/setup_device.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_device_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_firewalld.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import "github.com/docker/docker/libnetwork/iptables"
<ide><path>libnetwork/drivers/bridge/setup_ip_forwarding.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_ip_forwarding_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_ip_tables.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_ip_tables_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_ipv4.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_ipv4_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_ipv6.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_ipv6_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_verify.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/bridge/setup_verify_test.go
<add>// +build linux
<add>
<ide> package bridge
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan_endpoint.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan_joinleave.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan_network.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan_setup.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan_setup_test.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan_state.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan_store.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/ipvlan/ipvlan_test.go
<add>// +build linux
<add>
<ide> package ipvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan_endpoint.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan_joinleave.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan_network.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan_setup.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan_setup_test.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan_state.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan_store.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/macvlan/macvlan_test.go
<add>// +build linux
<add>
<ide> package macvlan
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/encryption.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/filter.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/joinleave.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/ov_endpoint.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/ov_network.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/ov_serf.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/ov_utils.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/overlay.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> //go:generate protoc -I.:../../Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/docker/libnetwork/drivers/overlay,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. overlay.proto
<ide><path>libnetwork/drivers/overlay/overlay_test.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/peerdb.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drivers/overlay/peerdb_test.go
<add>// +build linux
<add>
<ide> package overlay
<ide>
<ide> import (
<ide><path>libnetwork/drvregistry/drvregistry_test.go
<ide> package drvregistry
<ide>
<ide> import (
<add> "runtime"
<ide> "sort"
<ide> "testing"
<ide>
<ide> func TestWalkIPAMs(t *testing.T) {
<ide> })
<ide>
<ide> sort.Strings(ipams)
<del> assert.Check(t, is.DeepEqual(ipams, []string{"default", "null"}))
<add> expected := []string{"default", "null"}
<add> if runtime.GOOS == "windows" {
<add> expected = append(expected, "windows")
<add> }
<add> assert.Check(t, is.DeepEqual(ipams, expected))
<ide> }
<ide>
<ide> func TestWalkDrivers(t *testing.T) {
<ide><path>libnetwork/osl/namespace_windows.go
<ide> package osl
<ide>
<del>import "testing"
<del>
<ide> // GenerateKey generates a sandbox key based on the passed
<ide> // container id.
<ide> func GenerateKey(containerID string) string {
<ide> func InitOSContext() func() {
<ide> return func() {}
<ide> }
<ide>
<del>// SetupTestOSContext sets up a separate test OS context in which tests will be executed.
<del>func SetupTestOSContext(t *testing.T) func() {
<del> return func() {}
<del>}
<del>
<ide> // SetBasePath sets the base url prefix for the ns path
<ide> func SetBasePath(path string) {
<ide> }
<ide><path>libnetwork/osl/sandbox_freebsd.go
<ide> package osl
<ide>
<del>import "testing"
<del>
<ide> // GenerateKey generates a sandbox key based on the passed
<ide> // container id.
<ide> func GenerateKey(containerID string) string {
<ide> func InitOSContext() func() {
<ide> return func() {}
<ide> }
<ide>
<del>// SetupTestOSContext sets up a separate test OS context in which tests will be executed.
<del>func SetupTestOSContext(t *testing.T) func() {
<del> return func() {}
<del>}
<del>
<ide> // SetBasePath sets the base url prefix for the ns path
<ide> func SetBasePath(path string) {
<ide> }
<ide><path>libnetwork/osl/sandbox_linux_test.go
<ide> import (
<ide> "testing"
<ide> "time"
<ide>
<add> "github.com/docker/docker/libnetwork/ns"
<ide> "github.com/docker/docker/libnetwork/testutils"
<ide> "github.com/docker/docker/libnetwork/types"
<add> "github.com/docker/docker/pkg/reexec"
<ide> "github.com/vishvananda/netlink"
<ide> "github.com/vishvananda/netlink/nl"
<ide> "github.com/vishvananda/netns"
<ide> func TestLiveRestore(t *testing.T) {
<ide> t.Fatalf("Expected route conflict error, but succeeded for IPV4 ")
<ide> }
<ide> }
<add>
<add>func TestMain(m *testing.M) {
<add> if reexec.Init() {
<add> return
<add> }
<add> os.Exit(m.Run())
<add>}
<add>
<add>func TestSandboxCreate(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> key, err := newKey(t)
<add> if err != nil {
<add> t.Fatalf("Failed to obtain a key: %v", err)
<add> }
<add>
<add> s, err := NewSandbox(key, true, false)
<add> if err != nil {
<add> t.Fatalf("Failed to create a new sandbox: %v", err)
<add> }
<add>
<add> if s.Key() != key {
<add> t.Fatalf("s.Key() returned %s. Expected %s", s.Key(), key)
<add> }
<add>
<add> tbox, err := newInfo(ns.NlHandle(), t)
<add> if err != nil {
<add> t.Fatalf("Failed to generate new sandbox info: %v", err)
<add> }
<add>
<add> for _, i := range tbox.Info().Interfaces() {
<add> err = s.AddInterface(i.SrcName(), i.DstName(),
<add> tbox.InterfaceOptions().Bridge(i.Bridge()),
<add> tbox.InterfaceOptions().Address(i.Address()),
<add> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6()))
<add> if err != nil {
<add> t.Fatalf("Failed to add interfaces to sandbox: %v", err)
<add> }
<add> }
<add>
<add> err = s.SetGateway(tbox.Info().Gateway())
<add> if err != nil {
<add> t.Fatalf("Failed to set gateway to sandbox: %v", err)
<add> }
<add>
<add> err = s.SetGatewayIPv6(tbox.Info().GatewayIPv6())
<add> if err != nil {
<add> t.Fatalf("Failed to set ipv6 gateway to sandbox: %v", err)
<add> }
<add>
<add> verifySandbox(t, s, []string{"0", "1", "2"})
<add>
<add> err = s.Destroy()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> verifyCleanup(t, s, true)
<add>}
<add>
<add>func TestSandboxCreateTwice(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> key, err := newKey(t)
<add> if err != nil {
<add> t.Fatalf("Failed to obtain a key: %v", err)
<add> }
<add>
<add> _, err = NewSandbox(key, true, false)
<add> if err != nil {
<add> t.Fatalf("Failed to create a new sandbox: %v", err)
<add> }
<add> runtime.LockOSThread()
<add>
<add> // Create another sandbox with the same key to see if we handle it
<add> // gracefully.
<add> s, err := NewSandbox(key, true, false)
<add> if err != nil {
<add> t.Fatalf("Failed to create a new sandbox: %v", err)
<add> }
<add> runtime.LockOSThread()
<add>
<add> err = s.Destroy()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> GC()
<add> verifyCleanup(t, s, false)
<add>}
<add>
<add>func TestSandboxGC(t *testing.T) {
<add> key, err := newKey(t)
<add> if err != nil {
<add> t.Fatalf("Failed to obtain a key: %v", err)
<add> }
<add>
<add> s, err := NewSandbox(key, true, false)
<add> if err != nil {
<add> t.Fatalf("Failed to create a new sandbox: %v", err)
<add> }
<add>
<add> err = s.Destroy()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> GC()
<add> verifyCleanup(t, s, false)
<add>}
<add>
<add>func TestAddRemoveInterface(t *testing.T) {
<add> defer testutils.SetupTestOSContext(t)()
<add>
<add> key, err := newKey(t)
<add> if err != nil {
<add> t.Fatalf("Failed to obtain a key: %v", err)
<add> }
<add>
<add> s, err := NewSandbox(key, true, false)
<add> if err != nil {
<add> t.Fatalf("Failed to create a new sandbox: %v", err)
<add> }
<add> runtime.LockOSThread()
<add>
<add> if s.Key() != key {
<add> t.Fatalf("s.Key() returned %s. Expected %s", s.Key(), key)
<add> }
<add>
<add> tbox, err := newInfo(ns.NlHandle(), t)
<add> if err != nil {
<add> t.Fatalf("Failed to generate new sandbox info: %v", err)
<add> }
<add>
<add> for _, i := range tbox.Info().Interfaces() {
<add> err = s.AddInterface(i.SrcName(), i.DstName(),
<add> tbox.InterfaceOptions().Bridge(i.Bridge()),
<add> tbox.InterfaceOptions().Address(i.Address()),
<add> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6()))
<add> if err != nil {
<add> t.Fatalf("Failed to add interfaces to sandbox: %v", err)
<add> }
<add> }
<add>
<add> verifySandbox(t, s, []string{"0", "1", "2"})
<add>
<add> interfaces := s.Info().Interfaces()
<add> if err := interfaces[0].Remove(); err != nil {
<add> t.Fatalf("Failed to remove interfaces from sandbox: %v", err)
<add> }
<add>
<add> verifySandbox(t, s, []string{"1", "2"})
<add>
<add> i := tbox.Info().Interfaces()[0]
<add> if err := s.AddInterface(i.SrcName(), i.DstName(),
<add> tbox.InterfaceOptions().Bridge(i.Bridge()),
<add> tbox.InterfaceOptions().Address(i.Address()),
<add> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6())); err != nil {
<add> t.Fatalf("Failed to add interfaces to sandbox: %v", err)
<add> }
<add>
<add> verifySandbox(t, s, []string{"1", "2", "3"})
<add>
<add> err = s.Destroy()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> GC()
<add> verifyCleanup(t, s, false)
<add>}
<ide><path>libnetwork/osl/sandbox_test.go
<del>package osl
<del>
<del>import (
<del> "os"
<del> "runtime"
<del> "testing"
<del>
<del> "github.com/docker/docker/pkg/reexec"
<del> "github.com/docker/docker/libnetwork/ns"
<del> "github.com/docker/docker/libnetwork/testutils"
<del>)
<del>
<del>func TestMain(m *testing.M) {
<del> if reexec.Init() {
<del> return
<del> }
<del> os.Exit(m.Run())
<del>}
<del>
<del>func TestSandboxCreate(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> key, err := newKey(t)
<del> if err != nil {
<del> t.Fatalf("Failed to obtain a key: %v", err)
<del> }
<del>
<del> s, err := NewSandbox(key, true, false)
<del> if err != nil {
<del> t.Fatalf("Failed to create a new sandbox: %v", err)
<del> }
<del>
<del> if s.Key() != key {
<del> t.Fatalf("s.Key() returned %s. Expected %s", s.Key(), key)
<del> }
<del>
<del> tbox, err := newInfo(ns.NlHandle(), t)
<del> if err != nil {
<del> t.Fatalf("Failed to generate new sandbox info: %v", err)
<del> }
<del>
<del> for _, i := range tbox.Info().Interfaces() {
<del> err = s.AddInterface(i.SrcName(), i.DstName(),
<del> tbox.InterfaceOptions().Bridge(i.Bridge()),
<del> tbox.InterfaceOptions().Address(i.Address()),
<del> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6()))
<del> if err != nil {
<del> t.Fatalf("Failed to add interfaces to sandbox: %v", err)
<del> }
<del> }
<del>
<del> err = s.SetGateway(tbox.Info().Gateway())
<del> if err != nil {
<del> t.Fatalf("Failed to set gateway to sandbox: %v", err)
<del> }
<del>
<del> err = s.SetGatewayIPv6(tbox.Info().GatewayIPv6())
<del> if err != nil {
<del> t.Fatalf("Failed to set ipv6 gateway to sandbox: %v", err)
<del> }
<del>
<del> verifySandbox(t, s, []string{"0", "1", "2"})
<del>
<del> err = s.Destroy()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> verifyCleanup(t, s, true)
<del>}
<del>
<del>func TestSandboxCreateTwice(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> key, err := newKey(t)
<del> if err != nil {
<del> t.Fatalf("Failed to obtain a key: %v", err)
<del> }
<del>
<del> _, err = NewSandbox(key, true, false)
<del> if err != nil {
<del> t.Fatalf("Failed to create a new sandbox: %v", err)
<del> }
<del> runtime.LockOSThread()
<del>
<del> // Create another sandbox with the same key to see if we handle it
<del> // gracefully.
<del> s, err := NewSandbox(key, true, false)
<del> if err != nil {
<del> t.Fatalf("Failed to create a new sandbox: %v", err)
<del> }
<del> runtime.LockOSThread()
<del>
<del> err = s.Destroy()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> GC()
<del> verifyCleanup(t, s, false)
<del>}
<del>
<del>func TestSandboxGC(t *testing.T) {
<del> key, err := newKey(t)
<del> if err != nil {
<del> t.Fatalf("Failed to obtain a key: %v", err)
<del> }
<del>
<del> s, err := NewSandbox(key, true, false)
<del> if err != nil {
<del> t.Fatalf("Failed to create a new sandbox: %v", err)
<del> }
<del>
<del> err = s.Destroy()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> GC()
<del> verifyCleanup(t, s, false)
<del>}
<del>
<del>func TestAddRemoveInterface(t *testing.T) {
<del> defer testutils.SetupTestOSContext(t)()
<del>
<del> key, err := newKey(t)
<del> if err != nil {
<del> t.Fatalf("Failed to obtain a key: %v", err)
<del> }
<del>
<del> s, err := NewSandbox(key, true, false)
<del> if err != nil {
<del> t.Fatalf("Failed to create a new sandbox: %v", err)
<del> }
<del> runtime.LockOSThread()
<del>
<del> if s.Key() != key {
<del> t.Fatalf("s.Key() returned %s. Expected %s", s.Key(), key)
<del> }
<del>
<del> tbox, err := newInfo(ns.NlHandle(), t)
<del> if err != nil {
<del> t.Fatalf("Failed to generate new sandbox info: %v", err)
<del> }
<del>
<del> for _, i := range tbox.Info().Interfaces() {
<del> err = s.AddInterface(i.SrcName(), i.DstName(),
<del> tbox.InterfaceOptions().Bridge(i.Bridge()),
<del> tbox.InterfaceOptions().Address(i.Address()),
<del> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6()))
<del> if err != nil {
<del> t.Fatalf("Failed to add interfaces to sandbox: %v", err)
<del> }
<del> }
<del>
<del> verifySandbox(t, s, []string{"0", "1", "2"})
<del>
<del> interfaces := s.Info().Interfaces()
<del> if err := interfaces[0].Remove(); err != nil {
<del> t.Fatalf("Failed to remove interfaces from sandbox: %v", err)
<del> }
<del>
<del> verifySandbox(t, s, []string{"1", "2"})
<del>
<del> i := tbox.Info().Interfaces()[0]
<del> if err := s.AddInterface(i.SrcName(), i.DstName(),
<del> tbox.InterfaceOptions().Bridge(i.Bridge()),
<del> tbox.InterfaceOptions().Address(i.Address()),
<del> tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6())); err != nil {
<del> t.Fatalf("Failed to add interfaces to sandbox: %v", err)
<del> }
<del>
<del> verifySandbox(t, s, []string{"1", "2", "3"})
<del>
<del> err = s.Destroy()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> GC()
<del> verifyCleanup(t, s, false)
<del>}
<ide><path>libnetwork/osl/sandbox_unsupported_test.go
<ide> import (
<ide> var ErrNotImplemented = errors.New("not implemented")
<ide>
<ide> func newKey(t *testing.T) (string, error) {
<del> return nil, ErrNotImplemented
<add> return "", ErrNotImplemented
<ide> }
<ide>
<ide> func verifySandbox(t *testing.T, s Sandbox) {
<ide><path>libnetwork/resolver_test.go
<ide> package libnetwork
<ide> import (
<ide> "bytes"
<ide> "net"
<add> "runtime"
<ide> "syscall"
<ide> "testing"
<ide> "time"
<ide> func waitForLocalDNSServer(t *testing.T) {
<ide> }
<ide>
<ide> func TestDNSProxyServFail(t *testing.T) {
<add> if runtime.GOARCH == "arm64" {
<add> t.Skip("This test fails on arm64 foor some reason... this need to be fixed")
<add> }
<add>
<ide> c, err := New()
<ide> if err != nil {
<ide> t.Fatal(err) | 66 |
Javascript | Javascript | upgrade react native to babel 7! | ebd12fa09fca8c9cee4a48e3f1652986d51fcdb3 | <ide><path>Libraries/polyfills/babelHelpers.js
<ide> /* eslint-disable quotes, curly, no-proto, no-undef-init, dot-notation */
<ide>
<ide> // Created by running:
<del>// require('babel-core').buildExternalHelpers('_extends classCallCheck createClass createRawReactElement defineProperty get inherits interopRequireDefault interopRequireWildcard objectWithoutProperties possibleConstructorReturn slicedToArray taggedTemplateLiteral toArray toConsumableArray '.split(' '))
<del>// then replacing the `global` reference in the last line to also use `this`.
<add>// require('fs').writeFileSync('babelExternalHelpers.js', require('@babel/core').buildExternalHelpers('_extends classCallCheck createClass createRawReactElement defineProperty get inherits interopRequireDefault interopRequireWildcard objectWithoutProperties possibleConstructorReturn slicedToArray taggedTemplateLiteral toArray toConsumableArray wrapNativeSuper assertThisInitialized taggedTemplateLiteralLoose'.split(' ')))// then replacing the `global` reference in the last line to also use `this`.
<ide> //
<del>// actually, that's a lie, because babel6 omits _extends and createRawReactElement
<add>// Actually, that's a lie, because babel omits _extends and
<add>// createRawReactElement. the file is also cleaned up a bit.
<add>// You may need to clear wrapNativeSuper while the bug hasn't been fixed yet.
<add>// Do try to keep diffs to a minimum.
<ide>
<ide> var babelHelpers = global.babelHelpers = {};
<ide>
<del>babelHelpers.typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
<del> return typeof obj;
<del>} : function (obj) {
<del> return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
<del>};
<del>
<ide> babelHelpers.createRawReactElement = (function () {
<ide> var REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7;
<ide> return function createRawReactElement(type, key, props) {
<ide> babelHelpers.classCallCheck = function (instance, Constructor) {
<ide> }
<ide> };
<ide>
<del>babelHelpers.createClass = (function () {
<del> function defineProperties(target, props) {
<del> for (var i = 0; i < props.length; i++) {
<del> var descriptor = props[i];
<del> descriptor.enumerable = descriptor.enumerable || false;
<del> descriptor.configurable = true;
<del> if ("value" in descriptor) descriptor.writable = true;
<del> Object.defineProperty(target, descriptor.key, descriptor);
<del> }
<add>function _defineProperties(target, props) {
<add> for (var i = 0; i < props.length; i++) {
<add> var descriptor = props[i];
<add> descriptor.enumerable = descriptor.enumerable || false;
<add> descriptor.configurable = true;
<add> if ("value" in descriptor) descriptor.writable = true;
<add> Object.defineProperty(target, descriptor.key, descriptor);
<ide> }
<add>}
<ide>
<del> return function (Constructor, protoProps, staticProps) {
<del> if (protoProps) defineProperties(Constructor.prototype, protoProps);
<del> if (staticProps) defineProperties(Constructor, staticProps);
<del> return Constructor;
<del> };
<del>})();
<del>
<del>babelHelpers.defineEnumerableProperties = function(obj, descs) {
<del> for (var key in descs) {
<del> var desc = descs[key];
<del> desc.configurable = (desc.enumerable = true);
<del> if ('value' in desc) desc.writable = true;
<del> Object.defineProperty(obj, key, desc);
<del> }
<del> return obj;
<add>babelHelpers.createClass = function(Constructor, protoProps, staticProps) {
<add> if (protoProps) _defineProperties(Constructor.prototype, protoProps);
<add> if (staticProps) _defineProperties(Constructor, staticProps);
<add> return Constructor;
<ide> };
<ide>
<ide> babelHelpers.defineProperty = function (obj, key, value) {
<ide> babelHelpers.get = function get(object, property, receiver) {
<ide>
<ide> babelHelpers.inherits = function (subClass, superClass) {
<ide> if (typeof superClass !== "function" && superClass !== null) {
<del> throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
<add> throw new TypeError("Super expression must either be null or a function");
<ide> }
<del>
<ide> subClass.prototype = Object.create(superClass && superClass.prototype, {
<ide> constructor: {
<ide> value: subClass,
<ide> babelHelpers.inherits = function (subClass, superClass) {
<ide> if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
<ide> };
<ide>
<add>var _gPO = Object.getPrototypeOf || function _gPO(o) { return o.__proto__ };
<add>var _sPO = Object.setPrototypeOf || function _sPO(o, p) { o.__proto__ = p; return o };
<add>var _construct =
<add>// TODO: prepack does not like this line (and we can use the fallback just fine)
<add>// (typeof Reflect === "object" && Reflect.construct) ||
<add> function _construct(Parent, args, Class) {
<add> var Constructor, a = [null];
<add> a.push.apply(a, args);
<add> Constructor = Parent.bind.apply(Parent, a);
<add> return _sPO(new Constructor, Class.prototype);
<add> };
<add>var _cache = typeof Map === "function" && new Map();
<add>babelHelpers.wrapNativeSuper = function(Class) {
<add> // FB:
<add> // Note: while extending native classes is pretty meh we do have cases, for
<add> // example; Error. There is also a false positive, for example; Blob.
<add>
<add> if (typeof Class !== "function") {
<add> throw new TypeError("Super expression must either be null or a function");
<add> }
<add> if (typeof _cache !== "undefined") {
<add> if (_cache.has(Class)) return _cache.get(Class);
<add> _cache.set(Class, Wrapper);
<add> }
<add> function Wrapper() {
<add> // this is a temporary fix for a babel bug (it's invoking the wrong func
<add> // when you do `super()`)
<add> return _construct(Class, arguments, _gPO(this).constructor);
<add> }
<add> Wrapper.prototype = Object.create(Class.prototype, {
<add> constructor: {
<add> value: Wrapper,
<add> enumerable: false,
<add> writeable: true,
<add> configurable: true,
<add> }
<add> });
<add> return _sPO(
<add> Wrapper,
<add> _sPO(
<add> function Super() {
<add> return _construct(Class, arguments, _gPO(this).constructor);
<add> },
<add> Class
<add> )
<add> );
<add>};
<add>
<ide> babelHelpers.interopRequireDefault = function (obj) {
<ide> return obj && obj.__esModule ? obj : {
<ide> default: obj
<ide> babelHelpers.interopRequireWildcard = function (obj) {
<ide>
<ide> if (obj != null) {
<ide> for (var key in obj) {
<del> if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
<add> if (Object.prototype.hasOwnProperty.call(obj, key)) {
<add> var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
<add>
<add> if (desc.get || desc.set) {
<add> Object.defineProperty(newObj, key, desc);
<add> } else {
<add> newObj[key] = obj[key];
<add> }
<add> }
<ide> }
<ide> }
<ide>
<ide> babelHelpers.interopRequireWildcard = function (obj) {
<ide> }
<ide> };
<ide>
<del>babelHelpers.objectWithoutProperties = function (obj, keys) {
<add>babelHelpers.objectWithoutProperties = function(source, excluded) {
<add> if (source == null) return {};
<ide> var target = {};
<add> var sourceKeys = Object.keys(source);
<add> var key, i;
<add>
<add> for (i = 0; i < sourceKeys.length; i++) {
<add> key = sourceKeys[i];
<add> if (excluded.indexOf(key) >= 0) continue;
<add> target[key] = source[key];
<add> }
<add>
<add> if (Object.getOwnPropertySymbols) {
<add> var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
<ide>
<del> for (var i in obj) {
<del> if (keys.indexOf(i) >= 0) continue;
<del> if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
<del> target[i] = obj[i];
<add> for (i = 0; i < sourceSymbolKeys.length; i++) {
<add> key = sourceSymbolKeys[i];
<add> if (excluded.indexOf(key) >= 0) continue;
<add> if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
<add> target[key] = source[key];
<add> }
<ide> }
<ide>
<ide> return target;
<ide> };
<ide>
<ide> babelHelpers.possibleConstructorReturn = function (self, call) {
<del> if (!self) {
<add> if (call && (typeof call === "object" || typeof call === "function")) {
<add> return call;
<add> }
<add>
<add> if (self === void 0) {
<ide> throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
<ide> }
<ide>
<del> return call && (typeof call === "object" || typeof call === "function") ? call : self;
<add> return self;
<ide> };
<ide>
<del>babelHelpers.slicedToArray = (function () {
<del> function sliceIterator(arr, i) {
<del> var _arr = [];
<del> var _n = true;
<del> var _d = false;
<del> var _e = undefined;
<add>function _sliceIterator(arr, i) {
<add> var _arr = [];
<add> var _n = true;
<add> var _d = false;
<add> var _e = undefined;
<ide>
<del> try {
<del> for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
<del> _arr.push(_s.value);
<add> try {
<add> for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
<add> _arr.push(_s.value);
<ide>
<del> if (i && _arr.length === i) break;
<del> }
<del> } catch (err) {
<del> _d = true;
<del> _e = err;
<add> if (i && _arr.length === i) break;
<add> }
<add> } catch (err) {
<add> _d = true;
<add> _e = err;
<add> } finally {
<add> try {
<add> if (!_n && _i["return"] != null) _i["return"]();
<ide> } finally {
<del> try {
<del> if (!_n && _i["return"]) _i["return"]();
<del> } finally {
<del> if (_d) throw _e;
<del> }
<add> if (_d) throw _e;
<ide> }
<del>
<del> return _arr;
<ide> }
<ide>
<del> return function (arr, i) {
<del> if (Array.isArray(arr)) {
<del> return arr;
<del> } else if (Symbol.iterator in Object(arr)) {
<del> return sliceIterator(arr, i);
<del> } else {
<del> throw new TypeError("Invalid attempt to destructure non-iterable instance");
<del> }
<del> };
<del>})();
<add> return _arr;
<add>}
<add>
<add>babelHelpers.slicedToArray = function(arr, i) {
<add> if (Array.isArray(arr)) {
<add> return arr;
<add> } else if (Symbol.iterator in Object(arr)) {
<add> return _sliceIterator(arr, i);
<add> } else {
<add> throw new TypeError("Invalid attempt to destructure non-iterable instance");
<add> }
<add>};
<ide>
<ide> babelHelpers.taggedTemplateLiteral = function (strings, raw) {
<ide> return Object.freeze(Object.defineProperties(strings, {
<ide> babelHelpers.toArray = function (arr) {
<ide>
<ide> babelHelpers.toConsumableArray = function (arr) {
<ide> if (Array.isArray(arr)) {
<del> for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
<add> for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
<ide>
<ide> return arr2;
<ide> } else {
<ide> return Array.from(arr);
<ide> }
<ide> };
<add>
<add>babelHelpers.assertThisInitialized = function(self) {
<add> if (self === void 0) {
<add> throw new ReferenceError(
<add> "this hasn't been initialised - super() hasn't been called",
<add> );
<add> }
<add>
<add> return self;
<add>};
<add>
<add>babelHelpers.taggedTemplateLiteralLoose = function(strings, raw) {
<add> strings.raw = raw;
<add> return strings;
<add>};
<ide><path>babel-preset/configs/main.js
<ide> 'use strict';
<ide>
<ide> const defaultPlugins = [
<del> [require('babel-plugin-syntax-class-properties')],
<del> [require('babel-plugin-syntax-trailing-function-commas')],
<del> [require('babel-plugin-transform-class-properties')],
<del> [require('babel-plugin-transform-es2015-block-scoping')],
<del> [require('babel-plugin-transform-es2015-computed-properties')],
<del> [require('babel-plugin-transform-es2015-destructuring')],
<del> [require('babel-plugin-transform-es2015-function-name')],
<del> [require('babel-plugin-transform-es2015-literals')],
<del> [require('babel-plugin-transform-es2015-parameters')],
<del> [require('babel-plugin-transform-es2015-shorthand-properties')],
<del> [require('babel-plugin-transform-flow-strip-types')],
<del> [require('babel-plugin-transform-react-jsx')],
<del> [require('babel-plugin-transform-regenerator')],
<add> [require('@babel/plugin-transform-block-scoping')],
<add> // the flow strip types plugin must go BEFORE class properties!
<add> // there'll be a test case that fails if you don't.
<add> [require('@babel/plugin-transform-flow-strip-types')],
<ide> [
<del> require('babel-plugin-transform-es2015-modules-commonjs'),
<del> {strict: false, allowTopLevelThis: true},
<add> require('@babel/plugin-proposal-class-properties'),
<add> // use `this.foo = bar` instead of `this.defineProperty('foo', ...)`
<add> // (Makes the properties enumerable)
<add> {loose: true},
<add> ],
<add> [require('@babel/plugin-transform-computed-properties')],
<add> [require('@babel/plugin-transform-destructuring')],
<add> [require('@babel/plugin-transform-function-name')],
<add> [require('@babel/plugin-transform-literals')],
<add> [require('@babel/plugin-transform-parameters')],
<add> [require('@babel/plugin-transform-shorthand-properties')],
<add> [require('@babel/plugin-transform-react-jsx')],
<add> [require('@babel/plugin-transform-regenerator')],
<add> [require('@babel/plugin-transform-sticky-regex')],
<add> [require('@babel/plugin-transform-unicode-regex')],
<add> [
<add> require('@babel/plugin-transform-modules-commonjs'),
<add> {
<add> strict: false,
<add> strictMode : false, // prevent "use strict" injections
<add> allowTopLevelThis: true, // dont rewrite global `this` -> `undefined`
<add> },
<ide> ],
<ide> ];
<ide>
<del>const checkES2015Constants = [require('babel-plugin-check-es2015-constants')];
<del>const es2015ArrowFunctions = [require('babel-plugin-transform-es2015-arrow-functions')];
<del>const es2015Classes = [require('babel-plugin-transform-es2015-classes')];
<del>const es2015ForOf = [require('babel-plugin-transform-es2015-for-of'), {loose: true}];
<del>const es2015Spread = [require('babel-plugin-transform-es2015-spread')];
<del>const es2015TemplateLiterals = [require('babel-plugin-transform-es2015-template-literals')];
<del>const asyncFunctions = [require('babel-plugin-syntax-async-functions')];
<del>const exponentiationOperator = [require('babel-plugin-transform-exponentiation-operator')];
<del>const objectAssign = [require('babel-plugin-transform-object-assign')];
<del>const objectRestSpread = [require('babel-plugin-transform-object-rest-spread')];
<del>const reactDisplayName = [require('babel-plugin-transform-react-display-name')];
<del>const reactJsxSource = [require('babel-plugin-transform-react-jsx-source')];
<add>const es2015ArrowFunctions = [
<add> require('@babel/plugin-transform-arrow-functions'),
<add>];
<add>const es2015Classes = [require('@babel/plugin-transform-classes')];
<add>const es2015ForOf = [require('@babel/plugin-transform-for-of'), {loose: true}];
<add>const es2015Spread = [require('@babel/plugin-transform-spread')];
<add>const es2015TemplateLiterals = [
<add> require('@babel/plugin-transform-template-literals'),
<add> {loose: true}, // dont 'a'.concat('b'), just use 'a'+'b'
<add>];
<add>const exponentiationOperator = [
<add> require('@babel/plugin-transform-exponentiation-operator'),
<add>];
<add>const objectAssign = [require('@babel/plugin-transform-object-assign')];
<add>const objectRestSpread = [require('@babel/plugin-proposal-object-rest-spread')];
<add>const reactDisplayName = [
<add> require('@babel/plugin-transform-react-display-name'),
<add>];
<add>const reactJsxSource = [require('@babel/plugin-transform-react-jsx-source')];
<ide> const symbolMember = [require('../transforms/transform-symbol-member')];
<ide>
<ide> const getPreset = (src, options) => {
<ide> const getPreset = (src, options) => {
<ide>
<ide> const extraPlugins = [];
<ide>
<del> if (isNull || src.indexOf('async') !== -1 || src.indexOf('await') !== -1) {
<del> extraPlugins.push(asyncFunctions);
<del> }
<ide> if (hasClass) {
<ide> extraPlugins.push(es2015Classes);
<ide> }
<ide> if (isNull || src.indexOf('=>') !== -1) {
<ide> extraPlugins.push(es2015ArrowFunctions);
<ide> }
<del> if (isNull || src.indexOf('const') !== -1) {
<del> extraPlugins.push(checkES2015Constants);
<del> }
<ide> if (isNull || hasClass || src.indexOf('...') !== -1) {
<ide> extraPlugins.push(es2015Spread);
<ide> extraPlugins.push(objectRestSpread);
<ide><path>jest/preprocessor.js
<ide>
<ide> 'use strict';
<ide>
<del>const babel = require('babel-core');
<add>const {transformSync: babelTransformSync} = require('@babel/core');
<ide> /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
<ide> * found when Flow v0.54 was deployed. To see the error delete this comment and
<ide> * run Flow. */
<ide> const babelRegisterOnly = require('metro/src/babelRegisterOnly');
<ide> * found when Flow v0.54 was deployed. To see the error delete this comment and
<ide> * run Flow. */
<ide> const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
<del>const generate = require('babel-generator').default;
<add>const generate = require('@babel/generator').default;
<ide>
<ide> const nodeFiles = RegExp([
<ide> '/local-cli/',
<ide> const transformer = require('metro/src/transformer.js');
<ide> module.exports = {
<ide> process(src/*: string*/, file/*: string*/) {
<ide> if (nodeFiles.test(file)) { // node specific transforms only
<del> return babel.transform(
<add> return babelTransformSync(
<ide> src,
<ide> Object.assign({filename: file}, nodeOptions)
<ide> ).code;
<ide> module.exports = {
<ide> retainLines: true,
<ide> },
<ide> src,
<add> plugins: [
<add> [require('@babel/plugin-transform-block-scoping')],
<add> // the flow strip types plugin must go BEFORE class properties!
<add> // there'll be a test case that fails if you don't.
<add> [require('@babel/plugin-transform-flow-strip-types')],
<add> [
<add> require('@babel/plugin-proposal-class-properties'),
<add> // use `this.foo = bar` instead of `this.defineProperty('foo', ...)`
<add> // (Makes the properties enumerable)
<add> {loose: true},
<add> ],
<add> [require('@babel/plugin-transform-computed-properties')],
<add> [require('@babel/plugin-transform-destructuring')],
<add> [require('@babel/plugin-transform-function-name')],
<add> [require('@babel/plugin-transform-literals')],
<add> [require('@babel/plugin-transform-parameters')],
<add> [require('@babel/plugin-transform-shorthand-properties')],
<add> [require('@babel/plugin-transform-react-jsx')],
<add> [require('@babel/plugin-transform-regenerator')],
<add> [require('@babel/plugin-transform-sticky-regex')],
<add> [require('@babel/plugin-transform-unicode-regex')],
<add> [
<add> require('@babel/plugin-transform-modules-commonjs'),
<add> {strict: false, allowTopLevelThis: true},
<add> ],
<add> [require('@babel/plugin-transform-classes')],
<add> [require('@babel/plugin-transform-arrow-functions')],
<add> [require('@babel/plugin-transform-spread')],
<add> [require('@babel/plugin-proposal-object-rest-spread')],
<add> [
<add> require('@babel/plugin-transform-template-literals'),
<add> {loose: true}, // dont 'a'.concat('b'), just use 'a'+'b'
<add> ],
<add> [require('@babel/plugin-transform-exponentiation-operator')],
<add> [require('@babel/plugin-transform-object-assign')],
<add> [require('@babel/plugin-transform-for-of'), {loose: true}],
<add> [require('@babel/plugin-transform-react-display-name')],
<add> [require('@babel/plugin-transform-react-jsx-source')],
<add> ],
<ide> });
<ide>
<ide> return generate(ast, {
<ide> module.exports = {
<ide> getCacheKey: createCacheKeyFunction([
<ide> __filename,
<ide> require.resolve('metro/src/transformer.js'),
<del> require.resolve('babel-core/package.json'),
<add> require.resolve('@babel/core/package.json'),
<ide> ]),
<ide> }; | 3 |
PHP | PHP | add getdirty method | eca8e6b51ec5b0d7f153b24efbd646e86e2d3abd | <ide><path>src/Datasource/EntityTrait.php
<ide> public function isDirty($property = null)
<ide> return isset($this->_dirty[$property]);
<ide> }
<ide>
<add> /**
<add> * Gets the dirty properties.
<add> *
<add> * @return array
<add> */
<add> public function getDirty()
<add> {
<add> return array_keys($this->_dirty);
<add> }
<add>
<ide> /**
<ide> * Sets the entire entity as clean, which means that it will appear as
<ide> * no properties being modified or added at all. This is an useful call
<ide><path>tests/TestCase/ORM/EntityTest.php
<ide> public function testExtractDirty()
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add> /**
<add> * Tests the getDirty method
<add> *
<add> * @return void
<add> */
<add> public function testGetDirty()
<add> {
<add> $entity = new Entity([
<add> 'id' => 1,
<add> 'title' => 'Foo',
<add> 'author_id' => 3
<add> ]);
<add>
<add> $expected = [
<add> 'id',
<add> 'title',
<add> 'author_id'
<add> ];
<add> $result = $entity->getDirty();
<add> $this->assertSame($expected, $entity->getDirty());
<add> }
<add>
<ide> /**
<ide> * Tests the clean method
<ide> * | 2 |
Javascript | Javascript | make use of number.isnan to test-readfloat.js | ff59fd7a73f6e7811f82b025c606a48923417bc4 | <ide><path>test/parallel/test-readfloat.js
<ide> function test(clazz) {
<ide> buffer[1] = 0xff;
<ide> buffer[2] = 0x7f;
<ide> buffer[3] = 0x7f;
<del> assert.ok(isNaN(buffer.readFloatBE(0)));
<add> assert.ok(Number.isNaN(buffer.readFloatBE(0)));
<ide> assert.strictEqual(3.4028234663852886e+38, buffer.readFloatLE(0));
<ide>
<ide> buffer[0] = 0xab; | 1 |
Ruby | Ruby | convert sandbox test to spec | d25f9498244d2adebe3046c8857e05ded17f7485 | <ide><path>Library/Homebrew/test/sandbox_spec.rb
<add>require "sandbox"
<add>
<add>RSpec::Matchers.define_negated_matcher :not_matching, :matching
<add>
<add>describe Sandbox do
<add> let(:dir) { @dir = Pathname.new(Dir.mktmpdir) }
<add> let(:file) { dir/"foo" }
<add>
<add> before(:each) do
<add> skip "Sandbox not implemented." unless described_class.available?
<add> end
<add>
<add> after(:each) do
<add> dir.rmtree unless @dir.nil?
<add> end
<add>
<add> specify "#formula?" do
<add> f = formula { url "foo-1.0" }
<add> f2 = formula { url "bar-1.0" }
<add> allow(f2).to receive(:tap).and_return(Tap.fetch("test/tap"))
<add>
<add> ENV["HOMEBREW_SANDBOX"] = "1"
<add> expect(described_class).to be_formula(f), "Formulae should be sandboxed if --sandbox was passed."
<add>
<add> ENV.delete("HOMEBREW_SANDBOX")
<add> expect(described_class).to be_formula(f), "Formulae should be sandboxed if in a sandboxed tap."
<add> expect(described_class).not_to be_formula(f2), "Formulae should not be sandboxed if not in a sandboxed tap."
<add> end
<add>
<add> specify "#test?" do
<add> ENV.delete("HOMEBREW_NO_SANDBOX")
<add> expect(described_class).to be_test, "Tests should be sandboxed unless --no-sandbox was passed."
<add> end
<add>
<add> specify "#allow_write" do
<add> subject.allow_write file
<add> subject.exec "touch", file
<add>
<add> expect(file).to exist
<add> end
<add>
<add> describe "#exec" do
<add> it "fails when writing to file not specified with ##allow_write" do
<add> shutup do
<add> expect {
<add> subject.exec "touch", file
<add> }.to raise_error(ErrorDuringExecution)
<add> end
<add>
<add> expect(file).not_to exist
<add> end
<add>
<add> it "complains on failure" do
<add> ENV["HOMEBREW_VERBOSE"] = "1"
<add>
<add> expect(Utils).to receive(:popen_read).and_return("foo")
<add>
<add> expect { subject.exec "false" }
<add> .to raise_error(ErrorDuringExecution)
<add> .and output(/foo/).to_stdout
<add> end
<add>
<add> it "ignores bogus Python error" do
<add> ENV["HOMEBREW_VERBOSE"] = "1"
<add>
<add> with_bogus_error = <<-EOS.undent
<add> foo
<add> Mar 17 02:55:06 sandboxd[342]: Python(49765) deny file-write-unlink /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/errors.pyc
<add> bar
<add> EOS
<add> expect(Utils).to receive(:popen_read).and_return(with_bogus_error)
<add>
<add> expect { subject.exec "false" }
<add> .to raise_error(ErrorDuringExecution)
<add> .and output(a_string_matching(/foo/).and(matching(/bar/).and(not_matching(/Python/)))).to_stdout
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/sandbox_test.rb
<del>require "testing_env"
<del>require "sandbox"
<del>
<del>class SandboxTest < Homebrew::TestCase
<del> def setup
<del> super
<del> skip "sandbox not implemented" unless Sandbox.available?
<del> @sandbox = Sandbox.new
<del> @dir = Pathname.new(mktmpdir)
<del> @file = @dir/"foo"
<del> end
<del>
<del> def test_formula?
<del> f = formula { url "foo-1.0" }
<del> f2 = formula { url "bar-1.0" }
<del> f2.stubs(:tap).returns(Tap.fetch("test/tap"))
<del>
<del> ENV["HOMEBREW_SANDBOX"] = "1"
<del> assert Sandbox.formula?(f),
<del> "Formulae should be sandboxed if --sandbox was passed."
<del>
<del> ENV.delete("HOMEBREW_SANDBOX")
<del> assert Sandbox.formula?(f),
<del> "Formulae should be sandboxed if in a sandboxed tap."
<del> refute Sandbox.formula?(f2),
<del> "Formulae should not be sandboxed if not in a sandboxed tap."
<del> end
<del>
<del> def test_test?
<del> ENV.delete("HOMEBREW_NO_SANDBOX")
<del> assert Sandbox.test?,
<del> "Tests should be sandboxed unless --no-sandbox was passed."
<del> end
<del>
<del> def test_allow_write
<del> @sandbox.allow_write @file
<del> @sandbox.exec "touch", @file
<del> assert_predicate @file, :exist?
<del> end
<del>
<del> def test_deny_write
<del> shutup do
<del> assert_raises(ErrorDuringExecution) { @sandbox.exec "touch", @file }
<del> end
<del> refute_predicate @file, :exist?
<del> end
<del>
<del> def test_complains_on_failure
<del> Utils.expects(popen_read: "foo")
<del> ENV["HOMEBREW_VERBOSE"] = "1"
<del> out, _err = capture_io do
<del> assert_raises(ErrorDuringExecution) { @sandbox.exec "false" }
<del> end
<del> assert_match "foo", out
<del> end
<del>
<del> def test_ignores_bogus_python_error
<del> with_bogus_error = <<-EOS.undent
<del> foo
<del> Mar 17 02:55:06 sandboxd[342]: Python(49765) deny file-write-unlink /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/errors.pyc
<del> bar
<del> EOS
<del> Utils.expects(popen_read: with_bogus_error)
<del> ENV["HOMEBREW_VERBOSE"] = "1"
<del> out, _err = capture_io do
<del> assert_raises(ErrorDuringExecution) { @sandbox.exec "false" }
<del> end
<del> refute_predicate out, :empty?
<del> assert_match "foo", out
<del> assert_match "bar", out
<del> refute_match "Python", out
<del> end
<del>end | 2 |
Javascript | Javascript | add tests for d3.geo.rotation | 9323c2314fda1de78153dce95b119672d49939b0 | <ide><path>test/core/ascending-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.ascending");
<ide>
<ide><path>test/core/bisect-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.bisect");
<ide>
<ide><path>test/core/descending-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.descending");
<ide>
<ide><path>test/core/dispatch-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.dispatch");
<ide>
<ide><path>test/core/ease-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.ease");
<ide>
<ide><path>test/core/entries-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.entries");
<ide>
<ide><path>test/core/extent-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.extent");
<ide>
<ide><path>test/core/format-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.format");
<ide>
<ide><path>test/core/formatPrefix-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.formatPrefix");
<ide>
<ide><path>test/core/functor-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.functor");
<ide>
<ide><path>test/core/hcl-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.hcl");
<ide>
<ide><path>test/core/hsl-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.hsl");
<ide>
<ide><path>test/core/html-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.html");
<ide>
<ide><path>test/core/interpolate-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.interpolate");
<ide>
<ide><path>test/core/json-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.json");
<ide>
<ide><path>test/core/keys-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.keys");
<ide>
<ide><path>test/core/lab-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.lab");
<ide>
<ide><path>test/core/map-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.map");
<ide>
<ide><path>test/core/max-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.max");
<ide>
<ide><path>test/core/mean-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.mean");
<ide>
<ide><path>test/core/median-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.median");
<ide>
<ide><path>test/core/merge-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.merge");
<ide>
<ide><path>test/core/min-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.min");
<ide>
<ide><path>test/core/nest-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.nest");
<ide>
<ide><path>test/core/ns-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("ns");
<ide>
<ide><path>test/core/permute-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.permute");
<ide>
<ide><path>test/core/quantile-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.quantile");
<ide>
<ide><path>test/core/random-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.random");
<ide>
<ide><path>test/core/range-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.range");
<ide>
<ide><path>test/core/rebind-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.rebind");
<ide>
<ide><path>test/core/requote-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.requote");
<ide>
<ide><path>test/core/rgb-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.rgb");
<ide>
<ide><path>test/core/round-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.round");
<ide>
<ide><path>test/core/select-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.select");
<ide>
<ide><path>test/core/selectAll-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.selectAll");
<ide>
<ide><path>test/core/selection-append-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.append");
<ide>
<ide><path>test/core/selection-attr-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.attr");
<ide>
<ide><path>test/core/selection-call-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.call");
<ide>
<ide><path>test/core/selection-classed-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.call");
<ide>
<ide><path>test/core/selection-data-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.data");
<ide>
<ide><path>test/core/selection-datum-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.datum");
<ide>
<ide><path>test/core/selection-each-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.each");
<ide>
<ide><path>test/core/selection-empty-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.empty");
<ide>
<ide><path>test/core/selection-enter-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.enter");
<ide>
<ide><path>test/core/selection-filter-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.filter");
<ide>
<ide><path>test/core/selection-html-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.html");
<ide>
<ide><path>test/core/selection-insert-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.insert");
<ide>
<ide><path>test/core/selection-node-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.node");
<ide>
<ide><path>test/core/selection-on-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.on");
<ide>
<ide><path>test/core/selection-order-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.order");
<ide>
<ide><path>test/core/selection-property-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.property");
<ide>
<ide><path>test/core/selection-remove-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.remove");
<ide>
<ide><path>test/core/selection-select-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.select");
<ide>
<ide><path>test/core/selection-selectAll-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.selectAll");
<ide>
<ide><path>test/core/selection-sort-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.sort");
<ide>
<ide><path>test/core/selection-style-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.style");
<ide>
<ide><path>test/core/selection-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.selection");
<ide>
<ide><path>test/core/selection-text-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("selection.text");
<ide>
<ide><path>test/core/sum-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.sum");
<ide>
<ide><path>test/core/text-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.text");
<ide>
<ide><path>test/core/timer-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.timer");
<ide>
<ide><path>test/core/transition-test-attr.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-attrTween.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-call.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-delay.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-duration.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-each.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> "start": {
<ide><path>test/core/transition-test-filter.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> var datum = {};
<ide>
<ide><path>test/core/transition-test-id.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-remove.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-select.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-selectAll.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-style.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-styleTween.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-text.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-time.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-transition.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test-tween.js
<ide> require("../env");
<ide>
<del>var assert = require("assert");
<add>var assert = require("../env-assert");
<ide>
<ide> module.exports = {
<ide> topic: function() {
<ide><path>test/core/transition-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.transition");
<ide>
<ide><path>test/core/transpose-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.transpose");
<ide>
<ide><path>test/core/values-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.values");
<ide>
<ide><path>test/core/version-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.version");
<ide>
<ide><path>test/core/xhr-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.xhr");
<ide>
<ide><path>test/core/xml-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.xml");
<ide>
<ide><path>test/core/zip-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.zip");
<ide>
<ide><path>test/dsv/csv-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.csv");
<ide>
<ide><path>test/dsv/tsv-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.tsv");
<ide>
<ide><path>test/env-assert.js
<ide> var assert = require("assert");
<ide>
<add>assert = module.exports = Object.create(assert);
<add>
<ide> assert.inDelta = function(actual, expected, delta, message) {
<ide> if (!inDelta(actual, expected, delta)) {
<ide> assert.fail(actual, expected, message || "expected {actual} to be in within *" + delta + "* of {expected}", null, assert.inDelta);
<ide><path>test/env.js
<ide> process.env.TZ = "America/Los_Angeles";
<ide>
<ide> require("../globals");
<ide>
<del>require("./env-assert");
<ide> require("./env-xhr");
<ide> require("./env-fragment");
<ide>
<ide><path>test/geo/albers-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.albers");
<ide>
<ide><path>test/geo/area-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.area");
<ide>
<ide><path>test/geo/azimuthal-equal-area-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.azimuthalEqualArea");
<ide>
<ide><path>test/geo/azimuthal-equidistant-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.azimuthalEquidistant");
<ide>
<ide><path>test/geo/bounds-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.bounds");
<ide>
<ide><path>test/geo/centroid-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.centroid");
<ide>
<ide><path>test/geo/circle-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.circle");
<ide>
<ide><path>test/geo/equirectangular-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.equirectangular");
<ide>
<ide><path>test/geo/gnomonic-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.gnomonic");
<ide>
<ide><path>test/geo/graticule-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.graticule");
<ide>
<ide><path>test/geo/greatArc-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.greatArc");
<ide>
<ide><path>test/geo/mercator-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.mercator");
<ide>
<ide><path>test/geo/orthographic-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.orthographic");
<ide>
<ide><path>test/geo/path-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.path");
<ide>
<ide><path>test/geo/projection-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.projection");
<ide>
<ide><path>test/geo/rotation-test.js
<add>require("../env");
<add>
<add>var vows = require("vows"),
<add> assert = require("../env-assert");
<add>
<add>var suite = vows.describe("d3.geo.rotation");
<add>
<add>suite.addBatch({
<add> "a rotation of [+90°, 0°]": {
<add> topic: function() {
<add> return d3.geo.rotation([90, 0]);
<add> },
<add> "only rotates longitude": function(rotation) {
<add> assert.inDelta(rotation([0, 0]), [90, 0], 1e-6);
<add> },
<add> "wraps around when crossing the antimeridian": function(rotation) {
<add> assert.inDelta(rotation([150, 0]), [-120, 0], 1e-6);
<add> }
<add> },
<add> "a rotation of [-45°, -45°]": {
<add> topic: function() {
<add> return d3.geo.rotation([-45, 45]);
<add> },
<add> "rotates longitude and latitude": function(rotation) {
<add> assert.inDelta(rotation([0, 0]), [-54.73561, 30], 1e-6);
<add> }
<add> }
<add>});
<add>
<add>suite.export(module);
<ide><path>test/geo/stereographic-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.stereographic");
<ide>
<ide><path>test/geo/stream-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geo.stream");
<ide>
<ide><path>test/geom/polygon-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geom.polygon");
<ide>
<ide><path>test/geom/quadtree-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geom.quadtree");
<ide>
<ide><path>test/geom/voronoi-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.geom.voronoi");
<ide>
<ide><path>test/layout/cluster-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.cluster");
<ide>
<ide><path>test/layout/force-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.force");
<ide>
<ide><path>test/layout/hierarchy-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.hierarchy");
<ide>
<ide><path>test/layout/histogram-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.histogram");
<ide>
<ide><path>test/layout/pack-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.pack");
<ide>
<ide><path>test/layout/partition-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.partition");
<ide>
<ide><path>test/layout/pie-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.pie");
<ide>
<ide><path>test/layout/tree-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.tree");
<ide>
<ide><path>test/layout/treemap-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.layout.treemap");
<ide>
<ide><path>test/scale/category-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.category");
<ide>
<ide><path>test/scale/identity-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.identity");
<ide>
<ide><path>test/scale/linear-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.linear");
<ide>
<ide><path>test/scale/log-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.log");
<ide>
<ide><path>test/scale/ordinal-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.ordinal");
<ide>
<ide><path>test/scale/pow-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.pow");
<ide>
<ide><path>test/scale/quantile-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.quantile");
<ide>
<ide><path>test/scale/quantize-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.quantize");
<ide>
<ide><path>test/scale/sqrt-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.sqrt");
<ide>
<ide><path>test/scale/threshold-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.scale.threshold");
<ide>
<ide><path>test/svg/arc-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.svg.arc");
<ide>
<ide><path>test/svg/area-radial-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.svg.area.radial");
<ide>
<ide><path>test/svg/area-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.svg.area");
<ide>
<ide><path>test/svg/axis-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.svg.axis");
<ide>
<ide><path>test/svg/brush-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.svg.brush");
<ide>
<ide><path>test/svg/line-radial-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.svg.line.radial");
<ide>
<ide><path>test/svg/line-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.svg.line");
<ide>
<ide><path>test/svg/symbol-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.svg.symbol");
<ide>
<ide><path>test/time/day-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/dayOfYear-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/days-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/format-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/hour-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/hours-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/minute-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/minutes-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/month-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/months-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/scale-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/second-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/seconds-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/week-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/weeks-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert"),
<add> assert = require("../env-assert"),
<ide> time = require("./time"),
<ide> local = time.local,
<ide> utc = time.utc;
<ide><path>test/time/year-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.time.year");
<ide>
<ide><path>test/time/years-test.js
<ide> require("../env");
<ide>
<ide> var vows = require("vows"),
<del> assert = require("assert");
<add> assert = require("../env-assert");
<ide>
<ide> var suite = vows.describe("d3.time.years");
<ide> | 154 |
Text | Text | add v3.23.1 to changelog.md | f1f7342774b7e4ba2ccc4266f8e4bfcc2120af88 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.23.1 (November 23, 2020)
<add>
<add>- [#19282](https://github.com/emberjs/ember.js/pull/19282) [BUGFIX] Issue deprecations (instead of assertions) for tracked mutation in constructor during rendering
<add>
<ide> ### v3.24.0-beta.1 (November 16, 2020)
<ide>
<ide> - [#19224](https://github.com/emberjs/ember.js/pull/19224) [FEATURE] Add `{{page-title}}` helper to route template blueprints to implement [RFC #0654](https://github.com/emberjs/rfcs/blob/master/text/0645-add-ember-page-title-addon.md). | 1 |
Python | Python | use _umath_linalg for det() | 5b0fead2d4e3cc6c82761aba09f330147435a0cf | <ide><path>numpy/linalg/linalg.py
<ide> def slogdet(a):
<ide>
<ide> Notes
<ide> -----
<add> Broadcasting rules apply, see the `numpy.linalg` documentation for
<add> details.
<add>
<ide> The determinant is computed via LU factorization using the LAPACK
<ide> routine z/dgetrf.
<ide>
<ide> def det(a):
<ide>
<ide> Parameters
<ide> ----------
<del> a : (M, M) array_like
<del> Input array.
<add> a : (..., M, M) array_like
<add> Input array to compute determinants for.
<ide>
<ide> Returns
<ide> -------
<del> det : float
<add> det : (...) array_like
<ide> Determinant of `a`.
<ide>
<ide> See Also
<ide> def det(a):
<ide> >>> np.linalg.det(a)
<ide> -2.0
<ide>
<add> Computing determinants for a stack of matrices:
<add>
<add> >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
<add> >>> a.shape
<add> (2, 2, 2
<add> >>> np.linalg.det(a)
<add> array([-2., -3., -8.])
<add>
<ide> """
<del> sign, logdet = slogdet(a)
<del> return sign * exp(logdet)
<add> a = asarray(a)
<add> _assertNonEmpty(a)
<add> _assertRankAtLeast2(a)
<add> _assertNdSquareness(a)
<add> t, result_t = _commonType(a)
<add> return _umath_linalg.det(a.astype(t)).astype(result_t)
<ide>
<ide> # Linear Least Squares
<ide> | 1 |
Javascript | Javascript | fix benchmark runner | b888b681a86d0575f37db1f225c51255a996fa5d | <ide><path>benchmarks/iframe_runner.js
<ide> BenchWarmer.prototype = {
<ide> var count = parseInt(this.profile, 10);
<ide>
<ide> setTimeout(function() {
<del> self.setup();
<add> if (self.setup) { self.setup(); }
<ide> console.profile(self.emberPath + ": " + self.name);
<ide> for (var i=0; i<count; i++) {
<ide> self.fn();
<ide> }
<ide> console.profileEnd(self.emberPath + ": " + self.name);
<del> self.teardown();
<add> if (self.teardown) { self.teardown(); }
<ide> if (self.next) { self.next.run(); }
<ide> }, 1);
<ide> } else { | 1 |
Python | Python | update swivel to tfr1.0 | 66900a72d5536586c8322d52fac1b4212a50f438 | <ide><path>swivel/swivel.py
<ide> def count_matrix_input(filenames, submatrix_rows, submatrix_cols):
<ide> sparse_local_col = features['sparse_local_col'].values
<ide> sparse_count = features['sparse_value'].values
<ide>
<del> sparse_indices = tf.concat(1, [tf.expand_dims(sparse_local_row, 1),
<del> tf.expand_dims(sparse_local_col, 1)])
<add> sparse_indices = tf.concat([tf.expand_dims(sparse_local_row, 1),
<add> tf.expand_dims(sparse_local_col, 1)], 1)
<ide> count = tf.sparse_to_dense(sparse_indices, [submatrix_rows, submatrix_cols],
<ide> sparse_count)
<ide>
<ide> def __init__(self, config):
<ide> embedding_dim=config.embedding_size,
<ide> vocab_size=self.n_cols,
<ide> name='col_embedding')
<del> tf.histogram_summary('row_emb', self.row_embedding)
<del> tf.histogram_summary('col_emb', self.col_embedding)
<add> tf.summary.histogram('row_emb', self.row_embedding)
<add> tf.summary.histogram('col_emb', self.col_embedding)
<ide>
<ide> matrix_log_sum = math.log(np.sum(row_sums) + 1)
<ide> row_bias_init = [math.log(x + 1) for x in row_sums]
<ide> def __init__(self, config):
<ide> trainable=config.trainable_bias)
<ide> self.col_bias = tf.Variable(col_bias_init,
<ide> trainable=config.trainable_bias)
<del> tf.histogram_summary('row_bias', self.row_bias)
<del> tf.histogram_summary('col_bias', self.col_bias)
<add> tf.summary.histogram('row_bias', self.row_bias)
<add> tf.summary.histogram('col_bias', self.col_bias)
<ide>
<ide> # ===== CREATE GRAPH =====
<ide>
<ide> def __init__(self, config):
<ide>
<ide> self.loss = l2_loss + sigmoid_loss
<ide>
<del> tf.scalar_summary("l2_loss", l2_loss)
<del> tf.scalar_summary("sigmoid_loss", sigmoid_loss)
<del> tf.scalar_summary("loss", self.loss)
<add> tf.summary.scalar("l2_loss", l2_loss)
<add> tf.summary.scalar("sigmoid_loss", sigmoid_loss)
<add> tf.summary.scalar("loss", self.loss)
<ide>
<ide> # Add optimizer.
<ide> self.global_step = tf.Variable(0, name='global_step')
<ide> def main(_):
<ide> sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
<ide>
<ide> # Run the Op to initialize the variables.
<del> sess.run(tf.initialize_all_variables())
<add> sess.run(tf.global_variables_initializer())
<ide>
<ide> # Start feeding input
<ide> coord = tf.train.Coordinator() | 1 |
Text | Text | add instruction for test environment | f25de2c818e119df620e45e31d7edec281cf7e96 | <ide><path>guides/source/active_storage_overview.md
<ide> To use the Amazon S3 service in production, you add the following to
<ide> config.active_storage.service = :amazon
<ide> ```
<ide>
<add>To use the test service when testing, you add the following to
<add>`config/environments/test.rb`:
<add>
<add>```ruby
<add># Store uploaded files on the local file system in a temporary directory.
<add>config.active_storage.service = :test
<add>```
<add>
<ide> Continue reading for more information on the built-in service adapters (e.g.
<ide> `Disk` and `S3`) and the configuration they require.
<ide> | 1 |
Python | Python | simplify vae examples | 10b46cbdc47f7164cd92209077939a7f7882b3c0 | <ide><path>examples/variational_autoencoder.py
<ide> - Auto-Encoding Variational Bayes
<ide> https://arxiv.org/abs/1312.6114
<ide> '''
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<ide> import matplotlib.pyplot as plt
<ide> from scipy.stats import norm
<ide>
<del>from keras.layers import Input, Dense, Lambda, Layer
<add>from keras.layers import Input, Dense, Lambda
<ide> from keras.models import Model
<ide> from keras import backend as K
<ide> from keras import metrics
<ide> def sampling(args):
<ide> h_decoded = decoder_h(z)
<ide> x_decoded_mean = decoder_mean(h_decoded)
<ide>
<add># instantiate VAE model
<add>vae = Model(x, x_decoded_mean)
<add>
<add># Compute VAE loss
<add>xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)
<add>kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
<add>vae_loss = K.mean(xent_loss + kl_loss)
<ide>
<del># Custom loss layer
<del>class CustomVariationalLayer(Layer):
<del> def __init__(self, **kwargs):
<del> self.is_placeholder = True
<del> super(CustomVariationalLayer, self).__init__(**kwargs)
<del>
<del> def vae_loss(self, x, x_decoded_mean):
<del> xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)
<del> kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
<del> return K.mean(xent_loss + kl_loss)
<del>
<del> def call(self, inputs):
<del> x = inputs[0]
<del> x_decoded_mean = inputs[1]
<del> loss = self.vae_loss(x, x_decoded_mean)
<del> self.add_loss(loss, inputs=inputs)
<del> # We won't actually use the output.
<del> return x
<del>
<del>y = CustomVariationalLayer()([x, x_decoded_mean])
<del>vae = Model(x, y)
<del>vae.compile(optimizer='rmsprop', loss=None)
<add>vae.add_loss(vae_loss)
<add>vae.compile(optimizer='rmsprop')
<add>vae.summary()
<ide>
<ide>
<ide> # train the VAE on MNIST digits
<ide><path>examples/variational_autoencoder_deconv.py
<ide> - Auto-Encoding Variational Bayes
<ide> https://arxiv.org/abs/1312.6114
<ide> '''
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<ide> import matplotlib.pyplot as plt
<ide> from scipy.stats import norm
<ide>
<del>from keras.layers import Input, Dense, Lambda, Flatten, Reshape, Layer
<add>from keras.layers import Input, Dense, Lambda, Flatten, Reshape
<ide> from keras.layers import Conv2D, Conv2DTranspose
<ide> from keras.models import Model
<ide> from keras import backend as K
<ide> def sampling(args):
<ide> x_decoded_relu = decoder_deconv_3_upsamp(deconv_2_decoded)
<ide> x_decoded_mean_squash = decoder_mean_squash(x_decoded_relu)
<ide>
<add># instantiate VAE model
<add>vae = Model(x, x_decoded_mean_squash)
<ide>
<del># Custom loss layer
<del>class CustomVariationalLayer(Layer):
<del> def __init__(self, **kwargs):
<del> self.is_placeholder = True
<del> super(CustomVariationalLayer, self).__init__(**kwargs)
<del>
<del> def vae_loss(self, x, x_decoded_mean_squash):
<del> x = K.flatten(x)
<del> x_decoded_mean_squash = K.flatten(x_decoded_mean_squash)
<del> xent_loss = img_rows * img_cols * metrics.binary_crossentropy(x, x_decoded_mean_squash)
<del> kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
<del> return K.mean(xent_loss + kl_loss)
<del>
<del> def call(self, inputs):
<del> x = inputs[0]
<del> x_decoded_mean_squash = inputs[1]
<del> loss = self.vae_loss(x, x_decoded_mean_squash)
<del> self.add_loss(loss, inputs=inputs)
<del> # We don't use this output.
<del> return x
<del>
<add># Compute VAE loss
<add>xent_loss = img_rows * img_cols * metrics.binary_crossentropy(
<add> K.flatten(x),
<add> K.flatten(x_decoded_mean_squash))
<add>kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
<add>vae_loss = K.mean(xent_loss + kl_loss)
<add>vae.add_loss(vae_loss)
<ide>
<del>y = CustomVariationalLayer()([x, x_decoded_mean_squash])
<del>vae = Model(x, y)
<del>vae.compile(optimizer='rmsprop', loss=None)
<add>vae.compile(optimizer='rmsprop')
<ide> vae.summary()
<ide>
<ide> # train the VAE on MNIST digits
<ide><path>keras/engine/training.py
<ide> class Model(Container):
<ide> """The `Model` class adds training & evaluation routines to a `Container`.
<ide> """
<ide>
<del> def compile(self, optimizer, loss, metrics=None, loss_weights=None,
<add> def compile(self, optimizer, loss=None, metrics=None, loss_weights=None,
<ide> sample_weight_mode=None, weighted_metrics=None,
<ide> target_tensors=None, **kwargs):
<ide> """Configures the model for training. | 3 |
PHP | PHP | use tries as the property | ee385fa5eab0c4642f47636f0e033e982d402bb9 | <ide><path>src/Illuminate/Queue/Jobs/Job.php
<ide> public function payload()
<ide> *
<ide> * @return int|null
<ide> */
<del> public function retries()
<add> public function maxTries()
<ide> {
<del> return array_get($this->payload(), 'retries');
<add> return array_get($this->payload(), 'maxTries');
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Queue/Queue.php
<ide> protected function createPayload($job, $data = '', $queue = null)
<ide> if (is_object($job)) {
<ide> $payload = json_encode([
<ide> 'job' => 'Illuminate\Queue\CallQueuedHandler@call',
<del> 'retries' => isset($job->retries) ? $job->retries : null,
<add> 'maxTries' => isset($job->tries) ? $job->tries : null,
<ide> 'timeout' => isset($job->timeout) ? $job->timeout : null,
<ide> 'data' => [
<ide> 'commandName' => get_class($job),
<ide><path>src/Illuminate/Queue/Worker.php
<ide> protected function handleJobException($connectionName, $job, WorkerOptions $opti
<ide> */
<ide> protected function markJobAsFailedIfAlreadyExceedsMaxAttempts($connectionName, $job, $maxTries)
<ide> {
<del> $maxTries = ! is_null($job->retries()) ? $job->retries() : $maxTries;
<add> $maxTries = ! is_null($job->maxTries()) ? $job->maxTries() : $maxTries;
<ide>
<ide> if ($maxTries === 0 || $job->attempts() <= $maxTries) {
<ide> return;
<ide> protected function markJobAsFailedIfAlreadyExceedsMaxAttempts($connectionName, $
<ide> protected function markJobAsFailedIfHasExceededMaxAttempts(
<ide> $connectionName, $job, $maxTries, $e
<ide> ) {
<del> $maxTries = ! is_null($job->retries()) ? $job->retries() : $maxTries;
<add> $maxTries = ! is_null($job->maxTries()) ? $job->maxTries() : $maxTries;
<ide>
<ide> if ($maxTries === 0 || $job->attempts() < $maxTries) {
<ide> return;
<ide><path>tests/Queue/QueueWorkerTest.php
<ide> public function test_job_based_max_retries()
<ide> });
<ide> $job->attempts = 2;
<ide>
<del> $job->retries = 10;
<add> $job->maxTries = 10;
<ide>
<ide> $worker = $this->getWorker('default', ['queue' => [$job]]);
<ide> $worker->runNextJob('default', 'queue', $this->workerOptions(['maxTries' => 1]));
<ide> class WorkerFakeJob
<ide> public $callback;
<ide> public $deleted = false;
<ide> public $releaseAfter;
<del> public $retries;
<add> public $maxTries;
<ide> public $attempts = 0;
<ide> public $failedWith;
<ide>
<ide> public function payload()
<ide> return [];
<ide> }
<ide>
<del> public function retries()
<add> public function maxTries()
<ide> {
<del> return $this->retries;
<add> return $this->maxTries;
<ide> }
<ide>
<ide> public function delete() | 4 |
Ruby | Ruby | move command shortening to method | 254b2b9daf9392301aa0cfccd62615e869e1850b | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def status_upcase
<ide> @status.to_s.upcase
<ide> end
<ide>
<add> def command_short
<add> @command.gsub(/(brew|--verbose|--build-bottle) /, '')
<add> end
<add>
<ide> def passed?
<ide> @status == :passed
<ide> end
<ide> def run
<ide> tests.each do |test|
<ide> test.steps.each do |step|
<ide> next unless step.failed?
<del> failed_steps << step.command.gsub(/(brew|--verbose) /, '')
<add> failed_steps << step.command_short
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | remove un-used variable | 78325a13b900c451c5dfd05d5789c8de371f6787 | <ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> public function select($fieldName, $options = array(), $attributes = array()) {
<ide> unset($attributes['type']);
<ide> }
<ide>
<del> if (!isset($selected)) {
<del> $selected = $attributes['value'];
<del> }
<del>
<ide> if (!empty($attributes['multiple'])) {
<ide> $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
<ide> $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart'; | 1 |
Javascript | Javascript | remove openssl options of -no_<prot> | 53835a2092847aec8cd78f25fd819a01ff84c0cc | <ide><path>test/parallel/test-tls-no-sslv3.js
<ide> var stderr = '';
<ide> server.listen(0, '127.0.0.1', function() {
<ide> var address = this.address().address + ':' + this.address().port;
<ide> var args = ['s_client',
<del> '-no_ssl2',
<ide> '-ssl3',
<del> '-no_tls1',
<del> '-no_tls1_1',
<del> '-no_tls1_2',
<ide> '-connect', address];
<ide>
<ide> // for the performance and stability issue in s_client on Windows | 1 |
Python | Python | convert applications to new api | f0e0527591ffd6c061c94d6027c29a31bfb23d78 | <ide><path>keras/applications/__init__.py
<ide> from .resnet50 import ResNet50
<ide> from .inception_v3 import InceptionV3
<ide> from .xception import Xception
<add>from .music_tagger_crnn import MusicTaggerCRNN
<ide><path>keras/applications/inception_v3.py
<ide> import warnings
<ide>
<ide> from ..models import Model
<del>from ..layers import Flatten, Dense, Input, BatchNormalization, merge
<del>from ..layers import Convolution2D, MaxPooling2D, AveragePooling2D
<add>from .. import layers
<add>from ..layers import Flatten, Dense, Input, BatchNormalization
<add>from ..layers import Conv2D, MaxPooling2D, AveragePooling2D, GlobalAveragePooling2D, GlobalMaxPooling2D
<ide> from ..engine.topology import get_source_inputs
<ide> from ..utils.layer_utils import convert_all_kernels_in_model
<ide> from ..utils.data_utils import get_file
<ide>
<ide>
<ide> def conv2d_bn(x, filters, num_row, num_col,
<del> border_mode='same', subsample=(1, 1),
<add> padding='same', strides=(1, 1),
<ide> name=None):
<ide> """Utility function to apply conv + BN.
<ide> """
<ide> def conv2d_bn(x, filters, num_row, num_col,
<ide> bn_axis = 1
<ide> else:
<ide> bn_axis = 3
<del> x = Convolution2D(filters, num_row, num_col,
<del> subsample=subsample,
<del> activation='relu',
<del> border_mode=border_mode,
<del> name=conv_name)(x)
<add> x = Conv2D(filters, (num_row, num_col),
<add> strides=strides,
<add> activation='relu',
<add> padding=padding,
<add> name=conv_name)(x)
<ide> x = BatchNormalization(axis=bn_axis, name=bn_name)(x)
<ide> return x
<ide>
<ide>
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> input_tensor=None, input_shape=None,
<add> pooling=None,
<ide> classes=1000):
<ide> """Instantiate the Inception v3 architecture,
<ide> optionally loading weights pre-trained
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> It should have exactly 3 inputs channels,
<ide> and width and height should be no smaller than 139.
<ide> E.g. `(150, 150, 3)` would be one valid value.
<add> pooling: Optional pooling mode for feature extraction
<add> when `include_top` is `False`.
<add> - `None` means that the output of the model will be
<add> the 4D tensor output of the
<add> last convolutional layer.
<add> - `avg` means that global average pooling
<add> will be applied to the output of the
<add> last convolutional layer, and thus
<add> the output of the model will be a 2D tensor.
<add> - `max` means that global max pooling will
<add> be applied.
<ide> classes: optional number of classes to classify images
<ide> into, only to be specified if `include_top` is True, and
<ide> if no `weights` argument is specified.
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> else:
<ide> channel_axis = 3
<ide>
<del> x = conv2d_bn(img_input, 32, 3, 3, subsample=(2, 2), border_mode='valid')
<del> x = conv2d_bn(x, 32, 3, 3, border_mode='valid')
<add> x = conv2d_bn(img_input, 32, 3, 3, strides=(2, 2), padding='valid')
<add> x = conv2d_bn(x, 32, 3, 3, padding='valid')
<ide> x = conv2d_bn(x, 64, 3, 3)
<ide> x = MaxPooling2D((3, 3), strides=(2, 2))(x)
<ide>
<del> x = conv2d_bn(x, 80, 1, 1, border_mode='valid')
<del> x = conv2d_bn(x, 192, 3, 3, border_mode='valid')
<add> x = conv2d_bn(x, 80, 1, 1, padding='valid')
<add> x = conv2d_bn(x, 192, 3, 3, padding='valid')
<ide> x = MaxPooling2D((3, 3), strides=(2, 2))(x)
<ide>
<ide> # mixed 0, 1, 2: 35 x 35 x 256
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
<ide>
<ide> branch_pool = AveragePooling2D(
<del> (3, 3), strides=(1, 1), border_mode='same')(x)
<add> (3, 3), strides=(1, 1), padding='same')(x)
<ide> branch_pool = conv2d_bn(branch_pool, 32, 1, 1)
<del> x = merge([branch1x1, branch5x5, branch3x3dbl, branch_pool],
<del> mode='concat', concat_axis=channel_axis,
<del> name='mixed' + str(i))
<add> x = layers.concatenate([branch1x1, branch5x5, branch3x3dbl, branch_pool],
<add> axis=channel_axis,
<add> name='mixed' + str(i))
<ide>
<ide> # mixed 3: 17 x 17 x 768
<del> branch3x3 = conv2d_bn(x, 384, 3, 3, subsample=(2, 2), border_mode='valid')
<add> branch3x3 = conv2d_bn(x, 384, 3, 3, strides=(2, 2), padding='valid')
<ide>
<ide> branch3x3dbl = conv2d_bn(x, 64, 1, 1)
<ide> branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
<ide> branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3,
<del> subsample=(2, 2), border_mode='valid')
<add> strides=(2, 2), padding='valid')
<ide>
<ide> branch_pool = MaxPooling2D((3, 3), strides=(2, 2))(x)
<del> x = merge([branch3x3, branch3x3dbl, branch_pool],
<del> mode='concat', concat_axis=channel_axis,
<del> name='mixed3')
<add> x = layers.concatenate([branch3x3, branch3x3dbl, branch_pool],
<add> axis=channel_axis,
<add> name='mixed3')
<ide>
<ide> # mixed 4: 17 x 17 x 768
<ide> branch1x1 = conv2d_bn(x, 192, 1, 1)
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 7, 1)
<ide> branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
<ide>
<del> branch_pool = AveragePooling2D((3, 3), strides=(1, 1), border_mode='same')(x)
<add> branch_pool = AveragePooling2D((3, 3), strides=(1, 1), padding='same')(x)
<ide> branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
<del> x = merge([branch1x1, branch7x7, branch7x7dbl, branch_pool],
<del> mode='concat', concat_axis=channel_axis,
<del> name='mixed4')
<add> x = layers.concatenate([branch1x1, branch7x7, branch7x7dbl, branch_pool],
<add> axis=channel_axis,
<add> name='mixed4')
<ide>
<ide> # mixed 5, 6: 17 x 17 x 768
<ide> for i in range(2):
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
<ide>
<ide> branch_pool = AveragePooling2D(
<del> (3, 3), strides=(1, 1), border_mode='same')(x)
<add> (3, 3), strides=(1, 1), padding='same')(x)
<ide> branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
<del> x = merge([branch1x1, branch7x7, branch7x7dbl, branch_pool],
<del> mode='concat', concat_axis=channel_axis,
<del> name='mixed' + str(5 + i))
<add> x = layers.concatenate([branch1x1, branch7x7, branch7x7dbl, branch_pool],
<add> axis=channel_axis,
<add> name='mixed' + str(5 + i))
<ide>
<ide> # mixed 7: 17 x 17 x 768
<ide> branch1x1 = conv2d_bn(x, 192, 1, 1)
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 7, 1)
<ide> branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
<ide>
<del> branch_pool = AveragePooling2D((3, 3), strides=(1, 1), border_mode='same')(x)
<add> branch_pool = AveragePooling2D((3, 3), strides=(1, 1), padding='same')(x)
<ide> branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
<del> x = merge([branch1x1, branch7x7, branch7x7dbl, branch_pool],
<del> mode='concat', concat_axis=channel_axis,
<del> name='mixed7')
<add> x = layers.concatenate([branch1x1, branch7x7, branch7x7dbl, branch_pool],
<add> axis=channel_axis,
<add> name='mixed7')
<ide>
<ide> # mixed 8: 8 x 8 x 1280
<ide> branch3x3 = conv2d_bn(x, 192, 1, 1)
<ide> branch3x3 = conv2d_bn(branch3x3, 320, 3, 3,
<del> subsample=(2, 2), border_mode='valid')
<add> strides=(2, 2), padding='valid')
<ide>
<ide> branch7x7x3 = conv2d_bn(x, 192, 1, 1)
<ide> branch7x7x3 = conv2d_bn(branch7x7x3, 192, 1, 7)
<ide> branch7x7x3 = conv2d_bn(branch7x7x3, 192, 7, 1)
<ide> branch7x7x3 = conv2d_bn(branch7x7x3, 192, 3, 3,
<del> subsample=(2, 2), border_mode='valid')
<add> strides=(2, 2), padding='valid')
<ide>
<ide> branch_pool = AveragePooling2D((3, 3), strides=(2, 2))(x)
<del> x = merge([branch3x3, branch7x7x3, branch_pool],
<del> mode='concat', concat_axis=channel_axis,
<del> name='mixed8')
<add> x = layers.concatenate([branch3x3, branch7x7x3, branch_pool],
<add> axis=channel_axis,
<add> name='mixed8')
<ide>
<ide> # mixed 9: 8 x 8 x 2048
<ide> for i in range(2):
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> branch3x3 = conv2d_bn(x, 384, 1, 1)
<ide> branch3x3_1 = conv2d_bn(branch3x3, 384, 1, 3)
<ide> branch3x3_2 = conv2d_bn(branch3x3, 384, 3, 1)
<del> branch3x3 = merge([branch3x3_1, branch3x3_2],
<del> mode='concat', concat_axis=channel_axis,
<del> name='mixed9_' + str(i))
<add> branch3x3 = layers.concatenate([branch3x3_1, branch3x3_2],
<add> axis=channel_axis,
<add> name='mixed9_' + str(i))
<ide>
<ide> branch3x3dbl = conv2d_bn(x, 448, 1, 1)
<ide> branch3x3dbl = conv2d_bn(branch3x3dbl, 384, 3, 3)
<ide> branch3x3dbl_1 = conv2d_bn(branch3x3dbl, 384, 1, 3)
<ide> branch3x3dbl_2 = conv2d_bn(branch3x3dbl, 384, 3, 1)
<del> branch3x3dbl = merge([branch3x3dbl_1, branch3x3dbl_2],
<del> mode='concat', concat_axis=channel_axis)
<add> branch3x3dbl = layers.concatenate([branch3x3dbl_1, branch3x3dbl_2],
<add> axis=channel_axis)
<ide>
<ide> branch_pool = AveragePooling2D(
<del> (3, 3), strides=(1, 1), border_mode='same')(x)
<add> (3, 3), strides=(1, 1), padding='same')(x)
<ide> branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
<del> x = merge([branch1x1, branch3x3, branch3x3dbl, branch_pool],
<del> mode='concat', concat_axis=channel_axis,
<del> name='mixed' + str(9 + i))
<add> x = layers.concatenate([branch1x1, branch3x3, branch3x3dbl, branch_pool],
<add> axis=channel_axis,
<add> name='mixed' + str(9 + i))
<ide>
<ide> if include_top:
<ide> # Classification block
<ide> x = AveragePooling2D((8, 8), strides=(8, 8), name='avg_pool')(x)
<ide> x = Flatten(name='flatten')(x)
<ide> x = Dense(classes, activation='softmax', name='predictions')(x)
<add> else:
<add> if pooling == 'avg':
<add> x = GlobalAveragePooling2D()(x)
<add> elif pooling == 'max':
<add> x = GlobalMaxPooling2D()(x)
<ide>
<ide> # Ensure that the model takes into account
<ide> # any potential predecessors of `input_tensor`.
<ide><path>keras/applications/music_tagger_crnn.py
<ide> from .. import backend as K
<ide> from ..layers import Input, Dense
<ide> from ..models import Model
<del>from ..layers import Dense, Dropout, Reshape, Permute
<del>from ..layers.convolutional import Convolution2D
<add>from ..layers import Reshape, Permute
<add>from ..layers.convolutional import Conv2D
<ide> from ..layers.convolutional import MaxPooling2D, ZeroPadding2D
<ide> from ..layers.normalization import BatchNormalization
<ide> from ..layers.advanced_activations import ELU
<ide>
<ide>
<ide> def MusicTaggerCRNN(weights='msd', input_tensor=None,
<del> include_top=True, classes=50):
<add> include_top=True,
<add> classes=50):
<ide> """Instantiate the MusicTaggerCRNN architecture,
<ide> optionally loading weights pre-trained
<ide> on Million Song Dataset. Note that when using TensorFlow,
<ide> def MusicTaggerCRNN(weights='msd', input_tensor=None,
<ide> # Determine input axis
<ide> if K.image_data_format() == 'channels_first':
<ide> channel_axis = 1
<del> freq_axis = 2
<ide> time_axis = 3
<ide> else:
<ide> channel_axis = 3
<del> freq_axis = 1
<ide> time_axis = 2
<ide>
<ide> # Input block
<ide> x = ZeroPadding2D(padding=(0, 37))(melgram_input)
<ide> x = BatchNormalization(axis=time_axis, name='bn_0_freq')(x)
<ide>
<ide> # Conv block 1
<del> x = Convolution2D(64, 3, 3, border_mode='same', name='conv1')(x)
<del> x = BatchNormalization(axis=channel_axis, mode=0, name='bn1')(x)
<add> x = Conv2D(64, (3, 3), padding='same', name='conv1')(x)
<add> x = BatchNormalization(axis=channel_axis, name='bn1')(x)
<ide> x = ELU()(x)
<ide> x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), name='pool1')(x)
<ide>
<ide> # Conv block 2
<del> x = Convolution2D(128, 3, 3, border_mode='same', name='conv2')(x)
<del> x = BatchNormalization(axis=channel_axis, mode=0, name='bn2')(x)
<add> x = Conv2D(128, (3, 3), padding='same', name='conv2')(x)
<add> x = BatchNormalization(axis=channel_axis, name='bn2')(x)
<ide> x = ELU()(x)
<ide> x = MaxPooling2D(pool_size=(3, 3), strides=(3, 3), name='pool2')(x)
<ide>
<ide> # Conv block 3
<del> x = Convolution2D(128, 3, 3, border_mode='same', name='conv3')(x)
<del> x = BatchNormalization(axis=channel_axis, mode=0, name='bn3')(x)
<add> x = Conv2D(128, (3, 3), padding='same', name='conv3')(x)
<add> x = BatchNormalization(axis=channel_axis, name='bn3')(x)
<ide> x = ELU()(x)
<ide> x = MaxPooling2D(pool_size=(4, 4), strides=(4, 4), name='pool3')(x)
<ide>
<ide> # Conv block 4
<del> x = Convolution2D(128, 3, 3, border_mode='same', name='conv4')(x)
<del> x = BatchNormalization(axis=channel_axis, mode=0, name='bn4')(x)
<add> x = Conv2D(128, (3, 3), padding='same', name='conv4')(x)
<add> x = BatchNormalization(axis=channel_axis, name='bn4')(x)
<ide> x = ELU()(x)
<ide> x = MaxPooling2D(pool_size=(4, 4), strides=(4, 4), name='pool4')(x)
<ide>
<ide><path>keras/applications/resnet50.py
<ide>
<ide> import warnings
<ide>
<del>from ..layers import merge, Input
<add>from ..layers import Input
<add>from .. import layers
<ide> from ..layers import Dense, Activation, Flatten
<del>from ..layers import Convolution2D, MaxPooling2D, ZeroPadding2D, AveragePooling2D
<add>from ..layers import Conv2D, MaxPooling2D, ZeroPadding2D, AveragePooling2D, GlobalAveragePooling2D, GlobalMaxPooling2D
<ide> from ..layers import BatchNormalization
<ide> from ..models import Model
<ide> from .. import backend as K
<ide> def identity_block(input_tensor, kernel_size, filters, stage, block):
<ide> conv_name_base = 'res' + str(stage) + block + '_branch'
<ide> bn_name_base = 'bn' + str(stage) + block + '_branch'
<ide>
<del> x = Convolution2D(filters1, 1, 1, name=conv_name_base + '2a')(input_tensor)
<add> x = Conv2D(filters1, (1, 1), name=conv_name_base + '2a')(input_tensor)
<ide> x = BatchNormalization(axis=bn_axis, name=bn_name_base + '2a')(x)
<ide> x = Activation('relu')(x)
<ide>
<del> x = Convolution2D(filters2, kernel_size, kernel_size,
<del> border_mode='same', name=conv_name_base + '2b')(x)
<add> x = Conv2D(filters2, kernel_size, kernel_size,
<add> pading='same', name=conv_name_base + '2b')(x)
<ide> x = BatchNormalization(axis=bn_axis, name=bn_name_base + '2b')(x)
<ide> x = Activation('relu')(x)
<ide>
<del> x = Convolution2D(filters3, 1, 1, name=conv_name_base + '2c')(x)
<add> x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c')(x)
<ide> x = BatchNormalization(axis=bn_axis, name=bn_name_base + '2c')(x)
<ide>
<del> x = merge([x, input_tensor], mode='sum')
<add> x = layers.sum([x, input_tensor])
<ide> x = Activation('relu')(x)
<ide> return x
<ide>
<ide> def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2))
<ide> stage: integer, current stage label, used for generating layer names
<ide> block: 'a','b'..., current block label, used for generating layer names
<ide>
<del> Note that from stage 3, the first conv layer at main path is with subsample=(2,2)
<del> And the shortcut should have subsample=(2,2) as well
<add> Note that from stage 3, the first conv layer at main path is with strides=(2,2)
<add> And the shortcut should have strides=(2,2) as well
<ide> """
<ide> filters1, filters2, filters3 = filters
<ide> if K.image_data_format() == 'channels_last':
<ide> def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2))
<ide> conv_name_base = 'res' + str(stage) + block + '_branch'
<ide> bn_name_base = 'bn' + str(stage) + block + '_branch'
<ide>
<del> x = Convolution2D(filters1, 1, 1, subsample=strides,
<del> name=conv_name_base + '2a')(input_tensor)
<add> x = Conv2D(filters1, (1, 1), strides=strides,
<add> name=conv_name_base + '2a')(input_tensor)
<ide> x = BatchNormalization(axis=bn_axis, name=bn_name_base + '2a')(x)
<ide> x = Activation('relu')(x)
<ide>
<del> x = Convolution2D(filters2, kernel_size, kernel_size, border_mode='same',
<del> name=conv_name_base + '2b')(x)
<add> x = Conv2D(filters2, (kernel_size, kernel_size), pading='same',
<add> name=conv_name_base + '2b')(x)
<ide> x = BatchNormalization(axis=bn_axis, name=bn_name_base + '2b')(x)
<ide> x = Activation('relu')(x)
<ide>
<del> x = Convolution2D(filters3, 1, 1, name=conv_name_base + '2c')(x)
<add> x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c')(x)
<ide> x = BatchNormalization(axis=bn_axis, name=bn_name_base + '2c')(x)
<ide>
<del> shortcut = Convolution2D(filters3, 1, 1, subsample=strides,
<del> name=conv_name_base + '1')(input_tensor)
<add> shortcut = Conv2D(filters3, (1, 1), strides=strides,
<add> name=conv_name_base + '1')(input_tensor)
<ide> shortcut = BatchNormalization(axis=bn_axis, name=bn_name_base + '1')(shortcut)
<ide>
<del> x = merge([x, shortcut], mode='sum')
<add> x = layers.sum([x, shortcut])
<ide> x = Activation('relu')(x)
<ide> return x
<ide>
<ide>
<ide> def ResNet50(include_top=True, weights='imagenet',
<ide> input_tensor=None, input_shape=None,
<add> pooling=None,
<ide> classes=1000):
<ide> """Instantiate the ResNet50 architecture,
<ide> optionally loading weights pre-trained
<ide> def ResNet50(include_top=True, weights='imagenet',
<ide> It should have exactly 3 inputs channels,
<ide> and width and height should be no smaller than 197.
<ide> E.g. `(200, 200, 3)` would be one valid value.
<add> pooling: Optional pooling mode for feature extraction
<add> when `include_top` is `False`.
<add> - `None` means that the output of the model will be
<add> the 4D tensor output of the
<add> last convolutional layer.
<add> - `avg` means that global average pooling
<add> will be applied to the output of the
<add> last convolutional layer, and thus
<add> the output of the model will be a 2D tensor.
<add> - `max` means that global max pooling will
<add> be applied.
<ide> classes: optional number of classes to classify images
<ide> into, only to be specified if `include_top` is True, and
<ide> if no `weights` argument is specified.
<ide> def ResNet50(include_top=True, weights='imagenet',
<ide> bn_axis = 1
<ide>
<ide> x = ZeroPadding2D((3, 3))(img_input)
<del> x = Convolution2D(64, 7, 7, subsample=(2, 2), name='conv1')(x)
<add> x = Conv2D(64, (7, 7), strides=(2, 2), name='conv1')(x)
<ide> x = BatchNormalization(axis=bn_axis, name='bn_conv1')(x)
<ide> x = Activation('relu')(x)
<ide> x = MaxPooling2D((3, 3), strides=(2, 2))(x)
<ide> def ResNet50(include_top=True, weights='imagenet',
<ide> if include_top:
<ide> x = Flatten()(x)
<ide> x = Dense(classes, activation='softmax', name='fc1000')(x)
<add> else:
<add> if pooling == 'avg':
<add> x = GlobalAveragePooling2D()(x)
<add> elif pooling == 'max':
<add> x = GlobalMaxPooling2D()(x)
<ide>
<ide> # Ensure that the model takes into account
<ide> # any potential predecessors of `input_tensor`.
<ide><path>keras/applications/vgg16.py
<ide>
<ide> from ..models import Model
<ide> from ..layers import Flatten, Dense, Input
<del>from ..layers import Convolution2D, MaxPooling2D
<add>from ..layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, GlobalMaxPooling2D
<ide> from ..engine.topology import get_source_inputs
<ide> from ..utils.layer_utils import convert_all_kernels_in_model
<ide> from ..utils.data_utils import get_file
<ide>
<ide> def VGG16(include_top=True, weights='imagenet',
<ide> input_tensor=None, input_shape=None,
<add> pooling=None,
<ide> classes=1000):
<ide> """Instantiate the VGG16 architecture,
<ide> optionally loading weights pre-trained
<ide> def VGG16(include_top=True, weights='imagenet',
<ide> It should have exactly 3 inputs channels,
<ide> and width and height should be no smaller than 48.
<ide> E.g. `(200, 200, 3)` would be one valid value.
<add> pooling: Optional pooling mode for feature extraction
<add> when `include_top` is `False`.
<add> - `None` means that the output of the model will be
<add> the 4D tensor output of the
<add> last convolutional layer.
<add> - `avg` means that global average pooling
<add> will be applied to the output of the
<add> last convolutional layer, and thus
<add> the output of the model will be a 2D tensor.
<add> - `max` means that global max pooling will
<add> be applied.
<ide> classes: optional number of classes to classify images
<ide> into, only to be specified if `include_top` is True, and
<ide> if no `weights` argument is specified.
<ide> def VGG16(include_top=True, weights='imagenet',
<ide> else:
<ide> img_input = input_tensor
<ide> # Block 1
<del> x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv1')(img_input)
<del> x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv2')(x)
<add> x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)
<add> x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
<ide>
<ide> # Block 2
<del> x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv1')(x)
<del> x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv2')(x)
<add> x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)
<add> x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)
<ide>
<ide> # Block 3
<del> x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv1')(x)
<del> x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv2')(x)
<del> x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv3')(x)
<add> x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)
<add> x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)
<add> x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)
<ide>
<ide> # Block 4
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv1')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv2')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv3')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)
<ide>
<ide> # Block 5
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv1')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv2')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv3')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)
<ide>
<ide> if include_top:
<ide> def VGG16(include_top=True, weights='imagenet',
<ide> x = Dense(4096, activation='relu', name='fc1')(x)
<ide> x = Dense(4096, activation='relu', name='fc2')(x)
<ide> x = Dense(classes, activation='softmax', name='predictions')(x)
<add> else:
<add> if pooling == 'avg':
<add> x = GlobalAveragePooling2D()(x)
<add> elif pooling == 'max':
<add> x = GlobalMaxPooling2D()(x)
<ide>
<ide> # Ensure that the model takes into account
<ide> # any potential predecessors of `input_tensor`.
<ide><path>keras/applications/vgg19.py
<ide>
<ide> from ..models import Model
<ide> from ..layers import Flatten, Dense, Input
<del>from ..layers import Convolution2D, MaxPooling2D, GlobalAveragePooling, GlobalMaxPooling
<add>from ..layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, GlobalMaxPooling2D
<ide> from ..engine.topology import get_source_inputs
<ide> from ..utils.layer_utils import convert_all_kernels_in_model
<ide> from ..utils.data_utils import get_file
<ide> def VGG19(include_top=True, weights='imagenet',
<ide> else:
<ide> img_input = input_tensor
<ide> # Block 1
<del> x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv1')(img_input)
<del> x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv2')(x)
<add> x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)
<add> x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
<ide>
<ide> # Block 2
<del> x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv1')(x)
<del> x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv2')(x)
<add> x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)
<add> x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)
<ide>
<ide> # Block 3
<del> x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv1')(x)
<del> x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv2')(x)
<del> x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv3')(x)
<del> x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv4')(x)
<add> x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)
<add> x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)
<add> x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)
<add> x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv4')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)
<ide>
<ide> # Block 4
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv1')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv2')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv3')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv4')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)
<ide>
<ide> # Block 5
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv1')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv2')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv3')(x)
<del> x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv4')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)
<add> x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv4')(x)
<ide> x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)
<ide>
<ide> if include_top:
<ide> def VGG19(include_top=True, weights='imagenet',
<ide> x = Dense(classes, activation='softmax', name='predictions')(x)
<ide> else:
<ide> if pooling == 'avg':
<del> x = GlobalAveragePooling()(x)
<add> x = GlobalAveragePooling2D()(x)
<ide> elif pooling == 'max':
<del> x = GlobalMaxPooling()(x)
<add> x = GlobalMaxPooling2D()(x)
<ide>
<ide> # Ensure that the model takes into account
<ide> # any potential predecessors of `input_tensor`.
<ide><path>keras/applications/xception.py
<ide> import warnings
<ide>
<ide> from ..models import Model
<del>from ..layers import Dense, Input, BatchNormalization, Activation, merge
<del>from ..layers import Conv2D, SeparableConv2D, MaxPooling2D, GlobalAveragePooling2D
<add>from .. import layers
<add>from ..layers import Dense, Input, BatchNormalization, Activation
<add>from ..layers import Conv2D, SeparableConv2D, MaxPooling2D, GlobalAveragePooling2D, GlobalMaxPooling2D
<ide> from ..engine.topology import get_source_inputs
<ide> from ..utils.data_utils import get_file
<ide> from .. import backend as K
<ide>
<ide> def Xception(include_top=True, weights='imagenet',
<ide> input_tensor=None, input_shape=None,
<add> pooling=None,
<ide> classes=1000):
<ide> """Instantiate the Xception architecture,
<ide> optionally loading weights pre-trained
<ide> def Xception(include_top=True, weights='imagenet',
<ide> It should have exactly 3 inputs channels,
<ide> and width and height should be no smaller than 71.
<ide> E.g. `(150, 150, 3)` would be one valid value.
<add> pooling: Optional pooling mode for feature extraction
<add> when `include_top` is `False`.
<add> - `None` means that the output of the model will be
<add> the 4D tensor output of the
<add> last convolutional layer.
<add> - `avg` means that global average pooling
<add> will be applied to the output of the
<add> last convolutional layer, and thus
<add> the output of the model will be a 2D tensor.
<add> - `max` means that global max pooling will
<add> be applied.
<ide> classes: optional number of classes to classify images
<ide> into, only to be specified if `include_top` is True, and
<ide> if no `weights` argument is specified.
<ide> def Xception(include_top=True, weights='imagenet',
<ide> else:
<ide> img_input = input_tensor
<ide>
<del> x = Conv2D(32, 3, 3, subsample=(2, 2), bias=False, name='block1_conv1')(img_input)
<add> x = Conv2D(32, (3, 3), strides=(2, 2), use_bias=False, name='block1_conv1')(img_input)
<ide> x = BatchNormalization(name='block1_conv1_bn')(x)
<ide> x = Activation('relu', name='block1_conv1_act')(x)
<del> x = Conv2D(64, 3, 3, bias=False, name='block1_conv2')(x)
<add> x = Conv2D(64, (3, 3), use_bias=False, name='block1_conv2')(x)
<ide> x = BatchNormalization(name='block1_conv2_bn')(x)
<ide> x = Activation('relu', name='block1_conv2_act')(x)
<ide>
<del> residual = Conv2D(128, 1, 1, subsample=(2, 2),
<del> border_mode='same', bias=False)(x)
<add> residual = Conv2D(128, (1, 1), strides=(2, 2),
<add> padding='same', use_bias=False)(x)
<ide> residual = BatchNormalization()(residual)
<ide>
<del> x = SeparableConv2D(128, 3, 3, border_mode='same', bias=False, name='block2_sepconv1')(x)
<add> x = SeparableConv2D(128, (3, 3), padding='same', use_bias=False, name='block2_sepconv1')(x)
<ide> x = BatchNormalization(name='block2_sepconv1_bn')(x)
<ide> x = Activation('relu', name='block2_sepconv2_act')(x)
<del> x = SeparableConv2D(128, 3, 3, border_mode='same', bias=False, name='block2_sepconv2')(x)
<add> x = SeparableConv2D(128, (3, 3), padding='same', use_bias=False, name='block2_sepconv2')(x)
<ide> x = BatchNormalization(name='block2_sepconv2_bn')(x)
<ide>
<del> x = MaxPooling2D((3, 3), strides=(2, 2), border_mode='same', name='block2_pool')(x)
<del> x = merge([x, residual], mode='sum')
<add> x = MaxPooling2D((3, 3), strides=(2, 2), padding='same', name='block2_pool')(x)
<add> x = layers.sum([x, residual])
<ide>
<del> residual = Conv2D(256, 1, 1, subsample=(2, 2),
<del> border_mode='same', bias=False)(x)
<add> residual = Conv2D(256, (1, 1), strides=(2, 2),
<add> padding='same', use_bias=False)(x)
<ide> residual = BatchNormalization()(residual)
<ide>
<ide> x = Activation('relu', name='block3_sepconv1_act')(x)
<del> x = SeparableConv2D(256, 3, 3, border_mode='same', bias=False, name='block3_sepconv1')(x)
<add> x = SeparableConv2D(256, (3, 3), padding='same', use_bias=False, name='block3_sepconv1')(x)
<ide> x = BatchNormalization(name='block3_sepconv1_bn')(x)
<ide> x = Activation('relu', name='block3_sepconv2_act')(x)
<del> x = SeparableConv2D(256, 3, 3, border_mode='same', bias=False, name='block3_sepconv2')(x)
<add> x = SeparableConv2D(256, (3, 3), padding='same', use_bias=False, name='block3_sepconv2')(x)
<ide> x = BatchNormalization(name='block3_sepconv2_bn')(x)
<ide>
<del> x = MaxPooling2D((3, 3), strides=(2, 2), border_mode='same', name='block3_pool')(x)
<del> x = merge([x, residual], mode='sum')
<add> x = MaxPooling2D((3, 3), strides=(2, 2), padding='same', name='block3_pool')(x)
<add> x = layers.sum([x, residual])
<ide>
<del> residual = Conv2D(728, 1, 1, subsample=(2, 2),
<del> border_mode='same', bias=False)(x)
<add> residual = Conv2D(728, (1, 1), strides=(2, 2),
<add> padding='same', use_bias=False)(x)
<ide> residual = BatchNormalization()(residual)
<ide>
<ide> x = Activation('relu', name='block4_sepconv1_act')(x)
<del> x = SeparableConv2D(728, 3, 3, border_mode='same', bias=False, name='block4_sepconv1')(x)
<add> x = SeparableConv2D(728, (3, 3), padding='same', use_bias=False, name='block4_sepconv1')(x)
<ide> x = BatchNormalization(name='block4_sepconv1_bn')(x)
<ide> x = Activation('relu', name='block4_sepconv2_act')(x)
<del> x = SeparableConv2D(728, 3, 3, border_mode='same', bias=False, name='block4_sepconv2')(x)
<add> x = SeparableConv2D(728, (3, 3), padding='same', use_bias=False, name='block4_sepconv2')(x)
<ide> x = BatchNormalization(name='block4_sepconv2_bn')(x)
<ide>
<del> x = MaxPooling2D((3, 3), strides=(2, 2), border_mode='same', name='block4_pool')(x)
<del> x = merge([x, residual], mode='sum')
<add> x = MaxPooling2D((3, 3), strides=(2, 2), padding='same', name='block4_pool')(x)
<add> x = layers.sum([x, residual])
<ide>
<ide> for i in range(8):
<ide> residual = x
<ide> prefix = 'block' + str(i + 5)
<ide>
<ide> x = Activation('relu', name=prefix + '_sepconv1_act')(x)
<del> x = SeparableConv2D(728, 3, 3, border_mode='same', bias=False, name=prefix + '_sepconv1')(x)
<add> x = SeparableConv2D(728, (3, 3), padding='same', use_bias=False, name=prefix + '_sepconv1')(x)
<ide> x = BatchNormalization(name=prefix + '_sepconv1_bn')(x)
<ide> x = Activation('relu', name=prefix + '_sepconv2_act')(x)
<del> x = SeparableConv2D(728, 3, 3, border_mode='same', bias=False, name=prefix + '_sepconv2')(x)
<add> x = SeparableConv2D(728, (3, 3), padding='same', use_bias=False, name=prefix + '_sepconv2')(x)
<ide> x = BatchNormalization(name=prefix + '_sepconv2_bn')(x)
<ide> x = Activation('relu', name=prefix + '_sepconv3_act')(x)
<del> x = SeparableConv2D(728, 3, 3, border_mode='same', bias=False, name=prefix + '_sepconv3')(x)
<add> x = SeparableConv2D(728, (3, 3), padding='same', use_bias=False, name=prefix + '_sepconv3')(x)
<ide> x = BatchNormalization(name=prefix + '_sepconv3_bn')(x)
<ide>
<del> x = merge([x, residual], mode='sum')
<add> x = layers.sum([x, residual])
<ide>
<del> residual = Conv2D(1024, 1, 1, subsample=(2, 2),
<del> border_mode='same', bias=False)(x)
<add> residual = Conv2D(1024, (1, 1), strides=(2, 2),
<add> padding='same', use_bias=False)(x)
<ide> residual = BatchNormalization()(residual)
<ide>
<ide> x = Activation('relu', name='block13_sepconv1_act')(x)
<del> x = SeparableConv2D(728, 3, 3, border_mode='same', bias=False, name='block13_sepconv1')(x)
<add> x = SeparableConv2D(728, (3, 3), padding='same', use_bias=False, name='block13_sepconv1')(x)
<ide> x = BatchNormalization(name='block13_sepconv1_bn')(x)
<ide> x = Activation('relu', name='block13_sepconv2_act')(x)
<del> x = SeparableConv2D(1024, 3, 3, border_mode='same', bias=False, name='block13_sepconv2')(x)
<add> x = SeparableConv2D(1024, (3, 3), padding='same', use_bias=False, name='block13_sepconv2')(x)
<ide> x = BatchNormalization(name='block13_sepconv2_bn')(x)
<ide>
<del> x = MaxPooling2D((3, 3), strides=(2, 2), border_mode='same', name='block13_pool')(x)
<del> x = merge([x, residual], mode='sum')
<add> x = MaxPooling2D((3, 3), strides=(2, 2), padding='same', name='block13_pool')(x)
<add> x = layers.sum([x, residual])
<ide>
<del> x = SeparableConv2D(1536, 3, 3, border_mode='same', bias=False, name='block14_sepconv1')(x)
<add> x = SeparableConv2D(1536, (3, 3), padding='same', use_bias=False, name='block14_sepconv1')(x)
<ide> x = BatchNormalization(name='block14_sepconv1_bn')(x)
<ide> x = Activation('relu', name='block14_sepconv1_act')(x)
<ide>
<del> x = SeparableConv2D(2048, 3, 3, border_mode='same', bias=False, name='block14_sepconv2')(x)
<add> x = SeparableConv2D(2048, (3, 3), padding='same', use_bias=False, name='block14_sepconv2')(x)
<ide> x = BatchNormalization(name='block14_sepconv2_bn')(x)
<ide> x = Activation('relu', name='block14_sepconv2_act')(x)
<ide>
<ide> if include_top:
<ide> x = GlobalAveragePooling2D(name='avg_pool')(x)
<ide> x = Dense(classes, activation='softmax', name='predictions')(x)
<add> else:
<add> if pooling == 'avg':
<add> x = GlobalAveragePooling2D()(x)
<add> elif pooling == 'max':
<add> x = GlobalMaxPooling2D()(x)
<ide>
<ide> # Ensure that the model takes into account
<ide> # any potential predecessors of `input_tensor`.
<ide><path>keras/layers/core.py
<ide> class Reshape(Layer):
<ide> def __init__(self, target_shape, **kwargs):
<ide> super(Reshape, self).__init__(**kwargs)
<ide> self.target_shape = tuple(target_shape)
<del> self.input_spec = InputSpec(ndim=len(self.target_shape) + 1)
<ide>
<ide> def _fix_unknown_dimension(self, input_shape, output_shape):
<ide> """Find and replace a missing dimension in an output shape.
<ide><path>keras/layers/merge.py
<ide> def __init__(self, axis=-1, **kwargs):
<ide>
<ide> def build(self, input_shape):
<ide> # Used purely for shape validation.
<del> if not isinstance(input_shape, list) or len(input_shape) != 2:
<add> if not isinstance(input_shape, list):
<ide> raise ValueError('`Concatenate` layer should be called '
<del> 'on a list of 2 inputs.')
<del> if input_shape[0] is None or input_shape[1] is None:
<del> return
<add> 'on a list of inputs')
<ide> reduced_inputs_shapes = [list(shape) for shape in input_shape]
<ide> shape_set = set()
<ide> for i in range(len(reduced_inputs_shapes)):
<ide> def build(self, input_shape):
<ide> def call(self, inputs):
<ide> if not isinstance(inputs, list):
<ide> raise ValueError('A `Concatenate` layer should be called '
<del> 'on a list of 2 inputs.')
<add> 'on a list of inputs.')
<ide> return K.concatenate(inputs, axis=self.axis)
<ide>
<ide> def compute_output_shape(self, input_shape):
<del> if not isinstance(input_shape, list) or len(input_shape) != 2:
<add> if not isinstance(input_shape, list):
<ide> raise ValueError('A `Concatenate` layer should be called '
<del> 'on a list of 2 inputs.')
<add> 'on a list of inputs.')
<ide> input_shapes = input_shape
<ide> output_shape = list(input_shapes[0])
<ide> for shape in input_shapes[1:]:
<ide><path>keras/layers/pooling.py
<ide> def __init__(self, pool_size=(2, 2), strides=None, padding='valid',
<ide> if strides is None:
<ide> strides = pool_size
<ide> self.pool_size = conv_utils.normalize_tuple(pool_size, 2, 'pool_size')
<del> self.strides = conv_utils.normalize_tuple(pool_size, 2, 'strides')
<add> self.strides = conv_utils.normalize_tuple(strides, 2, 'strides')
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> self.data_format = conv_utils.normalize_data_format(data_format)
<ide> self.input_spec = InputSpec(ndim=4)
<ide><path>tests/keras/test_callbacks.py
<ide> def make_model():
<ide>
<ide> @keras_test
<ide> @pytest.mark.skipif((K.backend() != 'tensorflow'),
<del> reason="Requires tensorflow backend")
<add> reason='Requires tensorflow backend')
<ide> def test_TensorBoard():
<ide> np.random.seed(1337)
<ide> | 11 |
Text | Text | fix typo from perfomrance to performance | 1b69a8bb73f653c3f421cc1f7ae00ad9ce1f24be | <ide><path>fixtures/fizz/README.md
<ide> # Fizz Fixtures
<ide>
<del>A set of basic tests for Fizz primarily focussed on baseline perfomrance of legacy renderToString and streaming implementations.
<add>A set of basic tests for Fizz primarily focussed on baseline performance of legacy renderToString and streaming implementations.
<ide>
<ide> ## Setup
<ide> | 1 |
Ruby | Ruby | simplify trailing slash checks | 187b9c9d593be13b137da7fb675764f57b03a8db | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def get_mounts path=nil
<ide> class Checks
<ide>
<ide> ############# HELPERS
<del> def remove_trailing_slash s
<del> (s[s.length-1] == '/') ? s[0,s.length-1] : s
<del> end
<del>
<ide> def paths
<ide> @paths ||= ENV['PATH'].split(':').collect do |p|
<ide> begin
<del> remove_trailing_slash(File.expand_path(p))
<add> File.expand_path(p).chomp('/')
<ide> rescue ArgumentError
<ide> onoe "The following PATH component is invalid: #{p}"
<ide> end
<ide> def inject_file_list(list, str)
<ide> # Sorry for the lack of an indent here, the diff would have been unreadable.
<ide> # See https://github.com/mxcl/homebrew/pull/9986
<ide> def check_path_for_trailing_slashes
<del> bad_paths = ENV['PATH'].split(':').select{|p| p[p.length-1, p.length] == '/'}
<add> bad_paths = ENV['PATH'].split(':').select { |p| p[-1..-1] == '/' }
<ide> return if bad_paths.empty?
<ide> s = <<-EOS.undent
<ide> Some directories in your path end in a slash. | 1 |
Python | Python | enable morph rules for danish | d86b537a3820b23d66b5a8d52d15ae5d11c2b34b | <ide><path>spacy/lang/da/__init__.py
<ide> class DanishDefaults(Language.Defaults):
<ide> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM],
<ide> BASE_NORMS, NORM_EXCEPTIONS)
<ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
<del> # morph_rules = MORPH_RULES
<add> morph_rules = MORPH_RULES
<ide> tag_map = TAG_MAP
<ide> stop_words = STOP_WORDS
<ide> | 1 |
Javascript | Javascript | remove redundant escape | a26e9a8a57cdf84e8ecb3e39b186d73b39108457 | <ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide> let awaitPromise = false;
<ide> const input = code;
<ide>
<del> if (/^\s*\{/.test(code) && /\}\s*$/.test(code)) {
<add> if (/^\s*{/.test(code) && /}\s*$/.test(code)) {
<ide> // It's confusing for `{ a : 1 }` to be interpreted as a block
<ide> // statement rather than an object literal. So, we first try
<ide> // to wrap it in parentheses, so that it will be interpreted as | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.