content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | implement checkifinvalidmodule in parsers | e97fb466a0c74a7a187032581015dfcbb3c5222c | <ide><path>packages/react-native-codegen/src/parsers/__tests__/error-utils-test.js
<ide> const {
<ide> MoreThanOneModuleInterfaceParserError,
<ide> UnsupportedFunctionParamTypeAnnotationParserError,
<ide> } = require('../errors');
<add>const {FlowParser} = require('../flow/parser');
<add>const {TypeScriptParser} = require('../typescript/parser');
<ide>
<ide> describe('throwIfModuleInterfaceIsMisnamed', () => {
<ide> it("don't throw error if module interface name is Spec", () => {
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> const nativeModuleName = 'moduleName';
<ide> const methodName = 'methodName';
<ide> const moduleName = 'moduleName';
<add> const flowParser = new FlowParser();
<add> const typescriptParser = new TypeScriptParser();
<add>
<ide> it('throw error if flowTypeArguments type is incorrect', () => {
<ide> const flowTypeArguments = {
<ide> type: '',
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> ],
<ide> };
<ide>
<del> const parserType = 'Flow';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> flowTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> flowParser,
<ide> );
<ide> }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> params: [],
<ide> };
<ide>
<del> const parserType = 'Flow';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> flowTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> flowParser,
<ide> );
<ide> }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> ],
<ide> };
<ide>
<del> const parserType = 'Flow';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> flowTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> flowParser,
<ide> );
<ide> }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> ],
<ide> };
<ide>
<del> const parserType = 'Flow';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> flowTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> flowParser,
<ide> );
<ide> }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> ],
<ide> };
<ide>
<del> const parserType = 'Flow';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> flowTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> flowParser,
<ide> );
<ide> }).not.toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> ],
<ide> };
<ide>
<del> const parserType = 'TypeScript';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> typeScriptTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> typescriptParser,
<ide> );
<ide> }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> params: [],
<ide> };
<ide>
<del> const parserType = 'TypeScript';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> typeScriptTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> typescriptParser,
<ide> );
<ide> }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> ],
<ide> };
<ide>
<del> const parserType = 'TypeScript';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> typeScriptTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> typescriptParser,
<ide> );
<ide> }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> ],
<ide> };
<ide>
<del> const parserType = 'TypeScript';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> typeScriptTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> typescriptParser,
<ide> );
<ide> }).toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide> describe('throwIfIncorrectModuleRegistryCallTypeParameterParserError', () => {
<ide> ],
<ide> };
<ide>
<del> const parserType = 'TypeScript';
<del>
<ide> expect(() => {
<ide> throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> typeScriptTypeArguments,
<ide> methodName,
<ide> moduleName,
<del> parserType,
<add> typescriptParser,
<ide> );
<ide> }).not.toThrow(IncorrectModuleRegistryCallTypeParameterParserError);
<ide> });
<ide><path>packages/react-native-codegen/src/parsers/error-utils.js
<ide>
<ide> import type {NativeModuleTypeAnnotation} from '../CodegenSchema';
<ide> import type {ParserType} from './errors';
<add>import type {Parser} from './parser';
<ide>
<ide> const {
<ide> MisnamedModuleInterfaceParserError,
<ide> function throwIfIncorrectModuleRegistryCallTypeParameterParserError(
<ide> typeArguments: $FlowFixMe,
<ide> methodName: string,
<ide> moduleName: string,
<del> language: ParserType,
<add> parser: Parser,
<ide> ) {
<ide> function throwError() {
<ide> throw new IncorrectModuleRegistryCallTypeParameterParserError(
<ide> nativeModuleName,
<ide> typeArguments,
<ide> methodName,
<ide> moduleName,
<del> language,
<add> parser.language(),
<ide> );
<ide> }
<ide>
<del> if (language === 'Flow') {
<del> if (
<del> typeArguments.type !== 'TypeParameterInstantiation' ||
<del> typeArguments.params.length !== 1 ||
<del> typeArguments.params[0].type !== 'GenericTypeAnnotation' ||
<del> typeArguments.params[0].id.name !== 'Spec'
<del> ) {
<del> throwError();
<del> }
<del> } else if (language === 'TypeScript') {
<del> if (
<del> typeArguments.type !== 'TSTypeParameterInstantiation' ||
<del> typeArguments.params.length !== 1 ||
<del> typeArguments.params[0].type !== 'TSTypeReference' ||
<del> typeArguments.params[0].typeName.name !== 'Spec'
<del> ) {
<del> throwError();
<del> }
<add> if (parser.checkIfInvalidModule(typeArguments)) {
<add> throwError();
<ide> }
<ide> }
<ide>
<ide><path>packages/react-native-codegen/src/parsers/flow/modules/index.js
<ide> function buildModuleSchema(
<ide> typeArguments,
<ide> methodName,
<ide> $moduleName,
<del> language,
<add> parser,
<ide> );
<ide>
<ide> return $moduleName;
<ide><path>packages/react-native-codegen/src/parsers/flow/parser.js
<ide> class FlowParser implements Parser {
<ide> nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string {
<ide> return typeAnnotation.id.name;
<ide> }
<add>
<add> checkIfInvalidModule(typeArguments: $FlowFixMe): boolean {
<add> return (
<add> typeArguments.type !== 'TypeParameterInstantiation' ||
<add> typeArguments.params.length !== 1 ||
<add> typeArguments.params[0].type !== 'GenericTypeAnnotation' ||
<add> typeArguments.params[0].id.name !== 'Spec'
<add> );
<add> }
<ide> }
<ide>
<ide> module.exports = {
<ide><path>packages/react-native-codegen/src/parsers/parser.js
<ide> export interface Parser {
<ide> * @returns: the name of the type.
<ide> */
<ide> nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string;
<add> /**
<add> * Given a type arguments, it returns a boolean specifying if the Module is Invalid.
<add> * @parameter typeArguments: the type arguments.
<add> * @returns: a boolean specifying if the Module is Invalid.
<add> */
<add> checkIfInvalidModule(typeArguments: $FlowFixMe): boolean;
<ide> }
<ide><path>packages/react-native-codegen/src/parsers/parserMock.js
<ide> export class MockedParser implements Parser {
<ide> nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string {
<ide> return typeAnnotation.id.name;
<ide> }
<add>
<add> checkIfInvalidModule(typeArguments: $FlowFixMe): boolean {
<add> return false;
<add> }
<ide> }
<ide><path>packages/react-native-codegen/src/parsers/typescript/modules/index.js
<ide> function buildModuleSchema(
<ide> typeParameters,
<ide> methodName,
<ide> $moduleName,
<del> language,
<add> parser,
<ide> );
<ide>
<ide> return $moduleName;
<ide><path>packages/react-native-codegen/src/parsers/typescript/parser.js
<ide> class TypeScriptParser implements Parser {
<ide> nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string {
<ide> return typeAnnotation.typeName.name;
<ide> }
<add>
<add> checkIfInvalidModule(typeArguments: $FlowFixMe): boolean {
<add> return (
<add> typeArguments.type !== 'TSTypeParameterInstantiation' ||
<add> typeArguments.params.length !== 1 ||
<add> typeArguments.params[0].type !== 'TSTypeReference' ||
<add> typeArguments.params[0].typeName.name !== 'Spec'
<add> );
<add> }
<ide> }
<ide> module.exports = {
<ide> TypeScriptParser, | 8 |
Java | Java | add generatedfiles interface and support classes | 99173fbd4f082172d8d9cbe92d0cd1f2b313e19c | <ide><path>spring-core/src/main/java/org/springframework/aot/generate/AppendableConsumerInputStreamSource.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.io.ByteArrayInputStream;
<add>import java.io.IOException;
<add>import java.io.InputStream;
<add>import java.nio.charset.StandardCharsets;
<add>
<add>import org.springframework.core.io.InputStreamSource;
<add>import org.springframework.util.function.ThrowingConsumer;
<add>
<add>/**
<add> * Adapter class to convert a {@link ThrowingConsumer} of {@link Appendable} to
<add> * an {@link InputStreamSource}.
<add> *
<add> * @author Phillip Webb
<add> * @since 6.0
<add> */
<add>class AppendableConsumerInputStreamSource implements InputStreamSource {
<add>
<add> private final ThrowingConsumer<Appendable> content;
<add>
<add>
<add> AppendableConsumerInputStreamSource(ThrowingConsumer<Appendable> content) {
<add> this.content = content;
<add> }
<add>
<add>
<add> @Override
<add> public InputStream getInputStream() throws IOException {
<add> return new ByteArrayInputStream(toString().getBytes(StandardCharsets.UTF_8));
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> StringBuilder buffer = new StringBuilder();
<add> this.content.accept(buffer);
<add> return buffer.toString();
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/generate/FileSystemGeneratedFiles.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.io.IOException;
<add>import java.io.InputStream;
<add>import java.nio.file.FileSystem;
<add>import java.nio.file.Files;
<add>import java.nio.file.Path;
<add>import java.util.Arrays;
<add>import java.util.Objects;
<add>import java.util.function.Function;
<add>
<add>import org.springframework.core.io.InputStreamSource;
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * {@link GeneratedFiles} implementation that stores generated files using a
<add> * {@link FileSystem}.
<add> *
<add> * @author Phillip Webb
<add> * @since 6.0
<add> */
<add>public class FileSystemGeneratedFiles implements GeneratedFiles {
<add>
<add> private final Function<Kind, Path> roots;
<add>
<add>
<add> /**
<add> * Create a new {@link FileSystemGeneratedFiles} instance with all files
<add> * stored under the specific {@code root}. The following subdirectories are
<add> * created for the different file {@link Kind kinds}:
<add> * <ul>
<add> * <li>{@code sources}</li>
<add> * <li>{@code resources}</li>
<add> * <li>{@code classes}</li>
<add> * </ul>
<add> * @param root the root path
<add> * @see #FileSystemGeneratedFiles(Function)
<add> */
<add> public FileSystemGeneratedFiles(Path root) {
<add> this(conventionRoots(root));
<add> }
<add>
<add> /**
<add> * Create a new {@link FileSystemGeneratedFiles} instance with all files
<add> * stored under the root provided by the given {@link Function}.
<add> * @param roots a function that returns the root to use for the given
<add> * {@link Kind}
<add> */
<add> public FileSystemGeneratedFiles(Function<Kind, Path> roots) {
<add> Assert.notNull(roots, "'roots' must not be null");
<add> Assert.isTrue(Arrays.stream(Kind.values()).map(roots).noneMatch(Objects::isNull),
<add> "'roots' must return a value for all file kinds");
<add> this.roots = roots;
<add> }
<add>
<add>
<add> private static Function<Kind, Path> conventionRoots(Path root) {
<add> Assert.notNull(root, "'root' must not be null");
<add> return kind -> switch (kind) {
<add> case SOURCE -> root.resolve("sources");
<add> case RESOURCE -> root.resolve("resources");
<add> case CLASS -> root.resolve("classes");
<add> };
<add> }
<add>
<add> @Override
<add> public void addFile(Kind kind, String path, InputStreamSource content) {
<add> Assert.notNull(kind, "'kind' must not be null");
<add> Assert.hasLength(path, "'path' must not be empty");
<add> Assert.notNull(content, "'kind' must not be null");
<add> Path root = this.roots.apply(kind).toAbsolutePath().normalize();
<add> Path relativePath = root.resolve(path).toAbsolutePath().normalize();
<add> Assert.isTrue(relativePath.startsWith(root), () -> "'path' must be relative");
<add> try {
<add> try (InputStream inputStream = content.getInputStream()) {
<add> Files.createDirectories(relativePath.getParent());
<add> Files.copy(inputStream, relativePath);
<add> }
<add> }
<add> catch (IOException ex) {
<add> throw new IllegalStateException(ex);
<add> }
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/generate/GeneratedFiles.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import org.springframework.core.io.InputStreamSource;
<add>import org.springframework.javapoet.JavaFile;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<add>import org.springframework.util.function.ThrowingConsumer;
<add>
<add>/**
<add> * Interface that can be used to add {@link Kind#SOURCE source},
<add> * {@link Kind#RESOURCE resource} or {@link Kind#CLASS class} files generated
<add> * during ahead-of-time processing. Source and resource files are written using
<add> * UTF-8 encoding.
<add> *
<add> * @author Phillip Webb
<add> * @author Brian Clozel
<add> * @author Stephane Nicoll
<add> * @since 6.0
<add> * @see InMemoryGeneratedFiles
<add> * @see FileSystemGeneratedFiles
<add> */
<add>public interface GeneratedFiles {
<add>
<add> /**
<add> * Add a generated {@link Kind#SOURCE source file} with content from the
<add> * given {@link JavaFile}.
<add> * @param javaFile the java file to add
<add> */
<add> default void addSourceFile(JavaFile javaFile) {
<add> String className = javaFile.packageName + "." + javaFile.typeSpec.name;
<add> addSourceFile(className, javaFile::writeTo);
<add> }
<add>
<add> /**
<add> * Add a generated {@link Kind#SOURCE source file} with content from the
<add> * given {@link CharSequence}.
<add> * @param className the class name that should be used to determine the path
<add> * of the file
<add> * @param content the contents of the file
<add> */
<add> default void addSourceFile(String className, CharSequence content) {
<add> addSourceFile(className, appendable -> appendable.append(content));
<add> }
<add>
<add> /**
<add> * Add a generated {@link Kind#SOURCE source file} with content written to
<add> * an {@link Appendable} passed to the given {@link ThrowingConsumer}.
<add> * @param className the class name that should be used to determine the path
<add> * of the file
<add> * @param content a {@link ThrowingConsumer} that accepts an
<add> * {@link Appendable} which will receive the file contents
<add> */
<add> default void addSourceFile(String className, ThrowingConsumer<Appendable> content) {
<add> addFile(Kind.SOURCE, getClassNamePath(className), content);
<add> }
<add>
<add> /**
<add> * Add a generated {@link Kind#SOURCE source file} with content from the
<add> * given {@link InputStreamSource}.
<add> * @param className the class name that should be used to determine the path
<add> * of the file
<add> * @param content an {@link InputStreamSource} that will provide an input
<add> * stream containing the file contents
<add> */
<add> default void addSourceFile(String className, InputStreamSource content) {
<add> addFile(Kind.SOURCE, getClassNamePath(className), content);
<add> }
<add>
<add> /**
<add> * Add a generated {@link Kind#RESOURCE resource file} with content from the
<add> * given {@link CharSequence}.
<add> * @param path the relative path of the file
<add> * @param content the contents of the file
<add> */
<add> default void addResourceFile(String path, CharSequence content) {
<add> addResourceFile(path, appendable -> appendable.append(content));
<add> }
<add>
<add> /**
<add> * Add a generated {@link Kind#RESOURCE resource file} with content written
<add> * to an {@link Appendable} passed to the given {@link ThrowingConsumer}.
<add> * @param path the relative path of the file
<add> * @param content a {@link ThrowingConsumer} that accepts an
<add> * {@link Appendable} which will receive the file contents
<add> */
<add> default void addResourceFile(String path, ThrowingConsumer<Appendable> content) {
<add> addFile(Kind.RESOURCE, path, content);
<add> }
<add>
<add> /**
<add> * Add a generated {@link Kind#RESOURCE resource file} with content from the
<add> * given {@link InputStreamSource}.
<add> * @param path the relative path of the file
<add> * @param content an {@link InputStreamSource} that will provide an input
<add> * stream containing the file contents
<add> */
<add> default void addResourceFile(String path, InputStreamSource content) {
<add> addFile(Kind.RESOURCE, path, content);
<add> }
<add>
<add> /**
<add> * Add a generated {@link Kind#CLASS class file} with content from the given
<add> * {@link InputStreamSource}.
<add> * @param path the relative path of the file
<add> * @param content an {@link InputStreamSource} that will provide an input
<add> * stream containing the file contents
<add> */
<add> default void addClassFile(String path, InputStreamSource content) {
<add> addFile(Kind.CLASS, path, content);
<add> }
<add>
<add> /**
<add> * Add a generated file of the specified {@link Kind} with content from the
<add> * given {@link CharSequence}.
<add> * @param kind the kind of file being written
<add> * @param path the relative path of the file
<add> * @param content the contents of the file
<add> */
<add> default void addFile(Kind kind, String path, CharSequence content) {
<add> addFile(kind, path, appendable -> appendable.append(content));
<add> }
<add>
<add> /**
<add> * Add a generated file of the specified {@link Kind} with content written
<add> * to an {@link Appendable} passed to the given {@link ThrowingConsumer}.
<add> * @param kind the kind of file being written
<add> * @param path the relative path of the file
<add> * @param content a {@link ThrowingConsumer} that accepts an
<add> * {@link Appendable} which will receive the file contents
<add> */
<add> default void addFile(Kind kind, String path, ThrowingConsumer<Appendable> content) {
<add> Assert.notNull(content, "'content' must not be null");
<add> addFile(kind, path, new AppendableConsumerInputStreamSource(content));
<add> }
<add>
<add> /**
<add> * Add a generated file of the specified {@link Kind} with content from the
<add> * given {@link InputStreamSource}.
<add> * @param kind the kind of file being written
<add> * @param path the relative path of the file
<add> * @param content an {@link InputStreamSource} that will provide an input
<add> * stream containing the file contents
<add> */
<add> void addFile(Kind kind, String path, InputStreamSource content);
<add>
<add> private static String getClassNamePath(String className) {
<add> Assert.hasLength(className, "'className' must not be empty");
<add> Assert.isTrue(isJavaIdentifier(className),
<add> "'className' must be a valid identifier");
<add> return ClassUtils.convertClassNameToResourcePath(className) + ".java";
<add> }
<add>
<add> private static boolean isJavaIdentifier(String className) {
<add> char[] chars = className.toCharArray();
<add> for (int i = 0; i < chars.length; i++) {
<add> if (i == 0 && !Character.isJavaIdentifierStart(chars[i])) {
<add> return false;
<add> }
<add> if (i > 0 && chars[i] != '.' && !Character.isJavaIdentifierPart(chars[i])) {
<add> return false;
<add> }
<add> }
<add> return true;
<add> }
<add>
<add>
<add> /**
<add> * The various kinds of generated files that are supported.
<add> */
<add> enum Kind {
<add>
<add> /**
<add> * A source file containing Java code that should be compiled.
<add> */
<add> SOURCE,
<add>
<add> /**
<add> * A resource file that should be directly added to final application.
<add> * For example, a {@code .properties} file.
<add> */
<add> RESOURCE,
<add>
<add> /**
<add> * A class file containing bytecode. For example, the result of a proxy
<add> * generated using cglib.
<add> */
<add> CLASS
<add>
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/generate/InMemoryGeneratedFiles.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.io.IOException;
<add>import java.nio.charset.StandardCharsets;
<add>import java.util.Collections;
<add>import java.util.HashMap;
<add>import java.util.LinkedHashMap;
<add>import java.util.Map;
<add>
<add>import org.springframework.core.io.InputStreamSource;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * {@link GeneratedFiles} implementation that keeps generated files in-memory.
<add> *
<add> * @author Phillip Webb
<add> * @since 6.0
<add> */
<add>public class InMemoryGeneratedFiles implements GeneratedFiles {
<add>
<add> private final Map<Kind, Map<String, InputStreamSource>> files = new HashMap<>();
<add>
<add>
<add> @Override
<add> public void addFile(Kind kind, String path, InputStreamSource content) {
<add> Assert.notNull(kind, "'kind' must not be null");
<add> Assert.hasLength(path, "'path' must not be empty");
<add> Assert.notNull(content, "'content' must not be null");
<add> Map<String, InputStreamSource> paths = this.files.computeIfAbsent(kind,
<add> key -> new LinkedHashMap<>());
<add> Assert.state(!paths.containsKey(path),
<add> () -> "Path '" + path + "' already in use");
<add> paths.put(path, content);
<add> }
<add>
<add> /**
<add> * Return a {@link Map} of the generated files of a specific {@link Kind}.
<add> * @param kind the kind of generated file
<add> * @return a {@link Map} of paths to {@link InputStreamSource} instances
<add> */
<add> public Map<String, InputStreamSource> getGeneratedFiles(Kind kind) {
<add> Assert.notNull(kind, "'kind' must not be null");
<add> return Collections
<add> .unmodifiableMap(this.files.getOrDefault(kind, Collections.emptyMap()));
<add> }
<add>
<add> /**
<add> * Return the content of the specified file.
<add> * @param kind the kind of generated file
<add> * @param path the path of the file
<add> * @return the file content or {@code null} if no file could be found
<add> * @throws IOException on read error
<add> */
<add> @Nullable
<add> public String getGeneratedFileContent(Kind kind, String path) throws IOException {
<add> InputStreamSource source = getGeneratedFile(kind, path);
<add> if (source != null) {
<add> return new String(source.getInputStream().readAllBytes(),
<add> StandardCharsets.UTF_8);
<add> }
<add> return null;
<add> }
<add>
<add> /**
<add> * Return the {@link InputStreamSource} of specified file.
<add> * @param kind the kind of generated file
<add> * @param path the path of the file
<add> * @return the file source or {@code null} if no file could be found
<add> */
<add> @Nullable
<add> public InputStreamSource getGeneratedFile(Kind kind, String path) {
<add> Assert.notNull(kind, "'kind' must not be null");
<add> Assert.hasLength(path, "'path' must not be empty");
<add> Map<String, InputStreamSource> paths = this.files.get(kind);
<add> return (paths != null) ? paths.get(path) : null;
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/generate/package-info.java
<add>/**
<add> * Support classes for components that contribute generated code equivalent to a
<add> * runtime behavior.
<add> */
<add>@NonNullApi
<add>@NonNullFields
<add>package org.springframework.aot.generate;
<add>
<add>import org.springframework.lang.NonNullApi;
<add>import org.springframework.lang.NonNullFields;
<ide><path>spring-core/src/test/java/org/springframework/aot/generate/FileSystemGeneratedFilesTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.nio.charset.StandardCharsets;
<add>import java.nio.file.Path;
<add>import java.util.function.Function;
<add>
<add>import org.junit.jupiter.api.Test;
<add>import org.junit.jupiter.api.io.TempDir;
<add>
<add>import org.springframework.aot.generate.GeneratedFiles.Kind;
<add>import org.springframework.core.io.ByteArrayResource;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<add>
<add>/**
<add> * Tests for {@link FileSystemGeneratedFiles}.
<add> *
<add> * @author Phillip Webb
<add> */
<add>class FileSystemGeneratedFilesTests {
<add>
<add> @TempDir
<add> Path root;
<add>
<add> @Test
<add> void addFilesCopiesToFileSystem() {
<add> FileSystemGeneratedFiles generatedFiles = new FileSystemGeneratedFiles(this.root);
<add> generatedFiles.addSourceFile("com.example.Test", "{}");
<add> generatedFiles.addResourceFile("META-INF/test", "test");
<add> generatedFiles.addClassFile("com/example/TestProxy.class",
<add> new ByteArrayResource("!".getBytes(StandardCharsets.UTF_8)));
<add> assertThat(this.root.resolve("sources/com/example/Test.java")).content()
<add> .isEqualTo("{}");
<add> assertThat(this.root.resolve("resources/META-INF/test")).content()
<add> .isEqualTo("test");
<add> assertThat(this.root.resolve("classes/com/example/TestProxy.class")).content()
<add> .isEqualTo("!");
<add> }
<add>
<add> @Test
<add> void addFilesWithCustomRootsCopiesToFileSystem() {
<add> FileSystemGeneratedFiles generatedFiles = new FileSystemGeneratedFiles(
<add> kind -> this.root.resolve("the-" + kind));
<add> generatedFiles.addSourceFile("com.example.Test", "{}");
<add> generatedFiles.addResourceFile("META-INF/test", "test");
<add> generatedFiles.addClassFile("com/example/TestProxy.class",
<add> new ByteArrayResource("!".getBytes(StandardCharsets.UTF_8)));
<add> assertThat(this.root.resolve("the-SOURCE/com/example/Test.java")).content()
<add> .isEqualTo("{}");
<add> assertThat(this.root.resolve("the-RESOURCE/META-INF/test")).content()
<add> .isEqualTo("test");
<add> assertThat(this.root.resolve("the-CLASS/com/example/TestProxy.class")).content()
<add> .isEqualTo("!");
<add> }
<add>
<add> @Test
<add> void createWhenRootIsNullThrowsException() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> new FileSystemGeneratedFiles((Path) null))
<add> .withMessage("'root' must not be null");
<add> }
<add>
<add> @Test
<add> void createWhenRootsIsNullThrowsException() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(
<add> () -> new FileSystemGeneratedFiles((Function<Kind, Path>) null))
<add> .withMessage("'roots' must not be null");
<add> }
<add>
<add> @Test
<add> void createWhenRootsResultsInNullThrowsException() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(
<add> () -> new FileSystemGeneratedFiles(kind -> (kind != Kind.CLASS)
<add> ? this.root.resolve(kind.toString()) : null))
<add> .withMessage("'roots' must return a value for all file kinds");
<add> }
<add>
<add> @Test
<add> void addFileWhenPathIsOutsideOfRootThrowsException() {
<add> FileSystemGeneratedFiles generatedFiles = new FileSystemGeneratedFiles(this.root);
<add> assertPathMustBeRelative(generatedFiles, "/test");
<add> assertPathMustBeRelative(generatedFiles, "../test");
<add> assertPathMustBeRelative(generatedFiles, "test/../../test");
<add> }
<add>
<add> private void assertPathMustBeRelative(FileSystemGeneratedFiles generatedFiles,
<add> String path) {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> generatedFiles.addResourceFile(path, "test"))
<add> .withMessage("'path' must be relative");
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/generate/GeneratedFilesTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.io.ByteArrayOutputStream;
<add>import java.io.IOException;
<add>import java.nio.charset.StandardCharsets;
<add>
<add>import javax.lang.model.element.Modifier;
<add>
<add>import org.assertj.core.api.AbstractStringAssert;
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.aot.generate.GeneratedFiles.Kind;
<add>import org.springframework.core.io.ByteArrayResource;
<add>import org.springframework.core.io.InputStreamSource;
<add>import org.springframework.core.io.Resource;
<add>import org.springframework.javapoet.JavaFile;
<add>import org.springframework.javapoet.MethodSpec;
<add>import org.springframework.javapoet.TypeSpec;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<add>
<add>/**
<add> * Tests for {@link GeneratedFiles}.
<add> *
<add> * @author Phillip Webb
<add> */
<add>class GeneratedFilesTests {
<add>
<add> private final TestGeneratedFiles generatedFiles = new TestGeneratedFiles();
<add>
<add> @Test
<add> void addSourceFileWithJavaFileAddsFile() throws Exception {
<add> MethodSpec main = MethodSpec.methodBuilder("main")
<add> .addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(void.class)
<add> .addParameter(String[].class, "args")
<add> .addStatement("$T.out.println($S)", System.class, "Hello, World!")
<add> .build();
<add> TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
<add> .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addMethod(main).build();
<add> JavaFile javaFile = JavaFile.builder("com.example", helloWorld).build();
<add> this.generatedFiles.addSourceFile(javaFile);
<add> assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java")
<add> .contains("Hello, World!");
<add> }
<add>
<add> @Test
<add> void addSourceFileWithCharSequenceAddsFile() throws Exception {
<add> this.generatedFiles.addSourceFile("com.example.HelloWorld", "{}");
<add> assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java").isEqualTo("{}");
<add> }
<add>
<add> @Test
<add> void addSourceFileWithCharSequenceWhenClassNameIsEmptyThrowsException() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> this.generatedFiles.addSourceFile("", "{}"))
<add> .withMessage("'className' must not be empty");
<add> }
<add>
<add> @Test
<add> void addSourceFileWithCharSequenceWhenClassNameIsInvalidThrowsException() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> this.generatedFiles
<add> .addSourceFile("com/example/HelloWorld.java", "{}"))
<add> .withMessage("'className' must be a valid identifier");
<add> }
<add>
<add> @Test
<add> void addSourceFileWithConsumedAppendableAddsFile() throws Exception {
<add> this.generatedFiles.addSourceFile("com.example.HelloWorld",
<add> appendable -> appendable.append("{}"));
<add> assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java").isEqualTo("{}");
<add> }
<add>
<add> @Test
<add> void addSourceFileWithInputStreamSourceAddsFile() throws Exception {
<add> Resource resource = new ByteArrayResource("{}".getBytes(StandardCharsets.UTF_8));
<add> this.generatedFiles.addSourceFile("com.example.HelloWorld", resource);
<add> assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java").isEqualTo("{}");
<add> }
<add>
<add> @Test
<add> void addResourceFileWithCharSequenceAddsFile() throws Exception {
<add> this.generatedFiles.addResourceFile("META-INF/file", "test");
<add> assertThatFileAdded(Kind.RESOURCE, "META-INF/file").isEqualTo("test");
<add> }
<add>
<add> @Test
<add> void addResourceFileWithConsumedAppendableAddsFile() throws Exception {
<add> this.generatedFiles.addResourceFile("META-INF/file",
<add> appendable -> appendable.append("test"));
<add> assertThatFileAdded(Kind.RESOURCE, "META-INF/file").isEqualTo("test");
<add> }
<add>
<add> @Test
<add> void addResourceFileWithInputStreamSourceAddsFile() throws IOException {
<add> Resource resource = new ByteArrayResource(
<add> "test".getBytes(StandardCharsets.UTF_8));
<add> this.generatedFiles.addResourceFile("META-INF/file", resource);
<add> assertThatFileAdded(Kind.RESOURCE, "META-INF/file").isEqualTo("test");
<add> }
<add>
<add> @Test
<add> void addClassFileWithInputStreamSourceAddsFile() throws IOException {
<add> Resource resource = new ByteArrayResource(
<add> "test".getBytes(StandardCharsets.UTF_8));
<add> this.generatedFiles.addClassFile("com/example/HelloWorld.class", resource);
<add> assertThatFileAdded(Kind.CLASS, "com/example/HelloWorld.class").isEqualTo("test");
<add> }
<add>
<add> @Test
<add> void addFileWithCharSequenceAddsFile() throws Exception {
<add> this.generatedFiles.addFile(Kind.RESOURCE, "META-INF/file", "test");
<add> assertThatFileAdded(Kind.RESOURCE, "META-INF/file").isEqualTo("test");
<add> }
<add>
<add> @Test
<add> void addFileWithConsumedAppendableAddsFile() throws IOException {
<add> this.generatedFiles.addFile(Kind.SOURCE, "com/example/HelloWorld.java",
<add> appendable -> appendable.append("{}"));
<add> assertThatFileAdded(Kind.SOURCE, "com/example/HelloWorld.java").isEqualTo("{}");
<add> }
<add>
<add> private AbstractStringAssert<?> assertThatFileAdded(Kind kind, String path)
<add> throws IOException {
<add> return this.generatedFiles.assertThatFileAdded(kind, path);
<add> }
<add>
<add> static class TestGeneratedFiles implements GeneratedFiles {
<add>
<add> private Kind kind;
<add>
<add> private String path;
<add>
<add> private InputStreamSource content;
<add>
<add> @Override
<add> public void addFile(Kind kind, String path, InputStreamSource content) {
<add> this.kind = kind;
<add> this.path = path;
<add> this.content = content;
<add> }
<add>
<add> AbstractStringAssert<?> assertThatFileAdded(Kind kind, String path)
<add> throws IOException {
<add> assertThat(this.kind).as("kind").isEqualTo(kind);
<add> assertThat(this.path).as("path").isEqualTo(path);
<add> ByteArrayOutputStream out = new ByteArrayOutputStream();
<add> this.content.getInputStream().transferTo(out);
<add> return assertThat(out.toString(StandardCharsets.UTF_8));
<add> }
<add>
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/generate/InMemoryGeneratedFilesTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.aot.generate.GeneratedFiles.Kind;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
<add>
<add>/**
<add> * Tests for {@link InMemoryGeneratedFiles}.
<add> *
<add> * @author Phillip Webb
<add> */
<add>class InMemoryGeneratedFilesTests {
<add>
<add> private final InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles();
<add>
<add> @Test
<add> void addFileAddsInMemoryFile() throws Exception {
<add> this.generatedFiles.addResourceFile("META-INF/test", "test");
<add> assertThat(this.generatedFiles.getGeneratedFileContent(Kind.RESOURCE,
<add> "META-INF/test")).isEqualTo("test");
<add> }
<add>
<add> @Test
<add> void addFileWhenFileAlreadyAddedThrowsException() {
<add> this.generatedFiles.addResourceFile("META-INF/test", "test");
<add> assertThatIllegalStateException().isThrownBy(
<add> () -> this.generatedFiles.addResourceFile("META-INF/test", "test"))
<add> .withMessage("Path 'META-INF/test' already in use");
<add> }
<add>
<add> @Test
<add> void getGeneratedFilesReturnsFiles() throws Exception {
<add> this.generatedFiles.addResourceFile("META-INF/test1", "test1");
<add> this.generatedFiles.addResourceFile("META-INF/test2", "test2");
<add> assertThat(this.generatedFiles.getGeneratedFiles(Kind.RESOURCE))
<add> .containsKeys("META-INF/test1", "META-INF/test2");
<add> }
<add>
<add> @Test
<add> void getGeneratedFileContentWhenFileExistsReturnsContent() throws Exception {
<add> this.generatedFiles.addResourceFile("META-INF/test", "test");
<add> assertThat(this.generatedFiles.getGeneratedFileContent(Kind.RESOURCE,
<add> "META-INF/test")).isEqualTo("test");
<add> }
<add>
<add> @Test
<add> void getGeneratedFileContentWhenFileIsMissingReturnsNull() throws Exception {
<add> this.generatedFiles.addResourceFile("META-INF/test", "test");
<add> assertThat(this.generatedFiles.getGeneratedFileContent(Kind.RESOURCE,
<add> "META-INF/missing")).isNull();
<add> }
<add>
<add> @Test
<add> void getGeneratedFileWhenFileExistsReturnsInputStreamSource() {
<add> this.generatedFiles.addResourceFile("META-INF/test", "test");
<add> assertThat(this.generatedFiles.getGeneratedFile(Kind.RESOURCE, "META-INF/test"))
<add> .isNotNull();
<add> }
<add>
<add> @Test
<add> void getGeneratedFileWhenFileIsMissingReturnsNull() {
<add> this.generatedFiles.addResourceFile("META-INF/test", "test");
<add> assertThat(
<add> this.generatedFiles.getGeneratedFile(Kind.RESOURCE, "META-INF/missing"))
<add> .isNull();
<add> }
<add>
<add>} | 8 |
Ruby | Ruby | use descriptive exception names | 08a92d47b08b25356b8bfea31c91ceb68cfae3ee | <ide><path>activejob/test/cases/exceptions_test.rb
<ide> class ExceptionsTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> test "successfully retry job throwing exception against defaults" do
<del> RetryJob.perform_later 'SeriousError', 5
<add> RetryJob.perform_later 'DefaultsError', 5
<ide>
<ide> assert_equal [
<del> "Raised SeriousError for the 1st time",
<del> "Raised SeriousError for the 2nd time",
<del> "Raised SeriousError for the 3rd time",
<del> "Raised SeriousError for the 4th time",
<add> "Raised DefaultsError for the 1st time",
<add> "Raised DefaultsError for the 2nd time",
<add> "Raised DefaultsError for the 3rd time",
<add> "Raised DefaultsError for the 4th time",
<ide> "Successfully completed job" ], JobBuffer.values
<ide> end
<ide>
<ide> test "successfully retry job throwing exception against higher limit" do
<del> RetryJob.perform_later 'VerySeriousError', 9
<add> RetryJob.perform_later 'ShortWaitTenAttemptsError', 9
<ide> assert_equal 9, JobBuffer.values.count
<ide> end
<ide>
<ide> test "failed retry job when exception kept occurring against defaults" do
<ide> begin
<del> RetryJob.perform_later 'SeriousError', 6
<del> assert_equal "Raised SeriousError for the 5th time", JobBuffer.last_value
<del> rescue SeriousError
<add> RetryJob.perform_later 'DefaultsError', 6
<add> assert_equal "Raised DefaultsError for the 5th time", JobBuffer.last_value
<add> rescue DefaultsError
<ide> pass
<ide> end
<ide> end
<ide>
<ide> test "failed retry job when exception kept occurring against higher limit" do
<ide> begin
<del> RetryJob.perform_later 'VerySeriousError', 11
<del> assert_equal "Raised VerySeriousError for the 10th time", JobBuffer.last_value
<del> rescue VerySeriousError
<add> RetryJob.perform_later 'ShortWaitTenAttemptsError', 11
<add> assert_equal "Raised ShortWaitTenAttemptsError for the 10th time", JobBuffer.last_value
<add> rescue ShortWaitTenAttemptsError
<ide> pass
<ide> end
<ide> end
<ide>
<ide> test "discard job" do
<del> RetryJob.perform_later 'NotSeriousError', 2
<del> assert_equal "Raised NotSeriousError for the 1st time", JobBuffer.last_value
<add> RetryJob.perform_later 'DiscardableError', 2
<add> assert_equal "Raised DiscardableError for the 1st time", JobBuffer.last_value
<ide> end
<ide> end
<ide><path>activejob/test/jobs/retry_job.rb
<ide> require_relative '../support/job_buffer'
<ide> require 'active_support/core_ext/integer/inflections'
<ide>
<del>class SeriousError < StandardError; end
<del>class VerySeriousError < StandardError; end
<del>class NotSeriousError < StandardError; end
<add>class DefaultsError < StandardError; end
<add>class ShortWaitTenAttemptsError < StandardError; end
<add>class DiscardableError < StandardError; end
<ide>
<ide> class RetryJob < ActiveJob::Base
<del> retry_on SeriousError
<del> retry_on VerySeriousError, wait: 1.second, attempts: 10
<del> discard_on NotSeriousError
<add> retry_on DefaultsError
<add> retry_on ShortWaitTenAttemptsError, wait: 1.second, attempts: 10
<add> discard_on DiscardableError
<ide>
<ide> def perform(raising, attempts)
<ide> if executions < attempts | 2 |
Javascript | Javascript | fix some cases where undefined modules are used | 9e4c259cce6301697c7e82c99c23bf0b502f7ecb | <ide><path>lib/dependencies/CommonJsExportRequireDependency.js
<ide> CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependency
<ide> weak: dep.weak,
<ide> runtimeRequirements
<ide> });
<del> const ids = dep.getIds(moduleGraph);
<del> const usedImported = moduleGraph
<del> .getExportsInfo(importedModule)
<del> .getUsedName(ids, runtime);
<del> if (usedImported) {
<del> const comment = equals(usedImported, ids)
<del> ? ""
<del> : Template.toNormalComment(propertyAccess(ids)) + " ";
<del> requireExpr += `${comment}${propertyAccess(usedImported)}`;
<add> if (importedModule) {
<add> const ids = dep.getIds(moduleGraph);
<add> const usedImported = moduleGraph
<add> .getExportsInfo(importedModule)
<add> .getUsedName(ids, runtime);
<add> if (usedImported) {
<add> const comment = equals(usedImported, ids)
<add> ? ""
<add> : Template.toNormalComment(propertyAccess(ids)) + " ";
<add> requireExpr += `${comment}${propertyAccess(usedImported)}`;
<add> }
<ide> }
<ide>
<ide> switch (type) {
<ide><path>lib/dependencies/CommonJsFullRequireDependency.js
<ide> CommonJsFullRequireDependency.Template = class CommonJsFullRequireDependencyTemp
<ide> weak: dep.weak,
<ide> runtimeRequirements
<ide> });
<del> const ids = dep.names;
<del> const usedImported = moduleGraph
<del> .getExportsInfo(importedModule)
<del> .getUsedName(ids, runtime);
<del> if (usedImported) {
<del> const comment = equals(usedImported, ids)
<del> ? ""
<del> : Template.toNormalComment(propertyAccess(ids)) + " ";
<del> requireExpr += `${comment}${propertyAccess(usedImported)}`;
<add> if (importedModule) {
<add> const ids = dep.names;
<add> const usedImported = moduleGraph
<add> .getExportsInfo(importedModule)
<add> .getUsedName(ids, runtime);
<add> if (usedImported) {
<add> const comment = equals(usedImported, ids)
<add> ? ""
<add> : Template.toNormalComment(propertyAccess(ids)) + " ";
<add> requireExpr += `${comment}${propertyAccess(usedImported)}`;
<add> }
<ide> }
<ide> source.replace(dep.range[0], dep.range[1] - 1, requireExpr);
<ide> }
<ide><path>lib/dependencies/HarmonyImportDependency.js
<ide> HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
<ide> }
<ide>
<ide> const importStatement = dep.getImportStatement(false, templateContext);
<del> if (templateContext.moduleGraph.isAsync(referencedModule)) {
<add> if (
<add> referencedModule &&
<add> templateContext.moduleGraph.isAsync(referencedModule)
<add> ) {
<ide> templateContext.initFragments.push(
<ide> new ConditionalInitFragment(
<ide> importStatement[0], | 3 |
Go | Go | take care of some review comments | 15c74bebc1ea2d51612b5809b4477551547a8b3d | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> var (
<ide> DefaultThinpBlockSize uint32 = 128 // 64K = 128 512b sectors
<ide> )
<ide>
<add>const deviceSetMetaFile string = "deviceset-metadata"
<add>
<ide> type DevInfo struct {
<ide> Hash string `json:"-"`
<ide> DeviceId int `json:"device_id"`
<ide> func (devices *DeviceSet) metadataFile(info *DevInfo) string {
<ide> }
<ide>
<ide> func (devices *DeviceSet) deviceSetMetaFile() string {
<del> return path.Join(devices.metadataDir(), "deviceset-metadata")
<add> return path.Join(devices.metadataDir(), deviceSetMetaFile)
<ide> }
<ide>
<ide> func (devices *DeviceSet) oldMetadataFile() string {
<ide> func (devices *DeviceSet) saveMetadata(info *DevInfo) error {
<ide> if err != nil {
<ide> return fmt.Errorf("Error encoding metadata to json: %s", err)
<ide> }
<del> err = devices.writeMetaFile(jsonData, devices.metadataFile(info))
<del> if err != nil {
<add> if err := devices.writeMetaFile(jsonData, devices.metadataFile(info)); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (devices *DeviceSet) ResizePool(size int64) error {
<ide> func (devices *DeviceSet) loadDeviceSetMetaData() error {
<ide> jsonData, err := ioutil.ReadFile(devices.deviceSetMetaFile())
<ide> if err != nil {
<del> return nil
<del> }
<del>
<del> if err := json.Unmarshal(jsonData, devices); err != nil {
<del> return nil
<add> // For backward compatibility return success if file does
<add> // not exist.
<add> if os.IsNotExist(err) {
<add> return nil
<add> }
<add> return err
<ide> }
<ide>
<del> return nil
<add> return json.Unmarshal(jsonData, devices)
<ide> }
<ide>
<ide> func (devices *DeviceSet) saveDeviceSetMetaData() error {
<ide> jsonData, err := json.Marshal(devices)
<del>
<ide> if err != nil {
<ide> return fmt.Errorf("Error encoding metadata to json: %s", err)
<ide> }
<ide>
<del> err = devices.writeMetaFile(jsonData, devices.deviceSetMetaFile())
<del> if err != nil {
<del> return err
<del> }
<del>
<del> return nil
<add> return devices.writeMetaFile(jsonData, devices.deviceSetMetaFile())
<ide> }
<ide>
<ide> func (devices *DeviceSet) initDevmapper(doInit bool) error {
<ide> func (devices *DeviceSet) initDevmapper(doInit bool) error {
<ide>
<ide> // Right now this loads only NextDeviceId. If there is more metatadata
<ide> // down the line, we might have to move it earlier.
<del> devices.loadDeviceSetMetaData()
<add> if err = devices.loadDeviceSetMetaData(); err != nil {
<add> return err
<add> }
<ide>
<ide> // Setup the base image
<ide> if doInit { | 1 |
PHP | PHP | fix failing test | 4574dbc2735bc7967da6c7d731b1a3ab39f3e26e | <ide><path>lib/Cake/Test/Case/I18n/I18nTest.php
<ide> public function testPoNoTranslationNeeded () {
<ide> * @return void
<ide> */
<ide> public function testPoQuotedString () {
<add> Configure::write('Config.language', 'po');
<ide> $expected = 'this is a "quoted string" (translated)';
<ide> $this->assertEquals($expected, __('this is a "quoted string"'));
<ide> } | 1 |
Javascript | Javascript | update selected index after mutation | f1a8bd29235a2e267c88138a618d107cf5d4a9ea | <ide><path>src/devtools/views/Components/TreeContext.js
<ide> function reduceOwnersState(store: Store, state: State, action: Action): State {
<ide> ownerStackIndex = ownerStack.length - 1;
<ide> }
<ide> }
<add> if (selectedElementID !== null) {
<add> // Mutation might have caused the index of this ID to shift.
<add> selectedElementIndex = _ownerFlatTree.indexOf(selectedElementID);
<add> }
<add> } else {
<add> if (selectedElementID !== null) {
<add> // Mutation might have caused the index of this ID to shift.
<add> selectedElementIndex = store.getIndexOfElementID(selectedElementID);
<add> }
<add> }
<add> if (selectedElementIndex === -1) {
<add> // If we couldn't find this ID after mutation, unselect it.
<add> selectedElementIndex = null;
<add> selectedElementID = null;
<ide> }
<ide> break;
<ide> case 'RESET_OWNER_STACK': | 1 |
Python | Python | remove redudandant checks in test_views.py | 4a77211ab8dd33191ed8725e92bccc24812658a0 | <ide><path>tests/www/test_views.py
<ide> def check_content_not_in_response(self, text, resp, resp_code=200):
<ide> else:
<ide> self.assertNotIn(text, resp_html)
<ide>
<del> def percent_encode(self, obj):
<add> @staticmethod
<add> def percent_encode(obj):
<ide> return urllib.parse.quote_plus(str(obj))
<ide>
<ide>
<ide> def tearDown(self):
<ide> def test_can_handle_error_on_decrypt(self):
<ide>
<ide> # create valid variable
<del> resp = self.client.post('/variable/add',
<del> data=self.variable,
<del> follow_redirects=True)
<add> self.client.post('/variable/add', data=self.variable, follow_redirects=True)
<ide>
<ide> # update the variable with a wrong value, given that is encrypted
<ide> Var = models.Variable
<ide> def tearDown(self):
<ide>
<ide> def test_create_pool_with_same_name(self):
<ide> # create test pool
<del> resp = self.client.post('/pool/add',
<del> data=self.pool,
<del> follow_redirects=True)
<add> resp = self.client.post('/pool/add', data=self.pool, follow_redirects=True)
<ide> self.check_content_in_response('Added Row', resp)
<ide>
<ide> # create pool with the same name
<del> resp = self.client.post('/pool/add',
<del> data=self.pool,
<del> follow_redirects=True)
<add> resp = self.client.post('/pool/add', data=self.pool, follow_redirects=True)
<ide> self.check_content_in_response('Already exists.', resp)
<ide>
<ide> def test_create_pool_with_empty_name(self):
<ide>
<ide> self.pool['pool'] = ''
<del> resp = self.client.post('/pool/add',
<del> data=self.pool,
<del> follow_redirects=True)
<add> resp = self.client.post('/pool/add', data=self.pool, follow_redirects=True)
<ide> self.check_content_in_response('This field is required.', resp)
<ide>
<ide> def test_odd_name(self):
<ide> def test_home_filter_tags(self):
<ide> self.assertEqual('example,data', flask_session[FILTER_TAGS_COOKIE])
<ide>
<ide> self.client.get('home?reset_tags', follow_redirects=True)
<del> self.assertEqual(None, flask_session[FILTER_TAGS_COOKIE])
<add> self.assertIsNone(flask_session[FILTER_TAGS_COOKIE])
<ide>
<ide> def test_home_status_filter_cookie(self):
<ide> from airflow.www.views import FILTER_STATUS_COOKIE
<ide> def test_run_with_runnable_states(self, get_default_executor_function):
<ide> )
<ide> resp = self.client.post('run', data=form, follow_redirects=True)
<ide>
<del> self.check_content_in_response('', resp, resp_code=200)
<add> self.check_content_in_response('', resp)
<ide>
<ide> msg = "Task is in the '{}' state which is not a valid state for execution. " \
<ide> .format(state) + "The task must be cleared in order to be run"
<ide> def test_run_with_not_runnable_states(self, get_default_executor_function):
<ide> )
<ide> resp = self.client.post('run', data=form, follow_redirects=True)
<ide>
<del> self.check_content_in_response('', resp, resp_code=200)
<add> self.check_content_in_response('', resp)
<ide>
<ide> msg = "Task is in the '{}' state which is not a valid state for execution. " \
<ide> .format(state) + "The task must be cleared in order to be run"
<ide> def test_gantt_failure(self):
<ide> self.check_content_not_in_response('example_bash_operator', resp)
<ide>
<ide> def test_success_fail_for_read_only_role(self):
<del> # succcess endpoint need can_dag_edit, which read only role can not access
<add> # success endpoint need can_dag_edit, which read only role can not access
<ide> self.logout()
<ide> self.login(username='dag_read_only',
<ide> password='dag_read_only')
<ide> def test_trigger_dag_conf_malformed(self):
<ide>
<ide> def test_trigger_dag_form(self):
<ide> test_dag_id = "example_bash_operator"
<del>
<ide> resp = self.client.get('trigger?dag_id={}'.format(test_dag_id))
<del>
<del> self.assertEqual(resp.status_code, 200)
<ide> self.check_content_in_response('Trigger DAG: {}'.format(test_dag_id), resp)
<ide>
<ide> @parameterized.expand([ | 1 |
Javascript | Javascript | eliminate redundant object creation | 43cd006f03b87fe479110e1f0bbc1edb24623538 | <ide><path>src/math/Box3.js
<ide> function Box3( min, max ) {
<ide>
<ide> }
<ide>
<add>var _box = new Box3();
<add>
<ide> Object.assign( Box3.prototype, {
<ide>
<ide> isBox3: true,
<ide> Object.assign( Box3.prototype, {
<ide>
<ide> }
<ide>
<del> var box = new Box3();
<del>
<del> box.copy( geometry.boundingBox );
<del> box.applyMatrix4( object.matrixWorld );
<add> _box.copy( geometry.boundingBox );
<add> _box.applyMatrix4( object.matrixWorld );
<ide>
<del> this.expandByPoint( box.min );
<del> this.expandByPoint( box.max );
<add> this.expandByPoint( _box.min );
<add> this.expandByPoint( _box.max );
<ide>
<ide> }
<ide> | 1 |
Javascript | Javascript | report better errors for uglify-js | a395c07c5de840713b82af5bcd081c57c4f202e5 | <ide><path>lib/optimize/UglifyJsPlugin.js
<ide> UglifyJsPlugin.prototype.apply = function(compiler) {
<ide> compilation.warnings.push(new Error(file + " from UglifyJs\n" + warnings.join("\n")));
<ide> }
<ide> } catch(err) {
<del> err.file = file;
<del> compilation.errors.push(err);
<add> if(err.line) {
<add> var original = sourceMap.originalPositionFor({
<add> line: err.line,
<add> column: err.col
<add> });
<add> if(original && original.source) {
<add> compilation.errors.push(new Error(file + " from UglifyJs\n" + err.message + " [" + requestShortener.shorten(original.source) + ":" + original.line + "," + original.column + "]"));
<add> } else {
<add> compilation.errors.push(new Error(file + " from UglifyJs\n" + err.message + " [" + file + ":" + err.line + "," + err.col + "]"));
<add> }
<add> } else
<add> compilation.errors.push(new Error(file + " from UglifyJs\n" + err.message));
<ide> } finally {
<ide> uglify.AST_Node.warn_function = oldWarnFunction;
<ide> } | 1 |
Go | Go | add tests for bufreader | 028f7987fe455d958d08db98ae267d9fd4cf3813 | <ide><path>pkg/ioutils/readers_test.go
<ide> func TestBufReader(t *testing.T) {
<ide> t.Error(string(output))
<ide> }
<ide> }
<add>
<add>type repeatedReader struct {
<add> readCount int
<add> maxReads int
<add> data []byte
<add>}
<add>
<add>func newRepeatedReader(max int, data []byte) *repeatedReader {
<add> return &repeatedReader{0, max, data}
<add>}
<add>
<add>func (r *repeatedReader) Read(p []byte) (int, error) {
<add> if r.readCount >= r.maxReads {
<add> return 0, io.EOF
<add> }
<add> r.readCount++
<add> n := copy(p, r.data)
<add> return n, nil
<add>}
<add>
<add>func testWithData(data []byte, reads int) {
<add> reader := newRepeatedReader(reads, data)
<add> bufReader := NewBufReader(reader)
<add> io.Copy(ioutil.Discard, bufReader)
<add>}
<add>
<add>func Benchmark1M10BytesReads(b *testing.B) {
<add> reads := 1000000
<add> readSize := int64(10)
<add> data := make([]byte, readSize)
<add> b.SetBytes(readSize * int64(reads))
<add> b.ResetTimer()
<add> for i := 0; i < b.N; i++ {
<add> testWithData(data, reads)
<add> }
<add>}
<add>
<add>func Benchmark1M1024BytesReads(b *testing.B) {
<add> reads := 1000000
<add> readSize := int64(1024)
<add> data := make([]byte, readSize)
<add> b.SetBytes(readSize * int64(reads))
<add> b.ResetTimer()
<add> for i := 0; i < b.N; i++ {
<add> testWithData(data, reads)
<add> }
<add>}
<add>
<add>func Benchmark10k32KBytesReads(b *testing.B) {
<add> reads := 10000
<add> readSize := int64(32 * 1024)
<add> data := make([]byte, readSize)
<add> b.SetBytes(readSize * int64(reads))
<add> b.ResetTimer()
<add> for i := 0; i < b.N; i++ {
<add> testWithData(data, reads)
<add> }
<add>} | 1 |
Text | Text | add note about asyncresource for worker pooling | 55de20999b8b60a7ef889ea0d9573e9f271e1d17 | <ide><path>doc/api/worker_threads.md
<ide> The above example spawns a Worker thread for each `parse()` call. In actual
<ide> practice, use a pool of Workers instead for these kinds of tasks. Otherwise, the
<ide> overhead of creating Workers would likely exceed their benefit.
<ide>
<add>When implementing a worker pool, use the [`AsyncResource`][] API to inform
<add>diagnostic tools (e.g. in order to provide asynchronous stack traces) about the
<add>correlation between tasks and their outcomes.
<add>
<ide> ## worker.isMainThread
<ide> <!-- YAML
<ide> added: v10.5.0
<ide> active handle in the event system. If the worker is already `unref()`ed calling
<ide> `unref()` again will have no effect.
<ide>
<ide> [`'close'` event]: #worker_threads_event_close
<add>[`AsyncResource`]: async_hooks.html#async_hooks_class_asyncresource
<ide> [`Buffer`]: buffer.html
<ide> [`EventEmitter`]: events.html
<ide> [`EventTarget`]: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget | 1 |
Ruby | Ruby | add indifferent access to the attributes | 8377646d68b32de362fefad0d752a923f6b36da6 | <ide><path>activeresource/lib/active_resource/base.rb
<ide> require 'active_support'
<ide> require 'active_support/core_ext/class/attribute_accessors'
<ide> require 'active_support/core_ext/class/inheritable_attributes'
<add>require 'active_support/core_ext/hash/indifferent_access'
<ide> require 'active_support/core_ext/kernel/reporting'
<ide> require 'active_support/core_ext/module/attr_accessor_with_default'
<ide> require 'active_support/core_ext/module/delegation'
<ide> def split_options(options = {})
<ide> # my_other_course = Course.new(:name => "Philosophy: Reason and Being", :lecturer => "Ralph Cling")
<ide> # my_other_course.save
<ide> def initialize(attributes = {})
<del> @attributes = {}
<add> @attributes = {}.with_indifferent_access
<ide> @prefix_options = {}
<ide> load(attributes)
<ide> end
<ide><path>activeresource/test/cases/base/load_test.rb
<ide> def test_load_simple_hash
<ide> assert_equal @matz.stringify_keys, @person.load(@matz).attributes
<ide> end
<ide>
<add> def test_after_load_attributes_are_accessible
<add> assert_equal Hash.new, @person.attributes
<add> assert_equal @matz.stringify_keys, @person.load(@matz).attributes
<add> assert_equal @matz[:name], @person.attributes['name']
<add> end
<add>
<add> def test_after_load_attributes_are_accessible_via_indifferent_access
<add> assert_equal Hash.new, @person.attributes
<add> assert_equal @matz.stringify_keys, @person.load(@matz).attributes
<add> assert_equal @matz[:name], @person.attributes['name']
<add> assert_equal @matz[:name], @person.attributes[:name]
<add> end
<add>
<ide> def test_load_one_with_existing_resource
<ide> address = @person.load(:street_address => @first_address).street_address
<ide> assert_kind_of StreetAddress, address
<ide><path>activeresource/test/cases/base_test.rb
<ide> def setup
<ide> Person.password = nil
<ide> end
<ide>
<add> ########################################################################
<add> # Tests relating to setting up the API-connection configuration
<add> ########################################################################
<ide>
<ide> def test_site_accessor_accepts_uri_or_string_argument
<ide> site = URI.parse('http://localhost')
<ide> def test_updating_baseclass_timeout_wipes_descendent_cached_connection_objects
<ide> assert_not_equal(first_connection, second_connection, 'Connection should be re-created')
<ide> end
<ide>
<add>
<add> ########################################################################
<add> # Tests for setting up remote URLs for a given model (including adding
<add> # parameters appropriately)
<add> ########################################################################
<ide> def test_collection_name
<ide> assert_equal "people", Person.collection_name
<ide> end
<ide> def test_custom_prefix
<ide> assert_equal [:person_id].to_set, StreetAddress.__send__(:prefix_parameters)
<ide> end
<ide>
<add>
<add> ########################################################################
<add> # Tests basic CRUD functions (find/save/create etc)
<add> ########################################################################
<ide> def test_respond_to
<ide> matz = Person.find(1)
<ide> assert matz.respond_to?(:name)
<ide> def test_delete_with_410_gone
<ide> assert_raise(ActiveResource::ResourceGone) { Person.find(1) }
<ide> end
<ide>
<add> ########################################################################
<add> # Tests the more miscelaneous helper methods
<add> ########################################################################
<ide> def test_exists
<ide> # Class method.
<ide> assert !Person.exists?(nil) | 3 |
Go | Go | modify log in order to be same below | fe8bcb1a8e5ab0426822d512df97eebed268dfc4 | <ide><path>volume/store/store.go
<ide> func (s *VolumeStore) Purge(name string) {
<ide> s.globalLock.Lock()
<ide> v, exists := s.names[name]
<ide> if exists {
<del> if _, err := volumedrivers.ReleaseDriver(v.DriverName()); err != nil {
<del> logrus.Errorf("Error dereferencing volume driver: %v", err)
<add> driverName := v.DriverName()
<add> if _, err := volumedrivers.ReleaseDriver(driverName); err != nil {
<add> logrus.WithError(err).WithField("driver", driverName).Error("Error releasing reference to volume driver")
<ide> }
<ide> }
<ide> if err := s.removeMeta(name); err != nil { | 1 |
Javascript | Javascript | provide default methods for assert | 3c4c0db26abba8211c0e6d42c14f14b3514b481b | <ide><path>benchmark/assert/deepequal-buffer.js
<ide> function main(conf) {
<ide> data.copy(expectedWrong);
<ide>
<ide> switch (conf.method) {
<add> case '':
<add> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual':
<ide> bench.start();
<ide> for (i = 0; i < n; ++i) {
<ide><path>benchmark/assert/deepequal-map.js
<ide> function main(conf) {
<ide> var values, values2;
<ide>
<ide> switch (conf.method) {
<add> case '':
<add> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual_primitiveOnly':
<ide> values = array.map((_, i) => [`str_${i}`, 123]);
<ide> benchmark(assert.deepEqual, n, values);
<ide><path>benchmark/assert/deepequal-object.js
<ide> function main(conf) {
<ide> const expectedWrong = createObj(source, '4');
<ide>
<ide> switch (conf.method) {
<add> case '':
<add> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual':
<ide> bench.start();
<ide> for (i = 0; i < n; ++i) {
<ide><path>benchmark/assert/deepequal-prims-and-objs-big-array-set.js
<ide> function main(conf) {
<ide> const expectedWrongSet = new Set(expectedWrong);
<ide>
<ide> switch (conf.method) {
<add> case '':
<add> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual_Array':
<ide> bench.start();
<ide> for (i = 0; i < n; ++i) {
<ide><path>benchmark/assert/deepequal-prims-and-objs-big-loop.js
<ide> function main(conf) {
<ide>
<ide> // Creates new array to avoid loop invariant code motion
<ide> switch (conf.method) {
<add> case '':
<add> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual':
<ide> bench.start();
<ide> for (i = 0; i < n; ++i) {
<ide><path>benchmark/assert/deepequal-set.js
<ide> function main(conf) {
<ide> var values, values2;
<ide>
<ide> switch (conf.method) {
<add> case '':
<add> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual_primitiveOnly':
<ide> values = array.map((_, i) => `str_${i}`);
<ide> benchmark(assert.deepEqual, n, values);
<ide><path>benchmark/assert/deepequal-typedarrays.js
<ide> function main(conf) {
<ide> var i;
<ide>
<ide> switch (conf.method) {
<add> case '':
<add> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual':
<ide> bench.start();
<ide> for (i = 0; i < n; ++i) {
<ide><path>benchmark/assert/throws.js
<ide> function main(conf) {
<ide> var i;
<ide>
<ide> switch (conf.method) {
<add> case '':
<add> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'doesNotThrow':
<ide> bench.start();
<ide> for (i = 0; i < n; ++i) { | 8 |
Mixed | Javascript | improve function signature of util._extend | b3e7ac2605c18c041293cd3ab892c963e1145176 | <ide><path>doc/api/util.md
<ide> deprecated: v0.11.3
<ide>
<ide> Deprecated predecessor of `console.log`.
<ide>
<del>### util.\_extend(obj)
<add>### util.\_extend(target, source)
<ide> <!-- YAML
<ide> added: v0.7.5
<ide> deprecated: v6.0.0
<ide><path>lib/util.js
<ide> exports.inherits = function(ctor, superCtor) {
<ide> Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
<ide> };
<ide>
<del>exports._extend = function(origin, add) {
<del> // Don't do anything if add isn't an object
<del> if (add === null || typeof add !== 'object') return origin;
<add>exports._extend = function(target, source) {
<add> // Don't do anything if source isn't an object
<add> if (source === null || typeof source !== 'object') return target;
<ide>
<del> var keys = Object.keys(add);
<add> var keys = Object.keys(source);
<ide> var i = keys.length;
<ide> while (i--) {
<del> origin[keys[i]] = add[keys[i]];
<add> target[keys[i]] = source[keys[i]];
<ide> }
<del> return origin;
<add> return target;
<ide> };
<ide>
<ide> function hasOwnProperty(obj, prop) { | 2 |
Text | Text | update the redux flow.md | 7b34e44ad104c651d134bea4a4f9c94e243cea16 | <ide><path>docs/Basics/The Redux Flow.md
<ide> The Redux Flow
<ide> --------------------------
<ide>
<del>TODO
<add>Redux implements an architecture with unidirectional data flow. What does this mean? It means that **every change to the data follows the same lifecycle and goes into a single direction in a centralized fashion.** If you’re used to “fat models” or “active records” like Backbone, this may sound weird, but unidirectional data flow makes your apps much more predictable. It also encourages data normalization, so you don’t end up with independent copies of the same state that are unaware of each other. If this sounds unconvincing, read [The Case for Flux](https://medium.com/@dan_abramov/the-case-for-flux-379b7d1982c6) for a compelling argument for unidirectional data flow. Althought [Redux is not exactly Flux](./Relation to Other Libraries.md), it shares the same key benefits.
<add>
<add>Here is how any change in a Redux app happens:
<add>
<add>1. You call `store.dispatch(action)`. An `action` is just a plain object describing “what happened”. For example, `{ type: 'LIKE_ARTICLE', articleId: 42 }`, `{ type: 'USER_FETCHED', response: ... }`, or `{ type: 'ADD_TODO', text: 'Use Redux' }`. Actions are like newspapers, reporting anything that may result in changing the state of your app. You can call `store.dispatch(action)` from your components, XHR callbacks, scheduled intervals, or anywhere else.
<add>2. The Redux store will call the [reducer function](../Reference/Glossary.md#reducer) you gave it. It will pass the current state tree as the first argument, and the action as the second one. For example, your root reducer may receive `{ todos: ['Read docs'] }` as `state` and `{ type: 'ADD_TODO', text: 'Understand the flow' }` as `action`.
<add>3. Now, how you structure your root reducer function is completely up to you. However, Redux ships with `combineReducers` helper which is useful for “splitting” the root reducer into several separate reducer functions that each manage a slice of the state tree. Let’s imagine your passed `combineReducers({ todos: todos })` as your root reducer, where `todos` is a reducer function you wrote, and that just manages the `todos` array. The way `combineReducers` works is that, given `{ a: someFunction, b: someOtherFunction }` as its arguments, it will call `someFunction` with `state.a`, `someOtherFunction` with `state.b`, and combine their results into the new root `state`. In our example, it will pass `state.todos` as `state` to your `todos` reducer, and assemble the next root state with the same `{ todos: Array }` shape. The `todos` reducer might get `['Read docs']` as the current state, and return `['Read docs', 'Understand the flow']` as the next state. The reducer returned by `combineReducers` will then return `{ todos: ['Read docs', 'Understand the flow'] }` as the next root state. While `combineReducers` is a handy helper, you don’t have to use it, and you can write your own root reducer just fine.
<add>4. The Redux store saves the next state tree returned by the reducer. This is now the next state of your app! It will invoke every listener registered with `store.subscribe(listener)`. The listeners may call `store.getState()` to read the current state. This is where you can update your UI using the new state. If you use bindings like [React Redux](https://github.com/gaearon/react-redux), that’s exactly where they schedule a `component.setState()` call.
<add>
<add>This is all there is to it.
<add>
<add>One important addition is that, if you use any middleware on the store, it wraps the store’s `dispatch` function and may add support for dispatching promises, [thunks](https://github.com/gaearon/redux-thunk) or other potentially asynchronous [intermediate actions](../Reference/Glossary.md#intermediate-action). In the end, after being processed with middleware, they all become “raw” plain objects, which your reducer function will receive.
<ide>
<ide> --------------------------
<ide> Next: [Userland and Core](Userland and Core.md) | 1 |
PHP | PHP | reduce code repetition | d534013570373e01e76be9668420e451c71be570 | <ide><path>lib/Cake/Utility/Set.php
<ide> public static function nest($data, $options = array()) {
<ide> foreach ($data as $result) {
<ide> $result[$options['children']] = array();
<ide>
<del> $id = $result;
<del> foreach($idKeys as $key) {
<del> $id = $id[$key];
<del> }
<del>
<del> $parentId = $result;
<del> foreach($parentKeys as $key) {
<del> if (!isset($parentId[$key])) {
<del> break;
<del> }
<del> $parentId = $parentId[$key];
<del> }
<del> if (!is_scalar($parentId)) {
<del> $parentId = null;
<del> }
<add> $id = Set::getValue($result, $idKeys);
<add> $parentId = Set::getValue($result, $parentKeys);
<ide>
<ide> if (isset($idMap[$id][$options['children']])) {
<ide> $idMap[$id] = array_merge($result, (array)$idMap[$id]);
<ide> public static function nest($data, $options = array()) {
<ide> }
<ide> }
<ide>
<del> $root = $return[0];
<del> foreach($parentKeys as $key) {
<del> if (!isset($root[$key])) {
<del> break;
<del> }
<del> $root = $root[$key];
<del> }
<del> if (!is_scalar($root)) {
<del> $root = null;
<del> }
<add> $root = Set::getValue($return[0], $parentKeys);
<ide>
<ide> foreach ($return as $i => $result) {
<del>
<del> $parentId = $result;
<del> foreach($parentKeys as $key) {
<del> if (!isset($parentId[$key])) {
<del> break;
<del> }
<del> $parentId = $parentId[$key];
<del> }
<del> if (!is_scalar($parentId)) {
<del> $parentId = null;
<del> }
<del>
<add> $parentId = Set::getValue($result, $parentKeys);
<ide> if ($parentId != $root) {
<ide> unset($return[$i]);
<ide> }
<ide> }
<ide>
<ide> return $return;
<ide> }
<add>
<add>/**
<add> * A slimmed down set extract
<add> *
<add> * @param mixed $input an array
<add> * @param mixed $path string or array of array keys
<add> * @return the value at the specified position or null if it doesn't exist
<add> */
<add> protected static function getValue($input, $path) {
<add> if (is_string($path)) {
<add> $keys = explode('/', trim($path, '/'));
<add> } else {
<add> $keys = $path;
<add> }
<add>
<add> $return = $input;
<add> foreach($keys as $key) {
<add> if (!isset($return[$key])) {
<add> return null;
<add> }
<add> $return = $return[$key];
<add> }
<add> return $return;
<add> }
<ide> } | 1 |
Javascript | Javascript | make transferpropsto() message easier to debug | ef60eee57ab8a86e47847761532cf72a1205b668 | <ide><path>src/core/ReactPropTransferer.js
<ide> var ReactPropTransferer = {
<ide> transferPropsTo: function(component) {
<ide> invariant(
<ide> component.props.__owner__ === this,
<del> 'You can\'t call transferPropsTo() on a component that you don\'t ' +
<del> 'own. This usually means you are calling transferPropsTo() on a ' +
<del> 'component passed in as props or children.'
<add> '%s: You can\'t call transferPropsTo() on a component that you ' +
<add> 'don\'t own, %s. This usually means you are calling ' +
<add> 'transferPropsTo() on a component passed in as props or children.',
<add> this.constructor.displayName,
<add> component.constructor.displayName
<ide> );
<ide>
<ide> var props = {};
<ide><path>src/core/__tests__/ReactPropTransferer-test.js
<ide> describe('ReactPropTransferer', function() {
<ide> ReactTestUtils.renderIntoDocument(<Parent />);
<ide> }).toThrow(
<ide> 'Invariant Violation: ' +
<del> 'You can\'t call transferPropsTo() on a component that you don\'t own. ' +
<add> 'Child: You can\'t call transferPropsTo() on a component that you ' +
<add> 'don\'t own, span. ' +
<ide> 'This usually means you are calling transferPropsTo() on a component ' +
<ide> 'passed in as props or children.'
<ide> ); | 2 |
Javascript | Javascript | use jsx in the new tests | 98a7100930d4a877cc1d88b9b1ea410271ee9ea9 | <ide><path>src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> it('should update known hyphenated attributes for SVG tags', function() {
<ide> var container = document.createElement('div');
<ide>
<del> var beforeUpdate = React.createElement('svg', {}, null);
<add> var beforeUpdate = <svg />;
<ide> ReactDOM.render(beforeUpdate, container);
<ide>
<ide> var afterUpdate = <svg clip-path="url(#starlet)" />;
<ide> describe('ReactDOMComponent', function() {
<ide> it('should update camel case attributes for SVG tags', function() {
<ide> var container = document.createElement('div');
<ide>
<del> var beforeUpdate = React.createElement('svg', {}, null);
<add> var beforeUpdate = <svg />;
<ide> ReactDOM.render(beforeUpdate, container);
<ide>
<ide> var afterUpdate = <svg viewBox="0 0 100 100" />;
<ide> describe('ReactDOMComponent', function() {
<ide> spyOn(console, 'error');
<ide> var container = document.createElement('div');
<ide>
<del> var beforeUpdate = React.createElement('svg', {}, null);
<add> var beforeUpdate = <svg />;
<ide> ReactDOM.render(beforeUpdate, container);
<ide>
<ide> var afterUpdate = <svg clipPath="url(#starlet)" />;
<ide> describe('ReactDOMComponent', function() {
<ide> it('should update arbitrary hyphenated attributes for SVG tags', function() {
<ide> var container = document.createElement('div');
<ide>
<del> var beforeUpdate = React.createElement('svg', {}, null);
<add> var beforeUpdate = <svg />;
<ide> ReactDOM.render(beforeUpdate, container);
<ide>
<ide> var afterUpdate = <svg the-word="the-bird" />;
<ide> describe('ReactDOMComponent', function() {
<ide> it('should update arbitrary camel case attributes for SVG tags', function() {
<ide> var container = document.createElement('div');
<ide>
<del> var beforeUpdate = React.createElement('svg', {}, null);
<add> var beforeUpdate = <svg />;
<ide> ReactDOM.render(beforeUpdate, container);
<ide>
<ide> var afterUpdate = <svg theWord="theBird" />; | 1 |
Python | Python | add a test for masked array creations | 7c24bd4c36c2793238305f3043c7a71cd89c455f | <ide><path>benchmarks/benchmarks/bench_ma.py
<ide> def time_masked_array_l100(self):
<ide> def time_masked_array_l100_t100(self):
<ide> np.ma.masked_array(self.l100, self.t100)
<ide>
<add>class MACreation(Benchmark):
<add> param_names = ['data', 'mask']
<add> params = [[10, 100, 1000],
<add> [True, False, None]]
<add>
<add> def time_ma_creations(self, data, mask):
<add> np.ma.array(data=np.zeros(int(data)), mask=mask)
<add>
<ide>
<ide> class Indexing(Benchmark):
<ide> param_names = ['masked', 'ndim', 'size'] | 1 |
PHP | PHP | ensure queues are only suffixed once | ec7d5b8ce77009757c04cbdc0f0c8bc81b277dbc | <ide><path>src/Illuminate/Queue/SqsQueue.php
<ide> use Aws\Sqs\SqsClient;
<ide> use Illuminate\Contracts\Queue\Queue as QueueContract;
<ide> use Illuminate\Queue\Jobs\SqsJob;
<add>use Illuminate\Support\Str;
<ide>
<ide> class SqsQueue extends Queue implements QueueContract
<ide> {
<ide> public function getQueue($queue)
<ide> $queue = $queue ?: $this->default;
<ide>
<ide> return filter_var($queue, FILTER_VALIDATE_URL) === false
<del> ? rtrim($this->prefix, '/').'/'.$queue.$this->suffix
<add> ? rtrim($this->prefix, '/').'/'.Str::finish($queue, $this->suffix)
<ide> : $queue;
<ide> }
<ide>
<ide><path>tests/Queue/QueueSqsQueueTest.php
<ide> public function testGetQueueProperlyResolvesUrlWithSuffix()
<ide> $queueUrl = $this->baseUrl.'/'.$this->account.'/test'.$suffix;
<ide> $this->assertEquals($queueUrl, $queue->getQueue('test'));
<ide> }
<add>
<add> public function testGetQueueEnsuresTheQueueIsOnlySuffixedOnce()
<add> {
<add> $queue = new SqsQueue($this->sqs, "{$this->queueName}-staging", $this->prefix, $suffix = '-staging');
<add> $this->assertEquals($this->queueUrl.$suffix, $queue->getQueue(null));
<add> $queueUrl = $this->baseUrl.'/'.$this->account.'/test'.$suffix;
<add> $this->assertEquals($queueUrl, $queue->getQueue('test-staging'));
<add> }
<ide> } | 2 |
Text | Text | fix typo in index.md | 7f63288b8656da64468162a48fcf36389894f2e1 | <ide><path>guide/english/mathematics/area-of-a-trapezium/index.md
<ide> title: Area of a Trapezium
<ide> ---
<ide> ## Area of a Trapezium
<ide>
<del>Area of a Trapezium is defined by the 2D space enclosed by the Trapezium. A trapezium is a Quadrilateral by 2 oposite parallel sides of equal or unequal length and 2 opposite non parallel sides of equal or unequal length.
<add>Area of a Trapezium is defined by the 2D space enclosed by the Trapezium. A trapezium is a Quadrilateral by 2 opposite parallel sides of equal or unequal length and 2 opposite non parallel sides of equal or unequal length.
<ide>
<ide> Let the parallel sides be represented by 'a' and 'b' and the perpendicular distance between these parallel sides be 'h'
<ide> then | 1 |
Python | Python | fix _update_memory fn call in transformer-xl | ee60840ee6e6c099b913da71464eebe169704637 | <ide><path>src/transformers/modeling_transfo_xl.py
<ide> def init_mems(self, bsz):
<ide> else:
<ide> return None
<ide>
<del> def _update_mems(self, hids, mems, qlen, mlen):
<add> def _update_mems(self, hids, mems, mlen, qlen):
<ide> # does not deal with None
<ide> if mems is None:
<ide> return None | 1 |
Javascript | Javascript | protect safari 5.1 from csp | dc9b009c1325e05344fa2216fac71fac3a0a0590 | <ide><path>test/unit/support.js
<ide> testIframeWithCallback( "box-sizing does not affect jQuery.support.shrinkWrapBlo
<ide> strictEqual( shrinkWrapBlocks, jQuery.support.shrinkWrapBlocks, "jQuery.support.shrinkWrapBlocks properties are the same" );
<ide> });
<ide>
<del>testIframeWithCallback( "Check CSP (https://developer.mozilla.org/en-US/docs/Security/CSP) restrictions", "support/csp.php", function( support ) {
<del> expect( 1 );
<del> deepEqual( jQuery.extend( {}, support ), jQuery.support, "No violations of CSP polices" );
<del>});
<add>// Support: Safari 5.1
<add>// Shameless browser-sniff, but Safari 5.1 mishandles CSP
<add>if ( !( typeof navigator !== "undefined" &&
<add> (/ AppleWebKit\/\d.*? Version\/(\d+)/.exec(navigator.userAgent) || [])[1] < 6 ) ) {
<add>
<add> testIframeWithCallback( "Check CSP (https://developer.mozilla.org/en-US/docs/Security/CSP) restrictions", "support/csp.php", function( support ) {
<add> expect( 1 );
<add> deepEqual( jQuery.extend( {}, support ), jQuery.support, "No violations of CSP polices" );
<add> });
<add>} | 1 |
Text | Text | add src/crypto to cc list for nodejs/crypto | 0ef81d120d02a17ab443370f34e7ca2d19323770 | <ide><path>doc/contributing/collaborator-guide.md
<ide> might impact an LTS release.
<ide> | `lib/zlib` | @nodejs/zlib |
<ide> | `src/async_wrap.*` | @nodejs/async\_hooks |
<ide> | `src/node_api.*` | @nodejs/node-api |
<del>| `src/node_crypto.*` | @nodejs/crypto |
<add>| `src/node_crypto.*`, `src/crypto` | @nodejs/crypto |
<ide> | `test/*` | @nodejs/testing |
<ide> | `tools/node_modules/eslint`, `.eslintrc` | @nodejs/linting |
<ide> | build | @nodejs/build | | 1 |
PHP | PHP | fix exception message in reducespread | 91824b0833912ddee194f8fb722b74ab0dc57803 | <ide><path>src/Illuminate/Collections/Traits/EnumeratesValues.php
<ide> public function reduceSpread(callable $callback, ...$initial)
<ide>
<ide> if (! is_array($result)) {
<ide> throw new UnexpectedValueException(sprintf(
<del> "%s::reduceMany expects reducer to return an array, but got a '%s' instead.",
<add> "%s::reduceSpread expects reducer to return an array, but got a '%s' instead.",
<ide> class_basename(static::class), gettype($result)
<ide> ));
<ide> } | 1 |
Javascript | Javascript | create uid instead of displayname | 2d8959d99cf3b55145006f42d9bced2780fb6aa2 | <ide><path>client/next.js
<ide> const Component = evalScript(component).default
<ide>
<ide> const router = new Router({ Component, props })
<ide> const container = document.getElementById('__next')
<del>const appProps = { Component, props, router: {} }
<add>const appProps = { Component, props, router }
<ide>
<ide> render(createElement(App, { ...appProps }), container)
<ide><path>client/router.js
<ide> export default class Router {
<ide> constructor (initialData) {
<ide> this.subscriptions = []
<ide>
<del> const { Component } = initialData
<del> const { pathname } = location
<del> const route = toRoute(pathname)
<add> const id = createUid()
<add> const route = toRoute(location.pathname)
<ide>
<ide> this.currentRoute = route
<del> this.currentComponent = Component.displayName
<del> this.currentComponentData = initialData
<add> this.currentComponentData = { ...initialData, id }
<ide>
<ide> // set up the component cache (by route keys)
<ide> this.components = { [route]: initialData }
<ide>
<ide> // in order for `e.state` to work on the `onpopstate` event
<ide> // we have to register the initial route upon initialization
<del> const url = pathname + (location.search || '') + (location.hash || '')
<del> this.replace(Component, url)
<add> this.replace(id, getURL())
<ide>
<ide> this.onPopState = this.onPopState.bind(this)
<ide> window.addEventListener('unload', () => {})
<ide> export default class Router {
<ide> onPopState (e) {
<ide> this.abortComponentLoad()
<ide> const cur = this.currentComponent
<del> const pathname = location.pathname
<del> const url = pathname + (location.search || '') + (location.hash || '')
<add> const url = getURL()
<ide> const { fromComponent, route } = e.state || {}
<ide> if (fromComponent && cur && fromComponent === cur) {
<ide> // if the component has not changed due
<ide> export default class Router {
<ide> // since the URL has already changed
<ide> location.reload()
<ide> } else {
<del> this.currentRoute = route || toRoute(pathname)
<add> this.currentRoute = route || toRoute(location.pathname)
<ide> this.currentComponent = data.Component.displayName
<ide> this.currentComponentData = data
<ide> this.set(url)
<ide> export default class Router {
<ide> this.change('pushState', fromComponent, url, fn)
<ide> }
<ide>
<del> replace (fromComponent, url, fn) {
<del> this.change('replaceState', fromComponent, url, fn)
<add> replace (id, url, fn) {
<add> this.change('replaceState', id, url, fn)
<ide> }
<ide>
<del> change (method, component, url, fn) {
<add> change (method, id, url, fn) {
<ide> this.abortComponentLoad()
<ide>
<del> const set = (name) => {
<del> this.currentComponent = name
<del> const state = name
<del> ? { fromComponent: name, route: this.currentRoute }
<del> : {}
<add> const set = (id) => {
<add> const state = id ? { fromComponent: id, route: this.currentRoute } : {}
<ide> history[method](state, null, url)
<ide> this.set(url)
<ide> if (fn) fn(null)
<ide> }
<ide>
<del> const componentName = component && component.displayName
<del> if (component && !componentName) {
<del> throw new Error('Initial component must have a unique `displayName`')
<del> }
<del>
<del> if (this.currentComponent &&
<del> componentName !== this.currentComponent) {
<add> if (this.currentComponentData && id !== this.currentComponentData.id) {
<ide> this.fetchComponent(url, (err, data) => {
<ide> if (!err) {
<ide> this.currentRoute = toRoute(url)
<ide> this.currentComponentData = data
<del> set(data.Component.displayName)
<add> set(data.id)
<ide> }
<ide> if (fn) fn(err, data)
<ide> })
<ide> } else {
<del> set(componentName)
<add> set(id)
<ide> }
<ide> }
<ide>
<ide> export default class Router {
<ide> }
<ide>
<ide> fetchComponent (url, fn) {
<del> const pathname = parse(url, true)
<add> const { pathname } = parse(url)
<ide> const route = toRoute(pathname)
<ide>
<ide> let cancelled = false
<ide> export default class Router {
<ide> if (err) {
<ide> if (!cancelled) fn(err)
<ide> } else {
<add> const d = { data, id: createUid() }
<ide> // we update the cache even if cancelled
<ide> if (!this.components[route]) {
<del> this.components[route] = data
<add> this.components[route] = d
<ide> }
<del> if (!cancelled) fn(null, data)
<add> if (!cancelled) fn(null, d)
<ide> }
<ide> })
<ide>
<ide> export function loadComponent (url, fn) {
<ide> })
<ide> }
<ide>
<add>function getURL () {
<add> return location.pathname + (location.search || '') + (location.hash || '')
<add>}
<add>
<add>function createUid () {
<add> return Math.floor(Math.random() * 1e16)
<add>}
<add>
<ide> function loadJSON (url, fn) {
<ide> const xhr = new XMLHttpRequest()
<ide> xhr.onload = () => { | 2 |
Javascript | Javascript | resolve an edge case where ref.node can be falsy | 0aa4cc544c2ef93f53eea9373a35228a99f71784 | <ide><path>packages/react-refresh/src/ReactFreshBabelPlugin.js
<ide> export default function(babel, opts = {}) {
<ide> for (let i = 0; i < referencePaths.length; i++) {
<ide> const ref = referencePaths[i];
<ide> if (
<add> ref.node &&
<ide> ref.node.type !== 'JSXIdentifier' &&
<ide> ref.node.type !== 'Identifier'
<ide> ) { | 1 |
Python | Python | add benchmark for integer input to np.isin | 60c71bbfd5dc1024bc8ed59e7e7114f5f5359733 | <ide><path>benchmarks/benchmarks/bench_lib.py
<ide> def setup(self, array_size, percent_nans):
<ide>
<ide> def time_unique(self, array_size, percent_nans):
<ide> np.unique(self.arr)
<add>
<add>
<add>class Isin(Benchmark):
<add> """Benchmarks for `numpy.isin`."""
<add>
<add> param_names = ["size", "highest_element"]
<add> params = [
<add> [10, 100000, 3000000],
<add> [10, 10000, int(1e8)]
<add> ]
<add>
<add> def setup(self, size, highest_element):
<add> self.array = np.random.randint(
<add> low=0, high=highest_element, size=size)
<add> self.in_array = np.random.randint(
<add> low=0, high=highest_element, size=size)
<add>
<add> def time_isin(self, size, highest_element):
<add> np.isin(self.array, self.in_array) | 1 |
Javascript | Javascript | fix submit prevention | 86c7d1221c706993044583d51a0c61423fee5bcf | <ide><path>src/ng/directive/form.js
<ide> var formDirectiveFactory = function(isNgForm) {
<ide>
<ide> return {
<ide> pre: function ngFormPreLink(scope, formElement, attr, controller) {
<del> if (!attr.action) {
<add> // if `action` attr is not present on the form, prevent the default action (submission)
<add> if (!('action' in attr)) {
<ide> // we can't use jq events because if a form is destroyed during submission the default
<ide> // action is not prevented. see #1238
<ide> //
<ide><path>test/ng/directive/ngEventDirsSpec.js
<ide> describe('event directives', function() {
<ide> describe('ngSubmit', function() {
<ide>
<ide> it('should get called on form submit', inject(function($rootScope, $compile) {
<del> element = $compile('<form action="" ng-submit="submitted = true">' +
<add> element = $compile('<form action="/foo" ng-submit="submitted = true">' +
<ide> '<input type="submit"/>' +
<ide> '</form>')($rootScope);
<ide> $rootScope.$digest();
<add>
<add> // prevent submit within the test harness
<add> element.on('submit', function(e) { e.preventDefault(); });
<add>
<ide> expect($rootScope.submitted).not.toBeDefined();
<ide>
<ide> browserTrigger(element.children()[0]);
<ide> describe('event directives', function() {
<ide> }
<ide> };
<ide>
<del> element = $compile('<form action="" ng-submit="formSubmission($event)">' +
<add> element = $compile('<form action="/foo" ng-submit="formSubmission($event)">' +
<ide> '<input type="submit"/>' +
<ide> '</form>')($rootScope);
<ide> $rootScope.$digest();
<add>
<add> // prevent submit within the test harness
<add> element.on('submit', function(e) { e.preventDefault(); });
<add>
<ide> expect($rootScope.formSubmitted).not.toBeDefined();
<ide>
<ide> browserTrigger(element.children()[0]); | 2 |
PHP | PHP | update mass assignment to be guarded by default | a8925db5daa892f87bab5af310ed14ef9d408642 | <ide><path>Cake/ORM/Entity.php
<ide> public function __unset($property) {
<ide> *
<ide> * ## Example:
<ide> *
<del> * {{
<del> * $entity->set(['name' => 'andrew', 'id' => 1]);
<del> * echo $entity->name // prints andrew
<del> * echo $entity->id // prints 1
<del> * }}
<add> * {{{
<add> * $entity->set(['name' => 'andrew', 'id' => 1]);
<add> * echo $entity->name // prints andrew
<add> * echo $entity->id // prints 1
<add> * }}}
<ide> *
<ide> * Some times it is handy to bypass setter functions in this entity when assigning
<ide> * properties. You can achieve this by disabling the `setter` option using the
<del> * `$options` parameter
<del> *
<del> * ### Example:
<add> * `$options` parameter:
<ide> *
<del> * ``$entity->set('name', 'Andrew', ['setter' => false]);``
<del> *
<del> * ``$entity->set(['name' => 'Andrew', 'id' => 1], ['setter' => false]);``
<add> * {{{
<add> * $entity->set('name', 'Andrew', ['setter' => false]);
<add> * $entity->set(['name' => 'Andrew', 'id' => 1], ['setter' => false]);
<add> * }}}
<ide> *
<del> * Mass assignment should be treated carefully when accepting user input, for this
<del> * case you can tell this method to only set property that are marked as accessible
<del> * by setting the `guard` options in the `$options` parameter
<add> * Mass assignment should be treated carefully when accepting user input, by default
<add> * entities will guard all fields when properties are assigned in bulk. You can disable
<add> * the guarding for a single set call with the `guard` option:
<ide> *
<del> * ### Example:
<add> * {{{
<add> * $entity->set(['name' => 'Andrew', 'id' => 1], ['guard' => true]);
<add> * }}}
<ide> *
<del> * ``$entity->set('name', 'Andrew', ['guard' => true]);``
<add> * You do not need to use the guard option when assigning properties individually:
<ide> *
<del> * ``$entity->set(['name' => 'Andrew', 'id' => 1], ['guard' => true]);``
<add> * {{{
<add> * // No need to use the guard option.
<add> * $entity->set('name', 'Andrew');
<add> * }}}
<ide> *
<ide> * @param string|array $property the name of property to set or a list of
<ide> * properties with their respective values
<ide> public function __unset($property) {
<ide> */
<ide> public function set($property, $value = null, $options = []) {
<ide> if (is_string($property)) {
<add> $guard = false;
<ide> $property = [$property => $value];
<ide> } else {
<add> $guard = true;
<ide> $options = (array)$value;
<ide> }
<ide>
<del> $options += ['setter' => true, 'guard' => false];
<add> $options += ['setter' => true, 'guard' => $guard];
<ide>
<ide> foreach ($property as $p => $value) {
<ide> if ($options['guard'] === true && !$this->accessible($p)) {
<ide> public function set($property, $value = null, $options = []) {
<ide> }
<ide> $this->_properties[$p] = $value;
<ide> }
<del>
<ide> return $this;
<ide> }
<ide> | 1 |
PHP | PHP | add stub file that i missed before | 1d2af786eb1a14cdfb8e1934ddb8668e7c93e871 | <ide><path>tests/test_app/Plugin/TestPlugin/src/Command/WidgetCommand.php
<add><?php
<add>namespace TestPlugin\Command;
<add>
<add>use Cake\Console\Arguments;
<add>use Cake\Console\Command;
<add>use Cake\Console\ConsoleIo;
<add>
<add>class WidgetCommand extends Command
<add>{
<add> public function execute(Arguments $args, ConsoleIo $io)
<add> {
<add> $io->out('Widgets!');
<add> }
<add>} | 1 |
Java | Java | fix failing tests | 5e1e29a2dd6e94d7221aa90d21e052ffdc824a06 | <ide><path>spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/AbstractDataBufferAllocatingTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.lang.annotation.Retention;
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<add>import java.nio.charset.Charset;
<ide> import java.nio.charset.StandardCharsets;
<ide> import java.time.Duration;
<ide> import java.time.Instant;
<ide> protected void release(DataBuffer... buffers) {
<ide> }
<ide>
<ide> protected Consumer<DataBuffer> stringConsumer(String expected) {
<add> return stringConsumer(expected, UTF_8);
<add> }
<add>
<add> protected Consumer<DataBuffer> stringConsumer(String expected, Charset charset) {
<ide> return dataBuffer -> {
<del> String value = dataBuffer.toString(UTF_8);
<add> String value = dataBuffer.toString(charset);
<ide> DataBufferUtils.release(dataBuffer);
<ide> assertThat(value).isEqualTo(expected);
<ide> };
<ide><path>spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageWriterTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> void writePojo(String displayName, DataBufferFactory bufferFactory) {
<ide> testWrite(source, outputMessage, Pojo.class);
<ide>
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(stringConsumer("data:{\"foo\":\"foofoo\",\"bar\":\"barbar\"}\n\n"))
<del> .consumeNextWith(stringConsumer("data:{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}\n\n"))
<add> .consumeNextWith(stringConsumer("data:"))
<add> .consumeNextWith(stringConsumer("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}"))
<add> .consumeNextWith(stringConsumer("\n\n"))
<add> .consumeNextWith(stringConsumer("data:"))
<add> .consumeNextWith(stringConsumer("{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}"))
<add> .consumeNextWith(stringConsumer("\n\n"))
<ide> .expectComplete()
<ide> .verify();
<ide> }
<ide> void writePojoWithPrettyPrint(String displayName, DataBufferFactory bufferFactor
<ide> testWrite(source, outputMessage, Pojo.class);
<ide>
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(stringConsumer("data:{\n" +
<add> .consumeNextWith(stringConsumer("data:"))
<add> .consumeNextWith(stringConsumer("{\n" +
<ide> "data: \"foo\" : \"foofoo\",\n" +
<del> "data: \"bar\" : \"barbar\"\n" + "data:}\n\n"))
<del> .consumeNextWith(stringConsumer("data:{\n" +
<add> "data: \"bar\" : \"barbar\"\n" + "data:}"))
<add> .consumeNextWith(stringConsumer("\n\n"))
<add> .consumeNextWith(stringConsumer("data:"))
<add> .consumeNextWith(stringConsumer("{\n" +
<ide> "data: \"foo\" : \"foofoofoo\",\n" +
<del> "data: \"bar\" : \"barbarbar\"\n" + "data:}\n\n"))
<add> "data: \"bar\" : \"barbarbar\"\n" + "data:}"))
<add> .consumeNextWith(stringConsumer("\n\n"))
<ide> .expectComplete()
<ide> .verify();
<ide> }
<ide> void writePojoWithCustomEncoding(String displayName, DataBufferFactory bufferFac
<ide>
<ide> assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(mediaType);
<ide> StepVerifier.create(outputMessage.getBody())
<del> .consumeNextWith(dataBuffer -> {
<del> String value = dataBuffer.toString(charset);
<del> DataBufferUtils.release(dataBuffer);
<del> assertThat(value).isEqualTo("data:{\"foo\":\"foo\uD834\uDD1E\",\"bar\":\"bar\uD834\uDD1E\"}\n\n");
<del> })
<add> .consumeNextWith(stringConsumer("data:", charset))
<add> .consumeNextWith(stringConsumer("{\"foo\":\"foo\uD834\uDD1E\",\"bar\":\"bar\uD834\uDD1E\"}", charset))
<add> .consumeNextWith(stringConsumer("\n\n", charset))
<ide> .expectComplete()
<ide> .verify();
<ide> } | 2 |
Ruby | Ruby | build the association graph functionally | db994076946f44d9b0fea23ca8715a74cb1f2b87 | <ide><path>activerecord/lib/active_record/associations/join_dependency.rb
<ide> def self.walk_tree(associations, hash)
<ide> # joins #=> []
<ide> #
<ide> def initialize(base, associations, joins)
<del> @join_root = JoinBase.new(base)
<ide> @alias_tracker = AliasTracker.new(base.connection, joins)
<ide> @alias_tracker.aliased_name_for(base.table_name) # Updates the count for base.table_name to 1
<ide> tree = self.class.make_tree associations
<del> build tree, @join_root
<add> @join_root = JoinBase.new base, build(tree, base)
<ide> @join_root.children.each { |child| construct_tables! @join_root, child }
<ide> end
<ide>
<ide> def find_reflection(klass, name)
<ide> raise ConfigurationError, "Association named '#{ name }' was not found on #{ klass.name }; perhaps you misspelled it?"
<ide> end
<ide>
<del> def build(associations, parent)
<del> associations.each do |name, right|
<del> reflection = find_reflection parent.base_klass, name
<del> join_association = build_join_association reflection
<del> parent.children << join_association
<del> build right, join_association
<del> end
<del> end
<add> def build(associations, base_klass)
<add> associations.map do |name, right|
<add> reflection = find_reflection base_klass, name
<add> reflection.check_validity!
<ide>
<del> def build_join_association(reflection)
<del> reflection.check_validity!
<add> if reflection.options[:polymorphic]
<add> raise EagerLoadPolymorphicError.new(reflection)
<add> end
<ide>
<del> if reflection.options[:polymorphic]
<del> raise EagerLoadPolymorphicError.new(reflection)
<add> JoinAssociation.new reflection, build(right, reflection.klass)
<ide> end
<del>
<del> JoinAssociation.new(reflection)
<ide> end
<ide>
<ide> def construct(ar_parent, parent, row, rs, seen, model_cache, aliases)
<ide><path>activerecord/lib/active_record/associations/join_dependency/join_association.rb
<ide> class JoinAssociation < JoinPart # :nodoc:
<ide>
<ide> attr_accessor :tables
<ide>
<del> def initialize(reflection)
<del> super(reflection.klass)
<add> def initialize(reflection, children)
<add> super(reflection.klass, children)
<ide>
<ide> @reflection = reflection
<ide> @tables = nil
<ide><path>activerecord/lib/active_record/associations/join_dependency/join_part.rb
<ide> class JoinPart # :nodoc:
<ide>
<ide> delegate :table_name, :column_names, :primary_key, :to => :base_klass
<ide>
<del> def initialize(base_klass)
<add> def initialize(base_klass, children)
<ide> @base_klass = base_klass
<ide> @column_names_with_alias = nil
<del> @children = []
<add> @children = children
<ide> end
<ide>
<ide> def name | 3 |
Text | Text | clarify test text in line with test functionality | e0e8ab8409c60482e8f054727b7757934e34971d | <ide><path>curriculum/challenges/english/03-front-end-libraries/react/pass-an-array-as-props.english.md
<ide> tests:
<ide> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find("List").get(0).props.tasks.length >= 2; })(), "The first <code>List</code> component representing the tasks for today should have 2 or more items.");'
<ide> - text: The second <code>List</code> component representing the tasks for tomorrow should have 3 or more items.
<ide> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find("List").get(1).props.tasks.length >= 3; })(), "The second <code>List</code> component representing the tasks for tomorrow should have 3 or more items.");'
<del> - text: The <code>List</code> component should render the value from the <code>tasks</code> prop in the <code>p</code> tag.
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find("p").get(0).props.children === mockedComponent.find("List").get(0).props.tasks.join(", ") && mockedComponent.find("p").get(1).props.children === mockedComponent.find("List").get(1).props.tasks.join(", "); })(), "The <code>List</code> component should render the value from the <code>tasks</code> prop in the <code>p</code> tag.");'
<add> - text: The <code>List</code> component should render the value from the <code>tasks</code> prop in the <code>p</code> tag as a comma separated list, for example <code>walk dog, workout</code>.
<add> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find("p").get(0).props.children === mockedComponent.find("List").get(0).props.tasks.join(", ") && mockedComponent.find("p").get(1).props.children === mockedComponent.find("List").get(1).props.tasks.join(", "); })(), "The <code>List</code> component should render the value from the <code>tasks</code> prop in the <code>p</code> tag as a comma separated list, for example <code>walk dog, workout</code>.");'
<ide>
<ide> ```
<ide> | 1 |
Go | Go | fix input volume path check on windows | 5a38680bd2283c87848d2e7f62a14f0261291c7c | <ide><path>opts/opts.go
<ide> import (
<ide> "net"
<ide> "net/url"
<ide> "os"
<del> "path/filepath"
<add> "path"
<ide> "regexp"
<ide> "strings"
<ide>
<ide> func ValidatePath(val string) (string, error) {
<ide> splited := strings.SplitN(val, ":", 2)
<ide> if len(splited) == 1 {
<ide> containerPath = splited[0]
<del> val = filepath.Clean(splited[0])
<add> val = path.Clean(splited[0])
<ide> } else {
<ide> containerPath = splited[1]
<del> val = fmt.Sprintf("%s:%s", splited[0], filepath.Clean(splited[1]))
<add> val = fmt.Sprintf("%s:%s", splited[0], path.Clean(splited[1]))
<ide> }
<ide>
<del> if !filepath.IsAbs(containerPath) {
<add> if !path.IsAbs(containerPath) {
<ide> return val, fmt.Errorf("%s is not an absolute path", containerPath)
<ide> }
<ide> return val, nil | 1 |
PHP | PHP | add remove() and insert() | 3d8a955043936e3604e381b728c0aa1deec84b02 | <ide><path>lib/Cake/Test/Case/Utility/Set2Test.php
<ide> public function testSortWithOutOfOrderKeys() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Test insert()
<add> *
<add> * @return void
<add> */
<add> public function testInsertSimple() {
<add> $a = array(
<add> 'pages' => array('name' => 'page')
<add> );
<add> $result = Set2::insert($a, 'files', array('name' => 'files'));
<add> $expected = array(
<add> 'pages' => array('name' => 'page'),
<add> 'files' => array('name' => 'files')
<add> );
<add> $this->assertEquals($expected, $result);
<add>
<add> $a = array(
<add> 'pages' => array('name' => 'page')
<add> );
<add> $result = Set2::insert($a, 'pages.name', array());
<add> $expected = array(
<add> 'pages' => array('name' => array()),
<add> );
<add> $this->assertEquals($expected, $result);
<add> }
<ide>
<ide> /**
<del> * Test remove()
<add> * Test inserting with multiple values.
<add> *
<add> * @return void
<add> */
<add> public function testInsertMulti() {
<add> $data = self::articleData();
<add>
<add> $result = Set2::insert($data, '{n}.Article.insert', 'value');
<add> $this->assertEquals('value', $result[0]['Article']['insert']);
<add> $this->assertEquals('value', $result[1]['Article']['insert']);
<add>
<add> $result = Set2::insert($data, '{n}.Comment.{n}.insert', 'value');
<add> $this->assertEquals('value', $result[0]['Comment'][0]['insert']);
<add> $this->assertEquals('value', $result[0]['Comment'][1]['insert']);
<add> }
<add>
<add>/**
<add> * Test remove() method.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testRemove() {
<add> $a = array(
<add> 'pages' => array('name' => 'page'),
<add> 'files' => array('name' => 'files')
<add> );
<add>
<add> $result = Set2::remove($a, 'files');
<add> $expected = array(
<add> 'pages' => array('name' => 'page')
<add> );
<add> $this->assertEquals($expected, $result);
<add>
<add> $a = array(
<add> 'pages' => array(
<add> 0 => array('name' => 'main'),
<add> 1 => array(
<add> 'name' => 'about',
<add> 'vars' => array('title' => 'page title')
<add> )
<add> )
<add> );
<add>
<add> $result = Set2::remove($a, 'pages.1.vars');
<add> $expected = array(
<add> 'pages' => array(
<add> 0 => array('name' => 'main'),
<add> 1 => array('name' => 'about')
<add> )
<add> );
<add> $this->assertEquals($expected, $result);
<add>
<add> $result = Set2::remove($a, 'pages.2.vars');
<add> $expected = $a;
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<add>/**
<add> * Test removing multiple values.
<add> *
<add> * @return void
<add> */
<add> public function testRemoveMulti() {
<ide> $data = self::articleData();
<ide>
<del> $result = Set2::insert($data, '{n}.Article', array('test'));
<del> debug($result);
<add> $result = Set2::remove($data, '{n}.Article.title');
<add> $this->assertFalse(isset($result[0]['Article']['title']));
<add> $this->assertFalse(isset($result[1]['Article']['title']));
<ide>
<del> $result = Set2::remove($data, '{n}.Article');
<del> debug($result);
<del> $this->assertFalse(isset($data[0]['Article']));
<add> $result = Set2::remove($data, '{n}.Article.{s}');
<add> $this->assertFalse(isset($result[0]['Article']['id']));
<add> $this->assertFalse(isset($result[0]['Article']['user_id']));
<add> $this->assertFalse(isset($result[0]['Article']['title']));
<add> $this->assertFalse(isset($result[0]['Article']['body']));
<ide> }
<ide>
<ide> }
<ide><path>lib/Cake/Utility/Set2.php
<ide> public static function extract(array $data, $path) {
<ide> return (array) self::get($data, $path);
<ide> }
<ide>
<del> return self::_traverse($data, $path, function ($value) {
<del> return $value;
<del> });
<del> }
<del>
<del>/**
<del> * Traverses $data for $path. $callback is called for each terminal element.
<del> * The results of all the callbacks are returned.
<del> *
<del> * @param array $data The data to traverse.
<del> * @param string $path The set path to walk.
<del> * @param callable $callback to call on the result set.
<del> * @return array Results of the callback mapped over the leaf nodes of the path expression.
<del> */
<del> protected static function _traverse(array &$data, $path, $callback) {
<del> $result = array();
<del>
<ide> if (strpos('[', $path) === false) {
<ide> $tokens = explode('.', $path);
<ide> } else {
<ide> protected static function _traverse(array &$data, $path, $callback) {
<ide> }
<ide> $next = $filter;
<ide> }
<del>
<ide> $context = array($_key => $next);
<ide>
<ide> } while (!empty($tokens));
<del>
<del> return array_map($callback, $context[$_key]);
<add> return $context[$_key];
<ide> }
<ide>
<ide> /**
<ide> protected static function _matches(array $data, $selector) {
<ide> return true;
<ide> }
<ide>
<add>/**
<add> * Insert $values into an array with the given $path.
<add> *
<add> * @param array $data The data to insert into.
<add> * @param string $path The path to insert at.
<add> * @param mixed $values The values to insert.
<add> * @return array The data with $values inserted.
<add> */
<ide> public static function insert(array $data, $path, $values = null) {
<del> if (empty($path)) {
<del> return $data;
<add> $tokens = explode('.', $path);
<add> if (strpos($path, '{') === false) {
<add> return self::_simpleInsert($data, $tokens, $values);
<add> }
<add>
<add> $token = array_shift($tokens);
<add> $nextPath = implode('.', $tokens);
<add> foreach ($data as $k => $v) {
<add> if (self::_matchToken($k, $token)) {
<add> $data[$k] = self::insert($v, $nextPath, $values);
<add> }
<ide> }
<add> return $data;
<add> }
<ide>
<del> $result = self::_traverse($data, $path, function (&$value) use ($values) {
<del> $value['test'] = $values;
<del> return $value;
<del> });
<add>/**
<add> * Inserts values into simple paths.
<add> *
<add> * @param array $data Data to insert into.
<add> * @param string $path The path to insert into.
<add> * @param mixed $values The values to insert.
<add> * @return array Data with values inserted at $path.
<add> */
<add> protected static function _simpleInsert($data, $path, $values) {
<add> $_list =& $data;
<ide>
<add> $count = count($path);
<add> foreach ($path as $i => $key) {
<add> if (is_numeric($key) && intval($key) > 0 || $key === '0') {
<add> $key = intval($key);
<add> }
<add> if ($i === $count - 1 && is_array($_list)) {
<add> $_list[$key] = $values;
<add> } else {
<add> if (!isset($_list[$key])) {
<add> $_list[$key] = array();
<add> }
<add> $_list =& $_list[$key];
<add> }
<add> if (!is_array($_list)) {
<add> return array();
<add> }
<add> }
<ide> return $data;
<ide> }
<ide>
<ide> public static function insert(array $data, $path, $values = null) {
<ide> * @return array The modified array.
<ide> */
<ide> public static function remove(array $data, $path) {
<add> $tokens = explode('.', $path);
<add> if (strpos($path, '{') === false) {
<add> return self::_simpleRemove($data, $path);
<add> }
<add>
<add> $token = array_shift($tokens);
<add> $nextPath = implode('.', $tokens);
<add> foreach ($data as $k => $v) {
<add> $match = self::_matchToken($k, $token);
<add> if ($match && is_array($v)) {
<add> $data[$k] = self::remove($v, $nextPath);
<add> } elseif ($match) {
<add> unset($data[$k]);
<add> }
<add> }
<add> return $data;
<add> }
<add>
<add>/**
<add> * Remove values along a simple path.
<add> *
<add> * @param array $data Array to operate on.
<add> * @param string $path The path to remove.
<add> * @return array Data with value removed.
<add> */
<add> protected static function _simpleRemove($data, $path) {
<ide> if (empty($path)) {
<ide> return $data;
<ide> }
<add> if (!is_array($path)) {
<add> $path = explode('.', $path);
<add> }
<add> $_list =& $data;
<ide>
<del> return self::_traverse($data, $path, function ($value) {
<del> return $value;
<del> });
<add> foreach ($path as $i => $key) {
<add> if (is_numeric($key) && intval($key) > 0 || $key === '0') {
<add> $key = intval($key);
<add> }
<add> if ($i === count($path) - 1) {
<add> unset($_list[$key]);
<add> } else {
<add> if (!isset($_list[$key])) {
<add> return $data;
<add> }
<add> $_list =& $_list[$key];
<add> }
<add> }
<add> return $data;
<ide> }
<ide>
<ide> public static function combine(array $data, $keyPath, $valuePath = null) { | 2 |
PHP | PHP | apply fixes from styleci | 6f4076a5d2789538a835f63c47c41dfa4845c7b5 | <ide><path>src/Illuminate/Queue/Jobs/Job.php
<ide>
<ide> namespace Illuminate\Queue\Jobs;
<ide>
<del>use DateTime;
<del>use Carbon\Carbon;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Queue\CalculatesDelays;
<ide>
<ide><path>src/Illuminate/Queue/Queue.php
<ide>
<ide> namespace Illuminate\Queue;
<ide>
<del>use DateTime;
<del>use Carbon\Carbon;
<ide> use Illuminate\Support\Arr;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Container\Container; | 2 |
Python | Python | add filled_like to doc string of test class | 5be86a8af14e30127bdd102c8c0647de9a934ea3 | <ide><path>numpy/core/tests/test_numeric.py
<ide> def test_basic(self):
<ide>
<ide>
<ide> class TestLikeFuncs(TestCase):
<del> '''Test ones_like, zeros_like, and empty_like'''
<add> '''Test ones_like, zeros_like, empty_like and filled_like'''
<ide>
<ide> def setUp(self):
<ide> self.data = [ | 1 |
Mixed | Python | fix the build -- 88 chars per line max. | f34434a214e4c937f3a5a5b0d1f1bd64a3bee7c5 | <ide><path>DIRECTORY.md
<ide>
<ide> ## Computer Vision
<ide> * [Harriscorner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harriscorner.py)
<add> * [Meanthreshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/meanthreshold.py)
<ide>
<ide> ## Conversions
<ide> * [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py)
<ide> * [Circular Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/circular_linked_list.py)
<ide> * [Deque Doubly](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/deque_doubly.py)
<ide> * [Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list.py)
<add> * [Doubly Linked List Two](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list_two.py)
<ide> * [From Sequence](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/from_sequence.py)
<ide> * [Has Loop](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/has_loop.py)
<ide> * [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/is_palindrome.py)
<ide> * Stacks
<ide> * [Balanced Parentheses](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/balanced_parentheses.py)
<ide> * [Dijkstras Two Stack Algorithm](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/dijkstras_two_stack_algorithm.py)
<add> * [Evaluate Postfix Notations](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/evaluate_postfix_notations.py)
<ide> * [Infix To Postfix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_postfix_conversion.py)
<ide> * [Infix To Prefix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_prefix_conversion.py)
<ide> * [Linked Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/linked_stack.py)
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_055/sol1.py)
<ide> * Problem 056
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_056/sol1.py)
<add> * Problem 057
<add> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_057/sol1.py)
<ide> * Problem 062
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_062/sol1.py)
<ide> * Problem 063
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_071/sol1.py)
<ide> * Problem 072
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol1.py)
<add> * [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol2.py)
<ide> * Problem 074
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol1.py)
<add> * Problem 075
<add> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_075/sol1.py)
<ide> * Problem 076
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_076/sol1.py)
<ide> * Problem 080
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_080/sol1.py)
<add> * Problem 091
<add> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_091/sol1.py)
<ide> * Problem 097
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_097/sol1.py)
<ide> * Problem 099
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_125/sol1.py)
<ide> * Problem 173
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py)
<add> * Problem 174
<add> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_174/sol1.py)
<ide> * Problem 191
<ide> * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_191/sol1.py)
<ide> * Problem 234
<ide> * [Validate Solutions](https://github.com/TheAlgorithms/Python/blob/master/project_euler/validate_solutions.py)
<ide>
<ide> ## Quantum
<add> * [Half Adder](https://github.com/TheAlgorithms/Python/blob/master/quantum/half_adder.py)
<ide> * [Not Gate](https://github.com/TheAlgorithms/Python/blob/master/quantum/not_gate.py)
<ide> * [Quantum Entanglement](https://github.com/TheAlgorithms/Python/blob/master/quantum/quantum_entanglement.py)
<ide> * [Single Qubit Measure](https://github.com/TheAlgorithms/Python/blob/master/quantum/single_qubit_measure.py)
<ide><path>quantum/half_adder.py
<ide> .
<ide>
<ide> References:
<del>- https://en.wikipedia.org/wiki/Adder_(electronics)
<del>- https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add-
<add>https://en.wikipedia.org/wiki/Adder_(electronics)
<add>https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add-
<ide> """
<ide>
<ide> import qiskit as q | 2 |
Javascript | Javascript | handle sub/super-scripts in rich text | cfdaa5735330cda74df01a0a95a64f5428270771 | <ide><path>src/core/xfa/xhtml.js
<ide> const StyleMapping = new Map([
<ide> ["margin-top", value => measureToString(getMeasurement(value))],
<ide> ["text-indent", value => measureToString(getMeasurement(value))],
<ide> ["font-family", value => value],
<add> ["vertical-align", value => measureToString(getMeasurement(value))],
<ide> ]);
<ide>
<ide> const spacesRegExp = /\s+/g;
<ide> const crlfRegExp = /[\r\n]+/g;
<ide> const crlfForRichTextRegExp = /\r\n?/g;
<ide>
<del>function mapStyle(styleStr, node) {
<add>function mapStyle(styleStr, node, richText) {
<ide> const style = Object.create(null);
<ide> if (!styleStr) {
<ide> return style;
<ide> function mapStyle(styleStr, node) {
<ide> );
<ide> }
<ide>
<add> if (
<add> richText &&
<add> style.verticalAlign &&
<add> style.verticalAlign !== "0px" &&
<add> style.fontSize
<add> ) {
<add> // A non-zero verticalAlign means that we've a sub/super-script and
<add> // consequently the font size must be decreased.
<add> // https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf#G11.2097514
<add> // And the two following factors to position the scripts have been
<add> // found here:
<add> // https://en.wikipedia.org/wiki/Subscript_and_superscript#Desktop_publishing
<add> const SUB_SUPER_SCRIPT_FACTOR = 0.583;
<add> const VERTICAL_FACTOR = 0.333;
<add> const fontSize = getMeasurement(style.fontSize);
<add> style.fontSize = measureToString(fontSize * SUB_SUPER_SCRIPT_FACTOR);
<add> style.verticalAlign = measureToString(
<add> Math.sign(getMeasurement(style.verticalAlign)) *
<add> fontSize *
<add> VERTICAL_FACTOR
<add> );
<add> }
<add>
<ide> fixTextIndent(style);
<ide> return style;
<ide> }
<ide> class XhtmlObject extends XmlObject {
<ide> name: this[$nodeName],
<ide> attributes: {
<ide> href: this.href,
<del> style: mapStyle(this.style, this),
<add> style: mapStyle(this.style, this, this[$richText]),
<ide> },
<ide> children,
<ide> value, | 1 |
Ruby | Ruby | set proper assertion to be sure the test failed | f0b93d135e63d4795efe1fbd60e5a713ec53c1a2 | <ide><path>railties/test/application/test_test.rb
<ide> def test_truth
<ide> end
<ide> RUBY
<ide>
<del> assert_unsuccessful_run "unit/foo_test.rb", "Expected false to be truthy"
<add> assert_unsuccessful_run "unit/foo_test.rb", "Failure:\nFooTest#test_truth"
<ide> end
<ide>
<ide> test "integration test" do | 1 |
Python | Python | document the exceptioninfo class | 6febb44e06b3258867bf0fd270a6d9c6563c55b6 | <ide><path>celery/datastructures.py
<ide> def filled(self):
<ide>
<ide>
<ide> class ExceptionInfo(object):
<add> """Exception wrapping an exception and its traceback.
<add>
<add> :param exc_info: The exception tuple info as returned by
<add> :func:`traceback.format_exception`.
<add>
<add>
<add> .. attribute:: exception
<add>
<add> The original exception.
<add>
<add> .. attribute:: traceback
<add>
<add> A traceback from the point when :attr:`exception` was raised.
<add>
<add> """
<add>
<ide> def __init__(self, exc_info):
<ide> type_, exception, tb = exc_info
<ide> self.exception = exception | 1 |
Text | Text | add v15 rc2 blog post | 7dd71ca48834300e334aab1df1dba7fd89141b66 | <ide><path>docs/_posts/2016-03-16-react-v15-rc2.md
<add>---
<add>title: "React v15.0 Release Candidate 2"
<add>author: zpao
<add>---
<add>
<add>Today we're releasing a second release candidate for version 15. Primarily this is to address 2 issues, but we also picked up a few small changes from new contributors, including some improvements to some of our new warnings.
<add>
<add>The most pressing change that was made is to fix a bug in our new code that removes `<span>`s, as discussed in the original RC1 post. Specifically we have some code that takes a different path in IE11 and Edge due to the speed of some DOM operations. There was a bug in this code which didn't break out of the optimization for `DocumentFragment`s, resulting in text not appearing at all. Thanks to the several people who [reported this](https://github.com/facebook/react/issues/6246).
<add>
<add>The other change is to our SVG code. In RC1 we had made the decision to pass through all attributes directly. This led to [some confusion with `class` vs `className`](https://github.com/facebook/react/issues/6211) and ultimately led us to reconsider our position on the approach. Passing through all attributes meant that we would have two different patterns for using React where things like hyphenated attributes would work for SVG but not HTML. In the future, we *might* change our approach to the problem for HTML as well but in the meantime, maintaining consistency is important. So we reverted the changes that allowed the attributes to be passed through and instead expanded the SVG property list to include all attributes that are in the spec. We believe we have everything now but definitely [let us know](https://github.com/facebook/react/issues/1657#issuecomment-197031403) if we missed anything. It was and still is our intent to support the full range of SVG tags and attributes in this release.
<add>
<add>Thanks again to everybody who has tried the RC1 and reported issues. It has been extremely important and we wouldn't be able to do this without your help!
<add>
<add>## Installation
<add>
<add>We recommend using React from `npm` and using a tool like browserify or webpack to build your code into a single bundle. To install the two packages:
<add>
<add>* `npm install --save react@15.0.0-rc.2 react-dom@15.0.0-rc.2`
<add>
<add>Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, set the `NODE_ENV` environment variable to `production` to use the production build of React which does not include the development warnings and runs significantly faster.
<add>
<add>If you can’t use `npm` yet, we provide pre-built browser builds for your convenience, which are also available in the `react` package on bower.
<add>
<add>* **React**
<add> Dev build with warnings: <https://fb.me/react-15.0.0-rc.2.js>
<add> Minified build for production: <https://fb.me/react-15.0.0-rc.2.min.js>
<add>* **React with Add-Ons**
<add> Dev build with warnings: <https://fb.me/react-with-addons-15.0.0-rc.2.js>
<add> Minified build for production: <https://fb.me/react-with-addons-15.0.0-rc.2.min.js>
<add>* **React DOM** (include React in the page before React DOM)
<add> Dev build with warnings: <https://fb.me/react-dom-15.0.0-rc.2.js>
<add> Minified build for production: <https://fb.me/react-dom-15.0.0-rc.2.min.js> | 1 |
Python | Python | return actual bools instead of 0 or 1 | a4847b1de5fc8398c2589e04aee1b63ba0592ff4 | <ide><path>numpy/core/numeric.py
<ide> def asarray(a, dtype=None, order=None):
<ide> def asanyarray(a, dtype=None, order=None):
<ide> """Returns a as an array, but will pass subclasses through.
<ide> """
<del> return array(a, dtype, copy=False, order=order, subok=1)
<add> return array(a, dtype, copy=False, order=order, subok=True)
<ide>
<ide> def ascontiguousarray(a, dtype=None):
<ide> """Return 'a' as an array contiguous in memory (C order).
<ide> def require(a, dtype=None, requirements=None):
<ide> return asanyarray(a, dtype=dtype)
<ide>
<ide> if 'ENSUREARRAY' in requirements or 'E' in requirements:
<del> subok = 0
<add> subok = False
<ide> else:
<del> subok = 1
<add> subok = True
<ide>
<ide> arr = array(a, dtype=dtype, copy=False, subok=subok)
<ide>
<ide> def tensordot(a, b, axes=2):
<ide> nda = len(a.shape)
<ide> bs = b.shape
<ide> ndb = len(b.shape)
<del> equal = 1
<del> if (na != nb): equal = 0
<add> equal = True
<add> if (na != nb): equal = False
<ide> else:
<ide> for k in xrange(na):
<ide> if as_[axes_a[k]] != bs[axes_b[k]]:
<del> equal = 0
<add> equal = False
<ide> break
<ide> if axes_a[k] < 0:
<ide> axes_a[k] += nda
<ide> def roll(a, shift, axis=None):
<ide> a = asanyarray(a)
<ide> if axis is None:
<ide> n = a.size
<del> reshape=1
<add> reshape = True
<ide> else:
<ide> n = a.shape[axis]
<del> reshape=0
<add> reshape = False
<ide> shift %= n
<ide> indexes = concatenate((arange(n-shift,n),arange(n-shift)))
<ide> res = a.take(indexes, axis)
<ide> def array_equal(a1, a2):
<ide> try:
<ide> a1, a2 = asarray(a1), asarray(a2)
<ide> except:
<del> return 0
<add> return False
<ide> if a1.shape != a2.shape:
<del> return 0
<del> return logical_and.reduce(equal(a1,a2).ravel())
<add> return False
<add> return bool(logical_and.reduce(equal(a1,a2).ravel()))
<ide>
<ide> def array_equiv(a1, a2):
<ide> """Returns True if a1 and a2 are shape consistent
<ide> def array_equiv(a1, a2):
<ide> try:
<ide> a1, a2 = asarray(a1), asarray(a2)
<ide> except:
<del> return 0
<add> return False
<ide> try:
<del> return logical_and.reduce(equal(a1,a2).ravel())
<add> return bool(logical_and.reduce(equal(a1,a2).ravel()))
<ide> except ValueError:
<del> return 0
<add> return False
<ide>
<ide>
<ide> _errdict = {"ignore":ERR_IGNORE,
<ide><path>numpy/core/tests/test_numeric.py
<ide> def test_negative(self):
<ide> assert_equal(binary_repr(-1, width=8), '11111111')
<ide>
<ide>
<add>class TestArrayComparisons(TestCase):
<add> def test_array_equal(self):
<add> res = array_equal(array([1,2]), array([1,2]))
<add> assert res
<add> assert type(res) is bool
<add> res = array_equal(array([1,2]), array([1,2,3]))
<add> assert not res
<add> assert type(res) is bool
<add> res = array_equal(array([1,2]), array([3,4]))
<add> assert not res
<add> assert type(res) is bool
<add> res = array_equal(array([1,2]), array([1,3]))
<add> assert not res
<add> assert type(res) is bool
<add>
<add> def test_array_equiv(self):
<add> res = array_equiv(array([1,2]), array([1,2]))
<add> assert res
<add> assert type(res) is bool
<add> res = array_equiv(array([1,2]), array([1,2,3]))
<add> assert not res
<add> assert type(res) is bool
<add> res = array_equiv(array([1,2]), array([3,4]))
<add> assert not res
<add> assert type(res) is bool
<add> res = array_equiv(array([1,2]), array([1,3]))
<add> assert not res
<add> assert type(res) is bool
<add>
<add> res = array_equiv(array([1,1]), array([1]))
<add> assert res
<add> assert type(res) is bool
<add> res = array_equiv(array([1,1]), array([[1],[1]]))
<add> assert res
<add> assert type(res) is bool
<add> res = array_equiv(array([1,2]), array([2]))
<add> assert not res
<add> assert type(res) is bool
<add> res = array_equiv(array([1,2]), array([[1],[2]]))
<add> assert not res
<add> assert type(res) is bool
<add> res = array_equiv(array([1,2]), array([[1,2,3],[4,5,6],[7,8,9]]))
<add> assert not res
<add> assert type(res) is bool
<add>
<add>
<ide> def assert_array_strict_equal(x, y):
<ide> assert_array_equal(x, y)
<ide> # Check flags | 2 |
Ruby | Ruby | handle delete with limit in arel | 859fba7c4bf7d33b4f9655914ed4bdc85380552e | <ide><path>activerecord/lib/active_record/relation.rb
<ide> def delete_all
<ide> stmt = Arel::DeleteManager.new
<ide> stmt.from(table)
<ide>
<del> if has_join_values? || has_limit_or_offset?
<add> if has_join_values? || offset_value
<ide> @klass.connection.join_to_delete(stmt, arel, arel_attribute(primary_key))
<ide> else
<add> stmt.key = arel_attribute(primary_key)
<add> stmt.take(arel.limit)
<add> stmt.order(*arel.orders)
<ide> stmt.wheres = arel.constraints
<ide> end
<ide>
<ide><path>activerecord/lib/arel/delete_manager.rb
<ide>
<ide> module Arel # :nodoc: all
<ide> class DeleteManager < Arel::TreeManager
<add> include TreeManager::StatementMethods
<add>
<ide> def initialize
<ide> super
<ide> @ast = Nodes::DeleteStatement.new
<ide> def from(relation)
<ide> @ast.relation = relation
<ide> self
<ide> end
<del>
<del> def take(limit)
<del> @ast.limit = Nodes::Limit.new(Nodes.build_quoted(limit)) if limit
<del> self
<del> end
<del>
<del> def wheres=(list)
<del> @ast.wheres = list
<del> end
<ide> end
<ide> end
<ide><path>activerecord/lib/arel/nodes/delete_statement.rb
<ide> module Arel # :nodoc: all
<ide> module Nodes
<ide> class DeleteStatement < Arel::Nodes::Node
<del> attr_accessor :left, :right
<del> attr_accessor :limit
<add> attr_accessor :left, :right, :orders, :limit, :key
<ide>
<ide> alias :relation :left
<ide> alias :relation= :left=
<ide> def initialize(relation = nil, wheres = [])
<ide> super()
<ide> @left = relation
<ide> @right = wheres
<add> @orders = []
<add> @limit = nil
<add> @key = nil
<ide> end
<ide>
<ide> def initialize_copy(other)
<ide> def initialize_copy(other)
<ide> end
<ide>
<ide> def hash
<del> [self.class, @left, @right].hash
<add> [self.class, @left, @right, @orders, @limit, @key].hash
<ide> end
<ide>
<ide> def eql?(other)
<ide> self.class == other.class &&
<ide> self.left == other.left &&
<del> self.right == other.right
<add> self.right == other.right &&
<add> self.orders == other.orders &&
<add> self.limit == other.limit &&
<add> self.key == other.key
<ide> end
<ide> alias :== :eql?
<ide> end
<ide><path>activerecord/lib/arel/nodes/update_statement.rb
<ide> module Arel # :nodoc: all
<ide> module Nodes
<ide> class UpdateStatement < Arel::Nodes::Node
<del> attr_accessor :relation, :wheres, :values, :orders, :limit
<del> attr_accessor :key
<add> attr_accessor :relation, :wheres, :values, :orders, :limit, :key
<ide>
<ide> def initialize
<ide> @relation = nil
<ide><path>activerecord/lib/arel/tree_manager.rb
<ide> module Arel # :nodoc: all
<ide> class TreeManager
<ide> include Arel::FactoryMethods
<ide>
<add> module StatementMethods
<add> def take(limit)
<add> @ast.limit = Nodes::Limit.new(Nodes.build_quoted(limit)) if limit
<add> self
<add> end
<add>
<add> def order(*expr)
<add> @ast.orders = expr
<add> self
<add> end
<add>
<add> def key=(key)
<add> @ast.key = Nodes.build_quoted(key)
<add> end
<add>
<add> def key
<add> @ast.key
<add> end
<add>
<add> def wheres=(exprs)
<add> @ast.wheres = exprs
<add> end
<add>
<add> def where(expr)
<add> @ast.wheres << expr
<add> self
<add> end
<add> end
<add>
<ide> attr_reader :ast
<ide>
<ide> def initialize
<ide><path>activerecord/lib/arel/update_manager.rb
<ide>
<ide> module Arel # :nodoc: all
<ide> class UpdateManager < Arel::TreeManager
<add> include TreeManager::StatementMethods
<add>
<ide> def initialize
<ide> super
<ide> @ast = Nodes::UpdateStatement.new
<ide> @ctx = @ast
<ide> end
<ide>
<del> def take(limit)
<del> @ast.limit = Nodes::Limit.new(Nodes.build_quoted(limit)) if limit
<del> self
<del> end
<del>
<del> def key=(key)
<del> @ast.key = Nodes.build_quoted(key)
<del> end
<del>
<del> def key
<del> @ast.key
<del> end
<del>
<del> def order(*expr)
<del> @ast.orders = expr
<del> self
<del> end
<del>
<ide> ###
<ide> # UPDATE +table+
<ide> def table(table)
<ide> @ast.relation = table
<ide> self
<ide> end
<ide>
<del> def wheres=(exprs)
<del> @ast.wheres = exprs
<del> end
<del>
<del> def where(expr)
<del> @ast.wheres << expr
<del> self
<del> end
<del>
<ide> def set(values)
<ide> if String === values
<ide> @ast.values = [values]
<ide><path>activerecord/lib/arel/visitors/mysql.rb
<ide> def visit_Arel_Nodes_UpdateStatement(o, collector)
<ide> collector = inject_join o.values, collector, ", "
<ide> end
<ide>
<add> collect_where_for(o, collector)
<add> end
<add>
<add> def visit_Arel_Nodes_Concat(o, collector)
<add> collector << " CONCAT("
<add> visit o.left, collector
<add> collector << ", "
<add> visit o.right, collector
<add> collector << ") "
<add> collector
<add> end
<add>
<add> def collect_where_for(o, collector)
<ide> unless o.wheres.empty?
<ide> collector << " WHERE "
<ide> collector = inject_join o.wheres, collector, " AND "
<ide> def visit_Arel_Nodes_UpdateStatement(o, collector)
<ide>
<ide> maybe_visit o.limit, collector
<ide> end
<del>
<del> def visit_Arel_Nodes_Concat(o, collector)
<del> collector << " CONCAT("
<del> visit o.left, collector
<del> collector << ", "
<del> visit o.right, collector
<del> collector << ") "
<del> collector
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/arel/visitors/to_sql.rb
<ide> def compile(node, collector = Arel::Collectors::SQLString.new)
<ide> def visit_Arel_Nodes_DeleteStatement(o, collector)
<ide> collector << "DELETE FROM "
<ide> collector = visit o.relation, collector
<del> if o.wheres.any?
<del> collector << WHERE
<del> collector = inject_join o.wheres, collector, AND
<del> end
<ide>
<del> maybe_visit o.limit, collector
<add> collect_where_for(o, collector)
<ide> end
<ide>
<ide> # FIXME: we should probably have a 2-pass visitor for this
<ide> def build_subselect(key, o)
<ide> end
<ide>
<ide> def visit_Arel_Nodes_UpdateStatement(o, collector)
<del> if o.orders.empty? && o.limit.nil?
<del> wheres = o.wheres
<del> else
<del> wheres = [Nodes::In.new(o.key, [build_subselect(o.key, o)])]
<del> end
<del>
<ide> collector << "UPDATE "
<ide> collector = visit o.relation, collector
<ide> unless o.values.empty?
<ide> collector << " SET "
<ide> collector = inject_join o.values, collector, ", "
<ide> end
<ide>
<del> unless wheres.empty?
<del> collector << " WHERE "
<del> collector = inject_join wheres, collector, " AND "
<del> end
<del>
<del> collector
<add> collect_where_for(o, collector)
<ide> end
<ide>
<ide> def visit_Arel_Nodes_InsertStatement(o, collector)
<ide> def inject_join(list, collector, join_str)
<ide> }
<ide> end
<ide>
<add> def collect_where_for(o, collector)
<add> if o.orders.empty? && o.limit.nil?
<add> wheres = o.wheres
<add> else
<add> wheres = [Nodes::In.new(o.key, [build_subselect(o.key, o)])]
<add> end
<add>
<add> unless wheres.empty?
<add> collector << " WHERE "
<add> collector = inject_join wheres, collector, " AND "
<add> end
<add>
<add> collector
<add> end
<add>
<ide> def infix_value(o, collector, value)
<ide> collector = visit o.left, collector
<ide> collector << value
<ide><path>activerecord/test/cases/arel/delete_manager_test.rb
<ide> class DeleteManagerTest < Arel::Spec
<ide> dm = Arel::DeleteManager.new
<ide> dm.take 10
<ide> dm.from table
<add> dm.key = table[:id]
<ide> assert_match(/LIMIT 10/, dm.to_sql)
<ide> end
<ide> | 9 |
PHP | PHP | use full class instead of self for callable | 375afa5afe724870a965531777c9c3a12b360845 | <ide><path>src/Utility/Hash.php
<ide> public static function check(array $data, string $path): bool
<ide> * @return array Filtered array
<ide> * @link https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::filter
<ide> */
<del> public static function filter(array $data, $callback = ['self', '_filter']): array
<add> public static function filter(array $data, $callback = [Hash::class, '_filter']): array
<ide> {
<ide> foreach ($data as $k => $v) {
<ide> if (is_array($v)) { | 1 |
Ruby | Ruby | fix ap test suite after moving stuff to av | 8c2c95e5d22d5e1ebade26f6eeaeda5089e4f658 | <ide><path>actionpack/lib/abstract_controller.rb
<ide> module AbstractController
<ide> autoload :Base
<ide> autoload :Callbacks
<ide> autoload :Collector
<add> autoload :DoubleRenderError, "abstract_controller/rendering.rb"
<ide> autoload :Helpers
<ide> autoload :Logger
<ide> autoload :Translation
<ide><path>actionpack/lib/action_controller/base.rb
<ide> def self.without_modules(*modules)
<ide> end
<ide>
<ide> MODULES = [
<add> ActionView::Layouts,
<ide> AbstractController::Translation,
<ide> AbstractController::AssetPaths,
<ide>
<ide><path>actionpack/test/abstract/abstract_controller_test.rb
<ide> class TestBasic < ActiveSupport::TestCase
<ide> # Test Render mixin
<ide> # ====
<ide> class RenderingController < AbstractController::Base
<del> include AbstractController::Rendering
<add> include ActionView::Rendering
<ide>
<ide> def _prefixes
<ide> []
<ide> def setup
<ide> # ====
<ide> # self._layout is used when defined
<ide> class WithLayouts < PrefixedViews
<del> include AbstractController::Layouts
<add> include ActionView::Layouts
<ide>
<ide> private
<ide> def self.layout(formats)
<ide><path>actionpack/test/abstract/helper_test.rb
<ide> module AbstractController
<ide> module Testing
<ide>
<ide> class ControllerWithHelpers < AbstractController::Base
<del> include AbstractController::Rendering
<add> include ActionView::Rendering
<ide> include AbstractController::Helpers
<ide>
<ide> def with_module
<ide><path>actionpack/test/abstract/layouts_test.rb
<ide> module Layouts
<ide>
<ide> # Base controller for these tests
<ide> class Base < AbstractController::Base
<del> include AbstractController::Rendering
<del> include AbstractController::Layouts
<add> include ActionView::Rendering
<add> include ActionView::Layouts
<ide>
<ide> abstract!
<ide>
<ide><path>actionpack/test/abstract/render_test.rb
<ide> module AbstractController
<ide> module Testing
<ide>
<ide> class ControllerRenderer < AbstractController::Base
<del> include AbstractController::Rendering
<add> include ActionView::Rendering
<ide>
<ide> def _prefixes
<ide> %w[renderer]
<ide><path>actionpack/test/abstract_unit.rb
<ide> def assert_header(name, value)
<ide> module ActionController
<ide> class Base
<ide> include ActionController::Testing
<add> include ActionView::Layouts
<ide> # This stub emulates the Railtie including the URL helpers from a Rails application
<ide> include SharedTestRoutes.url_helpers
<ide> include SharedTestRoutes.mounted_helpers | 7 |
PHP | PHP | fix missing base path in httpsenforcermiddleware | a8d2db674b68991ffe5f4c8289139e557e75e988 | <ide><path>src/Http/Middleware/HttpsEnforcerMiddleware.php
<ide> public function process(ServerRequestInterface $request, RequestHandlerInterface
<ide>
<ide> if ($this->config['redirect'] && $request->getMethod() === 'GET') {
<ide> $uri = $request->getUri()->withScheme('https');
<add> $base = $request->getAttribute('base');
<add> if ($base) {
<add> $uri = $uri->withPath($base . $uri->getPath());
<add> }
<ide>
<ide> return new RedirectResponse(
<ide> $uri,
<ide><path>tests/TestCase/Http/Middleware/HttpsEnforcerMiddlewareTest.php
<ide> public function testRedirect(): void
<ide> );
<ide> }
<ide>
<add> public function testRedirectBasePath(): void
<add> {
<add> $request = new ServerRequest([
<add> 'url' => '/articles',
<add> 'base' => '/base',
<add> 'method' => 'GET',
<add> ]);
<add>
<add> $handler = new TestRequestHandler(function () {
<add> return new Response();
<add> });
<add>
<add> $middleware = new HttpsEnforcerMiddleware();
<add>
<add> $result = $middleware->process($request, $handler);
<add> $this->assertInstanceOf(RedirectResponse::class, $result);
<add> $this->assertSame(301, $result->getStatusCode());
<add> $this->assertEquals(['location' => ['https://localhost/base/articles']], $result->getHeaders());
<add> }
<add>
<ide> /**
<ide> * Test that exception is thrown when redirect is disabled.
<ide> */ | 2 |
Ruby | Ruby | remove postgresql and mysql audit noise | 816531e28dd476f5f266e3327f0b73b11c23e9ce | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_deps
<ide> problem <<-EOS.undent unless dep.tags.any? || f.name =~ /automake/ && dep.name == 'autoconf'
<ide> #{dep} dependency should be "depends_on '#{dep}' => :build"
<ide> EOS
<del> when "git", "ruby", "emacs", "mysql", "mercurial"
<add> when "git", "ruby", "emacs", "mercurial"
<ide> problem <<-EOS.undent
<ide> Don't use #{dep} as a dependency. We allow non-Homebrew
<ide> #{dep} installations.
<ide> def audit_deps
<ide> that works with brewed and system Python and allows us to support
<ide> bindings for 2.x and 3.x in parallel and much more.
<ide> EOS
<del> when "postgresql"
<del> # Postgis specifically requires a Homebrewed postgresql
<del> unless f.name == "postgis"
<del> problem <<-EOS.undent
<del> Don't use #{dep} as a dependency. We allow non-Homebrew
<del> #{dep} installations.
<del> EOS
<del> end
<ide> when 'gfortran'
<ide> problem "Use ENV.fortran during install instead of depends_on 'gfortran'"
<ide> when 'open-mpi', 'mpich2' | 1 |
Ruby | Ruby | move caching module to abstract controller | 40fa818580a9277d8d1a02241f1422dbf83a8aa1 | <ide><path>actionmailer/lib/action_mailer.rb
<ide> module ActionMailer
<ide> autoload :MailHelper
<ide> autoload :Preview
<ide> autoload :Previews, 'action_mailer/preview'
<del> autoload :Caching
<ide> autoload :TestCase
<ide> autoload :TestHelper
<ide> autoload :MessageDelivery
<ide><path>actionmailer/lib/action_mailer/base.rb
<ide>
<ide> require 'action_mailer/log_subscriber'
<ide>
<del>require 'action_dispatch/caching'
<del>
<ide> module ActionMailer
<ide> # Action Mailer allows you to send email from your application using a mailer model and views.
<ide> #
<ide> class Base < AbstractController::Base
<ide> include AbstractController::Translation
<ide> include AbstractController::AssetPaths
<ide> include AbstractController::Callbacks
<del> include ActionDispatch::Caching
<add> include AbstractController::Caching
<ide>
<ide> include ActionView::Layouts
<ide>
<ide><path>actionpack/lib/abstract_controller.rb
<ide> module AbstractController
<ide> extend ActiveSupport::Autoload
<ide>
<ide> autoload :Base
<add> autoload :Caching
<ide> autoload :Callbacks
<ide> autoload :Collector
<ide> autoload :DoubleRenderError, "abstract_controller/rendering"
<ide> module AbstractController
<ide> autoload :Translation
<ide> autoload :AssetPaths
<ide> autoload :UrlFor
<add>
<add> def self.eager_load!
<add> super
<add> AbstractController::Caching.eager_load!
<add> end
<ide> end
<add><path>actionpack/lib/abstract_controller/caching.rb
<del><path>actionpack/lib/action_dispatch/caching.rb
<del>require 'action_dispatch/caching/fragments'
<del>
<del>module ActionDispatch
<add>module AbstractController
<ide> module Caching
<ide> extend ActiveSupport::Concern
<ide> extend ActiveSupport::Autoload
<ide>
<add> eager_autoload do
<add> autoload :Fragments
<add> end
<add>
<ide> module ConfigMethods
<ide> def cache_store
<ide> config.cache_store
<ide> def cache_configured?
<ide> end
<ide>
<ide> include ConfigMethods
<del> include ActionDispatch::Caching::Fragments
<add> include AbstractController::Caching::Fragments
<ide>
<ide> included do
<ide> extend ConfigMethods
<add><path>actionpack/lib/abstract_controller/caching/fragments.rb
<del><path>actionpack/lib/action_dispatch/caching/fragments.rb
<del>module ActionDispatch
<add>module AbstractController
<ide> module Caching
<ide> # Fragment caching is used for caching various blocks within
<ide> # views without caching the entire action as a whole. This is
<ide><path>actionpack/lib/action_controller.rb
<ide> module ActionController
<ide>
<ide> autoload :API
<ide> autoload :Base
<del> autoload :Caching
<ide> autoload :Metal
<ide> autoload :Middleware
<ide> autoload :Renderer
<ide> autoload :FormBuilder
<ide>
<add> eager_autoload do
<add> autoload :Caching
<add> end
<add>
<ide> autoload_under "metal" do
<ide> autoload :ConditionalGet
<ide> autoload :Cookies
<ide> module ActionController
<ide>
<ide> autoload :TestCase, 'action_controller/test_case'
<ide> autoload :TemplateAssertions, 'action_controller/test_case'
<del>
<del> def self.eager_load!
<del> super
<del> ActionController::Caching.eager_load!
<del> end
<ide> end
<ide>
<ide> # Common Active Support usage in Action Controller
<ide><path>actionpack/lib/action_controller/caching.rb
<del>require 'action_dispatch/caching'
<del>
<ide> module ActionController
<ide> # \Caching is a cheap way of speeding up slow applications by keeping the result of
<ide> # calculations, renderings, and database calls around for subsequent requests.
<ide> module Caching
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> include ActionDispatch::Caching
<add> include AbstractController::Caching
<ide> end
<ide>
<ide> def instrument_payload(key) | 7 |
Text | Text | add guide for html value attribute challenge | 7573252fa05438dfb5dbd46301a8cb77a6e44b6d | <ide><path>guide/english/certifications/responsive-web-design/basic-html-and-html5/use-the-value-attribute-with-radio-buttons-and-checkboxes/index.md
<add>---
<add>title: Use the value attribute with Radio Buttons and Checkboxes
<add>---
<add>## Use the value attribute with Radio Buttons and Checkboxes
<add>To pass the challenge, add the `value` attribute to the `input` elements of type `checkbox` and `radio`. Use the `input` label text, in lowercase, as the value for the attribute. The `value` attribute will make sure the choices are identifiable when the form is submitted.
<add>
<add>Example form with value attributes:
<add>```html
<add><form action="/submit-sandwich">
<add>
<add> <label><input type="radio" name="bread" value="wheat"> Wheat</label>
<add> <label><input type="radio" name="bread" value="ciabatta"> Ciabatta</label><br>
<add>
<add> <label><input type="checkbox" name="fillings" value="chicken"> Chicken</label>
<add> <label><input type="checkbox" name="fillings" value="tuna"> Tuna</label>
<add> <label><input type="checkbox" name="fillings" value="mayo"> Mayo</label><br>
<add>
<add> <textarea placeholder="Allergies, and extra information"></textarea><br>
<add>
<add> <button type="submit">Order Sandwich</button>
<add></form>
<add>```
<ide>\ No newline at end of file | 1 |
Javascript | Javascript | use class fields in observe.js | c37fdacb348fa8f735f0c01fdfb0eefe6152dd34 | <ide><path>lib/internal/perf/observe.js
<ide> const {
<ide>
<ide> const { inspect } = require('util');
<ide>
<del>const kBuffer = Symbol('kBuffer');
<del>const kCallback = Symbol('kCallback');
<ide> const kDispatch = Symbol('kDispatch');
<del>const kEntryTypes = Symbol('kEntryTypes');
<ide> const kMaybeBuffer = Symbol('kMaybeBuffer');
<ide> const kDeprecatedFields = Symbol('kDeprecatedFields');
<del>const kType = Symbol('kType');
<ide>
<ide> const kDeprecationMessage =
<ide> 'Custom PerformanceEntry accessors are deprecated. ' +
<ide> function maybeIncrementObserverCount(type) {
<ide> }
<ide>
<ide> class PerformanceObserverEntryList {
<add> #buffer = [];
<add>
<ide> constructor(entries) {
<del> this[kBuffer] = ArrayPrototypeSort(entries, (first, second) => {
<add> this.#buffer = ArrayPrototypeSort(entries, (first, second) => {
<ide> return first.startTime - second.startTime;
<ide> });
<ide> }
<ide>
<ide> getEntries() {
<del> return ArrayPrototypeSlice(this[kBuffer]);
<add> return ArrayPrototypeSlice(this.#buffer);
<ide> }
<ide>
<ide> getEntriesByType(type) {
<ide> type = `${type}`;
<ide> return ArrayPrototypeFilter(
<del> this[kBuffer],
<add> this.#buffer,
<ide> (entry) => entry.entryType === type);
<ide> }
<ide>
<ide> getEntriesByName(name, type) {
<ide> name = `${name}`;
<ide> if (type != null /** not nullish */) {
<ide> return ArrayPrototypeFilter(
<del> this[kBuffer],
<add> this.#buffer,
<ide> (entry) => entry.name === name && entry.entryType === type);
<ide> }
<ide> return ArrayPrototypeFilter(
<del> this[kBuffer],
<add> this.#buffer,
<ide> (entry) => entry.name === name);
<ide> }
<ide>
<ide> class PerformanceObserverEntryList {
<ide> depth: options.depth == null ? null : options.depth - 1
<ide> };
<ide>
<del> return `PerformanceObserverEntryList ${inspect(this[kBuffer], opts)}`;
<add> return `PerformanceObserverEntryList ${inspect(this.#buffer, opts)}`;
<ide> }
<ide> }
<ide>
<ide> class PerformanceObserver {
<add> #buffer = [];
<add> #entryTypes = new SafeSet();
<add> #type;
<add> #callback;
<add>
<ide> constructor(callback) {
<del> // TODO(joyeecheung): V8 snapshot does not support instance member
<del> // initializers for now:
<del> // https://bugs.chromium.org/p/v8/issues/detail?id=10704
<del> this[kBuffer] = [];
<del> this[kEntryTypes] = new SafeSet();
<del> this[kType] = undefined;
<ide> validateFunction(callback, 'callback');
<del> this[kCallback] = callback;
<add> this.#callback = callback;
<ide> }
<ide>
<ide> observe(options = {}) {
<ide> class PerformanceObserver {
<ide> 'options.entryTypes can not set with ' +
<ide> 'options.type together');
<ide>
<del> switch (this[kType]) {
<add> switch (this.#type) {
<ide> case undefined:
<del> if (entryTypes !== undefined) this[kType] = kTypeMultiple;
<del> if (type !== undefined) this[kType] = kTypeSingle;
<add> if (entryTypes !== undefined) this.#type = kTypeMultiple;
<add> if (type !== undefined) this.#type = kTypeSingle;
<ide> break;
<ide> case kTypeSingle:
<ide> if (entryTypes !== undefined)
<ide> class PerformanceObserver {
<ide> break;
<ide> }
<ide>
<del> if (this[kType] === kTypeMultiple) {
<add> if (this.#type === kTypeMultiple) {
<ide> if (!ArrayIsArray(entryTypes)) {
<ide> throw new ERR_INVALID_ARG_TYPE(
<ide> 'options.entryTypes',
<ide> 'string[]',
<ide> entryTypes);
<ide> }
<del> maybeDecrementObserverCounts(this[kEntryTypes]);
<del> this[kEntryTypes].clear();
<add> maybeDecrementObserverCounts(this.#entryTypes);
<add> this.#entryTypes.clear();
<ide> for (let n = 0; n < entryTypes.length; n++) {
<ide> if (ArrayPrototypeIncludes(kSupportedEntryTypes, entryTypes[n])) {
<del> this[kEntryTypes].add(entryTypes[n]);
<add> this.#entryTypes.add(entryTypes[n]);
<ide> maybeIncrementObserverCount(entryTypes[n]);
<ide> }
<ide> }
<ide> } else {
<ide> if (!ArrayPrototypeIncludes(kSupportedEntryTypes, type))
<ide> return;
<del> this[kEntryTypes].add(type);
<add> this.#entryTypes.add(type);
<ide> maybeIncrementObserverCount(type);
<ide> if (buffered) {
<ide> const entries = filterBufferMapByNameAndType(undefined, type);
<del> ArrayPrototypePushApply(this[kBuffer], entries);
<add> ArrayPrototypePushApply(this.#buffer, entries);
<ide> kPending.add(this);
<ide> if (kPending.size)
<ide> queuePending();
<ide> }
<ide> }
<ide>
<del> if (this[kEntryTypes].size)
<add> if (this.#entryTypes.size)
<ide> kObservers.add(this);
<ide> else
<ide> this.disconnect();
<ide> }
<ide>
<ide> disconnect() {
<del> maybeDecrementObserverCounts(this[kEntryTypes]);
<add> maybeDecrementObserverCounts(this.#entryTypes);
<ide> kObservers.delete(this);
<ide> kPending.delete(this);
<del> this[kBuffer] = [];
<del> this[kEntryTypes].clear();
<del> this[kType] = undefined;
<add> this.#buffer = [];
<add> this.#entryTypes.clear();
<add> this.#type = undefined;
<ide> }
<ide>
<ide> takeRecords() {
<del> const list = this[kBuffer];
<del> this[kBuffer] = [];
<add> const list = this.#buffer;
<add> this.#buffer = [];
<ide> return list;
<ide> }
<ide>
<ide> class PerformanceObserver {
<ide> }
<ide>
<ide> [kMaybeBuffer](entry) {
<del> if (!this[kEntryTypes].has(entry.entryType))
<add> if (!this.#entryTypes.has(entry.entryType))
<ide> return;
<del> ArrayPrototypePush(this[kBuffer], entry);
<add> ArrayPrototypePush(this.#buffer, entry);
<ide> kPending.add(this);
<ide> if (kPending.size)
<ide> queuePending();
<ide> }
<ide>
<ide> [kDispatch]() {
<del> this[kCallback](new PerformanceObserverEntryList(this.takeRecords()),
<del> this);
<add> this.#callback(new PerformanceObserverEntryList(this.takeRecords()),
<add> this);
<ide> }
<ide>
<ide> [kInspect](depth, options) {
<ide> class PerformanceObserver {
<ide> return `PerformanceObserver ${inspect({
<ide> connected: kObservers.has(this),
<ide> pending: kPending.has(this),
<del> entryTypes: ArrayFrom(this[kEntryTypes]),
<del> buffer: this[kBuffer],
<add> entryTypes: ArrayFrom(this.#entryTypes),
<add> buffer: this.#buffer,
<ide> }, opts)}`;
<ide> }
<ide> } | 1 |
Text | Text | add rvagg to the tc | ac1fb39ce81373c161b4c7f873f96ae1830b0875 | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B
<ide> * **Colin Ihrig** ([@cjihrig](https://github.com/cjihrig)) <cjihrig@gmail.com>
<ide> * **Mikeal Rogers** ([@mikeal](https://github.com/mikeal)) <mikeal.rogers@gmail.com>
<del>* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org>
<add>* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org> (Technical Committee)
<ide> - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D
<ide> * **Thorsten Lorenz** ([@thlorenz](https://github.com/thlorenz)) <thlorenz@gmx.de>
<ide> * **Stephen Belanger** ([@qard](https://github.com/qard)) <admin@stephenbelanger.com> | 1 |
Ruby | Ruby | add options to field_set_tag | 8c105ee0c888a63cdbf593f0bfe688065b3e09e2 | <ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb
<ide> def image_submit_tag(source, options = {})
<ide> # Creates a field set for grouping HTML form elements.
<ide> #
<ide> # <tt>legend</tt> will become the fieldset's title (optional as per W3C).
<add> # <tt>options</tt> accept the same values as tag.
<ide> #
<ide> # === Examples
<ide> # <% field_set_tag do %>
<ide> def image_submit_tag(source, options = {})
<ide> # <p><%= text_field_tag 'name' %></p>
<ide> # <% end %>
<ide> # # => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset>
<del> def field_set_tag(legend = nil, &block)
<add> #
<add> # <% field_set_tag nil, :class => 'format' do %>
<add> # <p><%= text_field_tag 'name' %></p>
<add> # <% end %>
<add> # # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset>
<add> def field_set_tag(legend = nil, options = nil, &block)
<ide> content = capture(&block)
<del> concat(tag(:fieldset, {}, true))
<add> concat(tag(:fieldset, options, true))
<ide> concat(content_tag(:legend, legend)) unless legend.blank?
<ide> concat(content)
<ide> concat("</fieldset>")
<ide><path>actionpack/test/template/form_tag_helper_test.rb
<ide> def test_field_set_tag_in_erb
<ide>
<ide> expected = %(<fieldset>Hello world!</fieldset>)
<ide> assert_dom_equal expected, output_buffer
<add>
<add> self.output_buffer = ''
<add> field_set_tag('', :class => 'format') { concat "Hello world!" }
<add>
<add> expected = %(<fieldset class="format">Hello world!</fieldset>)
<add> assert_dom_equal expected, output_buffer
<ide> end
<ide>
<ide> def protect_against_forgery? | 2 |
Javascript | Javascript | write otf header using a string, not an array | f337d6105c304b7af66585626c268fb335b33517 | <ide><path>fonts.js
<ide> var Font = (function () {
<ide> convert: function font_convert(aFont, aProperties) {
<ide> var otf = new Uint8Array(kMaxFontFileSize);
<ide>
<del> function createOpenTypeHeader(aFile, aOffsets, aNumTables) {
<add> function s2a(s) {
<add> var a = [];
<add> for (var i = 0; i < s.length; ++i)
<add> a[i] = s.charCodeAt(i);
<add> return a;
<add> }
<add>
<add> function createOpenTypeHeader(aFile, aOffsets, numTables) {
<add> var header = "";
<add>
<add> function WriteHeader16(value) {
<add> header += String.fromCharCode(value >> 8);
<add> header += String.fromCharCode(value & 0xff);
<add> }
<add>
<ide> // sfnt version (4 bytes)
<del> var version = [0x4F, 0x54, 0x54, 0X4F];
<add> header += "\x4F\x54\x54\x4F";
<ide>
<ide> // numTables (2 bytes)
<del> var numTables = aNumTables;
<add> WriteHeader16(numTables);
<ide>
<ide> // searchRange (2 bytes)
<ide> var tablesMaxPower2 = FontsUtils.getMaxPower2(numTables);
<ide> var searchRange = tablesMaxPower2 * 16;
<add> WriteHeader16(searchRange);
<ide>
<ide> // entrySelector (2 bytes)
<del> var entrySelector = Math.log(tablesMaxPower2) / Math.log(2);
<add> WriteHeader16(Math.log(tablesMaxPower2) / Math.log(2));
<ide>
<ide> // rangeShift (2 bytes)
<del> var rangeShift = numTables * 16 - searchRange;
<del>
<del> var header = [].concat(version,
<del> FontsUtils.integerToBytes(numTables, 2),
<del> FontsUtils.integerToBytes(searchRange, 2),
<del> FontsUtils.integerToBytes(entrySelector, 2),
<del> FontsUtils.integerToBytes(rangeShift, 2));
<del> aFile.set(header, aOffsets.currentOffset);
<add> WriteHeader16(numTables * 16 - searchRange);
<add>
<add> aFile.set(s2a(header), aOffsets.currentOffset);
<ide> aOffsets.currentOffset += header.length;
<ide> aOffsets.virtualOffset += header.length;
<ide> } | 1 |
Ruby | Ruby | require arg for --root-url | 7116b74705589f846428b1af4e0db7ca9feb0302 | <ide><path>Library/Homebrew/dev-cmd/bottle.rb
<ide> def bottle_args
<ide> depends_on: "--write",
<ide> description: "When passed with `--write`, a new commit will not generated after writing changes "\
<ide> "to the formula file."
<del> flag "--root-url",
<add> flag "--root-url=",
<ide> description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default."
<ide> switch :verbose
<ide> switch :debug
<ide><path>Library/Homebrew/test/dev-cmd/bottle_spec.rb
<ide> .and not_to_output.to_stdout
<ide> .and be_a_failure
<ide>
<add> expect { brew "bottle", "--root-url" }
<add> .to output(/missing argument: --root-url/).to_stderr
<add> .and not_to_output.to_stdout
<add> .and be_a_failure
<add>
<ide> setup_test_formula "testball"
<ide>
<ide> # `brew bottle` should not fail with dead symlink | 2 |
Ruby | Ruby | specify order by enumsortorder for postgres enums | 9b73129c3e1158fb922927399095327b1807489d | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def enum_types
<ide> query = <<~SQL
<ide> SELECT
<ide> type.typname AS name,
<del> string_agg(enum.enumlabel, ',') AS value
<add> string_agg(enum.enumlabel, ',' ORDER BY enum.enumsortorder) AS value
<ide> FROM pg_enum AS enum
<ide> JOIN pg_type AS type
<ide> ON (type.oid = enum.enumtypid) | 1 |
Python | Python | fix failing pylint checks | 5117aaa797e2f6c76912ddcee1fe91bde5b51d83 | <ide><path>airflow/utils/serve_logs.py
<ide> import os
<ide>
<ide> import flask
<del>from setproctitle import setproctitle
<add>from setproctitle import setproctitle # pylint: disable=no-name-in-module
<ide>
<ide> from airflow.configuration import conf
<ide> | 1 |
Text | Text | fix typo in document | 4e557b6c6d64b495dd754c706b19a619714e1f0d | <ide><path>guides/source/active_record_querying.md
<ide> SELECT * FROM customers WHERE (customers.orders_count NOT IN (1,3,5))
<ide> If a query has a hash condition with non-nil values on a nullable column, the records that have `nil` values on the nullable column won't be returned. For example:
<ide>
<ide> ```ruby
<del>Customer.create!(nullable_contry: nil)
<add>Customer.create!(nullable_country: nil)
<ide> Customer.where.not(nullable_country: "UK")
<ide> => []
<ide> # But
<del>Customer.create!(nullable_contry: "UK")
<add>Customer.create!(nullable_country: "UK")
<ide> Customer.where.not(nullable_country: nil)
<del>=> [#<Customer id: 2, nullable_contry: "UK">]
<add>=> [#<Customer id: 2, nullable_country: "UK">]
<ide> ```
<ide>
<ide> [`where.not`]: https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods/WhereChain.html#method-i-not | 1 |
Ruby | Ruby | use templatepath in digestor | 54f8d0b2696a9a557249a8f1f1b071b427a88568 | <ide><path>actionview/lib/action_view/digestor.rb
<ide> def digest(name:, format: nil, finder:, dependencies: nil)
<ide> # (Concurrent::Map's lookups have volatile semantics)
<ide> finder.digest_cache[cache_key] || @@digest_mutex.synchronize do
<ide> finder.digest_cache.fetch(cache_key) do # re-check under lock
<del> partial = name.include?("/_")
<del> root = tree(name, finder, partial)
<add> path = TemplatePath.parse(name)
<add> root = tree(path.to_s, finder, path.partial?)
<ide> dependencies.each do |injected_dep|
<ide> root.children << Injected.new(injected_dep, nil, nil)
<ide> end if dependencies
<ide> def tree(name, finder, partial = false, seen = {})
<ide> logical_name = name.gsub(%r|/_|, "/")
<ide> interpolated = name.include?("#")
<ide>
<del> if !interpolated && (template = find_template(finder, logical_name, [], partial, []))
<add> path = TemplatePath.parse(name)
<add>
<add> if !interpolated && (template = find_template(finder, path.name, [path.prefix], partial, []))
<ide> if node = seen[template.identifier] # handle cycles in the tree
<ide> node
<ide> else | 1 |
Python | Python | add better error message for model.summary() | 32fee92df5fa21e3d1ff6375f7a5a923636c311b | <ide><path>keras/engine/network.py
<ide> def summary(self, line_length=None, positions=None, print_fn=None):
<ide> """
<ide> if not self.built:
<ide> raise ValueError(
<del> 'This model has never been called, thus its weights '
<del> 'have not yet been created, so no summary can be displayed. '
<del> 'Build the model first '
<del> '(e.g. by calling it on some test data).')
<add> 'This model has not yet been built. '
<add> 'Build the model first by calling build() or calling fit() with some data. '
<add> 'Or specify input_shape or batch_input_shape in the first layer for automatic build. ')
<ide> return print_layer_summary(self,
<ide> line_length=line_length,
<ide> positions=positions, | 1 |
Javascript | Javascript | add a small amount to docs | 16cf465575325bf21a94d2a345d8bf4d9d097f11 | <ide><path>Chart.js
<ide> // Boolean - whether or not the chart should be responsive and resize when the browser does.
<ide> responsive: false,
<ide>
<del> // Boolean - whether to maintain the starting aspect ratio or not when responsive
<add> // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
<ide> maintainAspectRatio: true,
<ide>
<ide> // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
<ide><path>src/Chart.Core.js
<ide> // Boolean - whether or not the chart should be responsive and resize when the browser does.
<ide> responsive: false,
<ide>
<del> // Boolean - whether to maintain the starting aspect ratio or not when responsive
<add> // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
<ide> maintainAspectRatio: true,
<ide>
<ide> // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove | 2 |
Ruby | Ruby | return an empty array if no tracker is found | 445284906476f03acf37cab2b7dc265a985531c3 | <ide><path>actionpack/lib/action_view/dependency_tracker.rb
<ide> class DependencyTracker
<ide> @trackers = ThreadSafe::Cache.new
<ide>
<ide> def self.find_dependencies(name, template)
<del> handler = template.handler
<del> @trackers.fetch(handler).call(name, template)
<add> tracker = @trackers[template.handler]
<add>
<add> if tracker.present?
<add> tracker.call(name, template)
<add> else
<add> []
<add> end
<ide> end
<ide>
<ide> def self.register_tracker(handler, tracker)
<ide><path>actionpack/test/template/dependency_tracker_test.rb
<ide>
<ide> class DependencyTrackerTest < ActionView::TestCase
<ide> Neckbeard = Class.new
<add> Bowtie = Class.new
<ide>
<ide> class NeckbeardTracker
<ide> def self.call(name, template)
<ide> def self.call(name, template)
<ide> class FakeTemplate
<ide> attr_reader :source, :handler
<ide>
<del> def initialize(source)
<del> @source, @handler = source, Neckbeard
<add> def initialize(source, handler = Neckbeard)
<add> @source, @handler = source, handler
<ide> end
<ide> end
<ide>
<ide> def test_finds_tracker_by_template_handler
<ide> dependencies = tracker.find_dependencies("boo/hoo", template)
<ide> assert_equal ["foo/boo/hoo"], dependencies
<ide> end
<add>
<add> def test_returns_empty_array_if_no_tracker_is_found
<add> template = FakeTemplate.new("boo/hoo", Bowtie)
<add> dependencies = tracker.find_dependencies("boo/hoo", template)
<add> assert_equal [], dependencies
<add> end
<ide> end | 2 |
Text | Text | improve changelog entry [ci skip] | 974335d4d0635bab660413b4533d8f6c5eb1aac0 | <ide><path>actionview/CHANGELOG.md
<del>* Only cache template digests if config.cache_template_loading, since
<del> ActionView::Resolver.caching is set to the same value as
<del> config.cache_template_loading
<add>* Only cache template digests if `config.cache_template_loading` id true.
<ide>
<del> *Josh Lauer* *Justin Ridgewell*
<add> *Josh Lauer*, *Justin Ridgewell*
<ide>
<ide> * Added an `extname` hash option for `javascript_include_tag` method.
<ide> | 1 |
Go | Go | modify usage of docker exec command in exec.md | 26bd3e8b11dd9ef9a8226341ed04cbc8a58776cc | <ide><path>api/client/container/exec.go
<ide> func NewExecCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide> var opts execOptions
<ide>
<ide> cmd := &cobra.Command{
<del> Use: "exec CONTAINER COMMAND [ARG...]",
<add> Use: "exec [OPTIONS] CONTAINER COMMAND [ARG...]",
<ide> Short: "Run a command in a running container",
<ide> Args: cli.RequiresMinArgs(2),
<ide> RunE: func(cmd *cobra.Command, args []string) error { | 1 |
Javascript | Javascript | append bundle script to body (#353) | 249a0c40078d88308e84401cc195856068df4d6b | <ide><path>lib/document.js
<ide> function createClientScript ({ dev, cdn }) {
<ide> script.onload = function () { fn(null) }
<ide> script.onerror = fn
<ide> script.crossorigin = 'anonymous'
<del> document.head.appendChild(script)
<add> document.body.appendChild(script)
<ide> }
<ide> })()
<ide> `}} /> | 1 |
Javascript | Javascript | fix error message | 922985bbe75a01387e9f1bea6a132174fbc783d1 | <ide><path>lib/JavascriptModulesPlugin.js
<ide> class JavascriptModulesPlugin {
<ide> static getCompilationHooks(compilation) {
<ide> if (!(compilation instanceof Compilation)) {
<ide> throw new TypeError(
<del> "The 'compilation' argument must be an instance of JavascriptParser"
<add> "The 'compilation' argument must be an instance of Compilation"
<ide> );
<ide> }
<ide> let hooks = compilationHooksMap.get(compilation);
<ide><path>lib/wasm-async/AsyncWebAssemblyModulesPlugin.js
<ide> class AsyncWebAssemblyModulesPlugin {
<ide> static getCompilationHooks(compilation) {
<ide> if (!(compilation instanceof Compilation)) {
<ide> throw new TypeError(
<del> "The 'compilation' argument must be an instance of JavascriptParser"
<add> "The 'compilation' argument must be an instance of Compilation"
<ide> );
<ide> }
<ide> let hooks = compilationHooksMap.get(compilation); | 2 |
Python | Python | add gpu to the unitest | 12412caf56dee8b296d500e201ad6b770eaf2f91 | <ide><path>glances/plugins/glances_help.py
<ide> def __init__(self, args=None, config=None):
<ide> self.view_data = {}
<ide> self.generate_view_data()
<ide>
<add> def reset(self):
<add> """No stats. It is just a plugin to display the help."""
<add> pass
<add>
<ide> def update(self):
<ide> """No stats. It is just a plugin to display the help."""
<ide> pass
<ide><path>glances/plugins/glances_now.py
<ide> def __init__(self, args=None):
<ide> # Set the message position
<ide> self.align = 'bottom'
<ide>
<add> def reset(self):
<add> """Reset/init the stats."""
<add> self.stats = ''
<add>
<ide> def update(self):
<ide> """Update current date/time."""
<ide> # Had to convert it to string because datetime is not JSON serializable
<ide><path>glances/plugins/glances_ports.py
<ide> def exit(self):
<ide> # Call the father class
<ide> super(Plugin, self).exit()
<ide>
<add> def reset(self):
<add> """Reset/init the stats."""
<add> self.stats = []
<add>
<ide> @GlancesPlugin._log_result_decorator
<ide> def update(self):
<ide> """Update the ports list."""
<ide><path>unitest.py
<ide> def test_013_irq(self):
<ide> self.assertTrue(type(stats_grab) is list, msg='IRQ stats is not a list')
<ide> print('INFO: IRQ stats: %s' % stats_grab)
<ide>
<add> @unittest.skipIf(not LINUX, "GPU available only on Linux")
<add> def test_013_gpu(self):
<add> """Check GPU plugin."""
<add> print('INFO: [TEST_014] Check GPU stats')
<add> stats_grab = stats.get_plugin('gpu').get_raw()
<add> self.assertTrue(type(stats_grab) is list, msg='GPU stats is not a list')
<add> print('INFO: GPU stats: %s' % stats_grab)
<add>
<add> def test_095_methods(self):
<add> """Test mandatories methods"""
<add> print('INFO: [TEST_095] Mandatories methods')
<add> mandatories_methods = ['reset', 'update']
<add> plugins_list = stats.getAllPlugins()
<add> for plugin in plugins_list:
<add> for method in mandatories_methods:
<add> self.assertTrue(hasattr(stats.get_plugin(plugin), method),
<add> msg='{} has no method {}()'.format(plugin, method))
<add>
<ide> def test_096_views(self):
<ide> """Test get_views method"""
<ide> print('INFO: [TEST_096] Test views') | 4 |
Text | Text | add oliver to the platform dev team 🎉 | 4f2a5d05dd0d9a2bb3953ab082f99bd4ed83eac8 | <ide><path>docs/index.md
<ide> Read our [How to Contribute to Open Source Guide](https://github.com/freeCodeCam
<ide>
<ide> ### Where are the Guide articles (guide.freecodecamp.org)?
<ide>
<del>We have sunset the general guide articles.
<add>We have sunset the general guide articles.
<ide>
<del>The guide articles redirect to high quality tutorials on freeCodeCamp news.
<add>The guide articles redirect to high quality tutorials on freeCodeCamp news.
<ide>
<del>The challenge hint articles are available on the freeCodeCamp forum as hint topics. We have updated the links on our curriculum help button to point to the hint topics instead.
<add>The challenge hint articles are available on the freeCodeCamp forum as hint topics. We have updated the links on our curriculum help button to point to the hint topics instead.
<ide>
<ide> ### Can I translate freeCodeCamp's curriculum?
<ide>
<ide> We do intend to make the curriculum available in more languages, but we do not h
<ide>
<ide> China is the largest demographic regions, in our non-native English speaking audience. Currently, we have hundreds of thousands of users using an old version of the platform. This will give us an estimate of logistics involved in the i18n efforts to other languages.
<ide>
<del>We intend to start i18n efforts in these languages post the Chinese language launch:
<add>We intend to start i18n efforts in these languages post the Chinese language launch:
<ide>
<del>Arabic, Portuguese, Russian and Spanish (in no particular order).
<add>Arabic, Portuguese, Russian and Spanish (in no particular order).
<ide>
<del>We will focus on Latin America as the demographic region for Portuguese and Spanish.
<add>We will focus on Latin America as the demographic region for Portuguese and Spanish.
<ide>
<ide> We do not have any plans for i18n to any other languages other than the above for the foreseeable future.
<ide>
<ide> Be polite and patient. Our community of volunteers and moderators are always aro
<ide>
<ide> If you have queries about the stack, architecture of the codebase, feel free to reach out to our staff dev team:
<ide>
<del>| Staff | Send message on Gitter | DM on Twitter |
<del>| :------------------- | :------------------------------------------------------------ | :---------------------------------------------------- |
<del>| Mrugesh Mohapatra | [@raisedadead](https://gitter.im/raisedadead) | [@raisedadead](https://twitter.com/raisedadead) |
<del>| Ahmad Abdolsaheb | [@ahmadabdolsaheb](https://gitter.im/ahmadabdolsaheb) | [@Abdolsaheb](https://twitter.com/Abdolsaheb) |
<del>| Kristofer Koishigawa | [@scissorsneedfoodtoo](https://gitter.im/scissorsneedfoodtoo) | [@kriskoishigawa](https://twitter.com/kriskoishigawa) |
<del>| Tom Mondloc | [@moT01](https://gitter.im/moT01) | - |
<add>| Staff | Send message on Gitter | Send message on Forum |
<add>| :-------------------- | :------------------------------------------------------------ | :------------------------------------------------------------------------------- |
<add>| Mrugesh Mohapatra | [@raisedadead](https://gitter.im/raisedadead) | [@raisedadead](https://www.freecodecamp.org/forum/u/raisedadead) |
<add>| Ahmad Abdolsaheb | [@ahmadabdolsaheb](https://gitter.im/ahmadabdolsaheb) | [@abdolsa](https://www.freecodecamp.org/forum/u/abdolsa) |
<add>| Kristofer Koishigawa | [@scissorsneedfoodtoo](https://gitter.im/scissorsneedfoodtoo) | [@scissorsneedfoodtoo](https://www.freecodecamp.org/forum/u/scissorsneedfoodtoo) |
<add>| Tom Mondloc | [@moT01](https://gitter.im/moT01) | [@moT01](https://www.freecodecamp.org/forum/u/moT01) |
<add>| Oliver Eyton-Williams | [@ojeytonwilliams](https://gitter.im/ojeytonwilliams) | [@ojeytonwilliams](https://www.freecodecamp.org/forum/u/ojeytonwilliams) |
<ide>
<ide> **You can email our developer staff at: `dev[at]freecodecamp.org`** | 1 |
Text | Text | add info about dev vs. prod builds | c877451887d1fc531e7c2637681f47cf50d6a5de | <ide><path>docs/downloads.md
<ide> title: Downloads
<ide> layout: single
<ide> ---
<ide> Download the starter kit to get everything you need to
<del>[get started with React](/react/docs/getting-started.html).
<add>[get started with React](/react/docs/getting-started.html). The starter kit includes React, the in-browser JSX transformer, and some simple example apps.
<ide>
<ide> <div class="buttons-unit downloads">
<ide> <a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
<ide> Download Starter Kit {{site.react_version}}
<ide> </a>
<ide> </div>
<ide>
<del>## Individual Downloads
<add>## Development vs. Production Builds
<ide>
<del>#### <a href="http://fb.me/react-{{site.react_version}}.min.js">React Core {{site.react_version}} (production)</a>
<del>The compressed, production version of React core
<add>We provide two versions of React: an uncompressed version for development and a minified version for production. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages.
<ide>
<del>```html
<del><script src="http://fb.me/react-{{site.react_version}}.min.js"></script>
<del>```
<add>If you're just starting out, make sure to use the development version.
<ide>
<del>#### <a href="http://fb.me/react-{{site.react_version}}.js">React Core {{site.react_version}} (development)</a>
<add>## Individual Downloads
<add>
<add>#### <a href="http://fb.me/react-{{site.react_version}}.js">React {{site.react_version}} (development)</a>
<ide> The uncompressed, development version of React core with inline documentation.
<ide>
<ide> ```html
<ide> <script src="http://fb.me/react-{{site.react_version}}.js"></script>
<ide> ```
<ide>
<del>#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.min.js">React With Add-Ons {{site.react_version}} (production)</a>
<del>The compressed, production version of React with [add-ons](/react/docs/addons.html).
<add>#### <a href="http://fb.me/react-{{site.react_version}}.min.js">React {{site.react_version}} (production)</a>
<add>The compressed, production version of React core.
<ide>
<ide> ```html
<del><script src="http://fb.me/react-with-addons-{{site.react_version}}.min.js"></script>
<add><script src="http://fb.me/react-{{site.react_version}}.min.js"></script>
<ide> ```
<ide>
<del>#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.js">React With Add-Ons {{site.react_version}} (development)</a>
<add>#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.js">React with Add-Ons {{site.react_version}} (development)</a>
<ide> The uncompressed, development version of React with [add-ons](/react/docs/addons.html).
<ide>
<ide> ```html
<ide> <script src="http://fb.me/react-with-addons-{{site.react_version}}.js"></script>
<ide> ```
<ide>
<del>#### <a href="http://fb.me/JSXTransformer-{{site.react_version}}.js">JSX Transform</a>
<add>#### <a href="http://fb.me/react-with-addons-{{site.react_version}}.min.js">React with Add-Ons {{site.react_version}} (production)</a>
<add>The compressed, production version of React with [add-ons](/react/docs/addons.html).
<add>
<add>```html
<add><script src="http://fb.me/react-with-addons-{{site.react_version}}.min.js"></script>
<add>```
<add>
<add>#### <a href="http://fb.me/JSXTransformer-{{site.react_version}}.js">JSX Transformer</a>
<ide> The JSX transformer used to support [XML syntax](/react/docs/jsx-in-depth.html) in JavaScript.
<ide>
<ide> ```html
<ide> <script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<ide> ```
<ide>
<del>All scripts are also available via [CDNJS](http://cdnjs.com/#react).
<add>All scripts are also available via [CDNJS](http://cdnjs.com/libraries/react/).
<ide>
<ide> ## Bower
<ide> | 1 |
PHP | PHP | add docs for meridian | 1d664086a31622075d6cdc20e1af1349bc8acc2a | <ide><path>src/View/Input/DateTime.php
<ide> public function __construct($templates, $selectBox) {
<ide> * - `hour` - Array of options for the hour select box.
<ide> * - `minute` - Array of options for the minute select box.
<ide> * - `second` - Set to true to enable the seconds input. Defaults to false.
<add> * - `meridian` - Set to true to enable the meridian input. Defaults to false.
<add> * The meridian will be enabled automatically if you chose a 12 hour format.
<ide> *
<ide> * @param array $data Data to render with.
<ide> * @return string A generated select box. | 1 |
Javascript | Javascript | add deprecation warning for status-bar | 7fd53202473e019c2fc54eaf93b749aa15151fc5 | <ide><path>Libraries/react-native/react-native-implementation.js
<ide> module.exports = {
<ide> return require('RefreshControl');
<ide> },
<ide> get StatusBar() {
<add> warnOnce(
<add> 'statusbar-moved',
<add> 'StatusBar has been extracted from react-native core and will be removed in a future release. ' +
<add> "It can now be installed and imported from '@react-native-community/status-bar' instead of 'react-native'. " +
<add> 'https://github.com/react-native-community/react-native-statusbar',
<add> );
<ide> return require('StatusBar');
<ide> },
<ide> get SwipeableFlatList() { | 1 |
Ruby | Ruby | add all components | 6c3b8e100f0f3dc23fe6c77cfd049ba126e58e8c | <ide><path>Library/Homebrew/rubocops/components_order_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> [{ name: :bottle, type: :method_call }],
<ide> [{ name: :keg_only, type: :method_call }],
<ide> [{ name: :option, type: :method_call }],
<add> [{ name: :deprecated_option, type: :method_call }],
<ide> [{ name: :depends_on, type: :method_call }],
<ide> [{ name: :conflicts_with, type: :method_call }],
<add> [{ name: :skip_clean, type: :method_call }],
<add> [{ name: :fails_with, type: :method_call }, { name: :fails_with, type: :block_call }],
<ide> [{ name: :go_resource, type: :block_call }, { name: :resource, type: :block_call }],
<add> [{ name: :patch, type: :method_call }, { name: :patch, type: :block_call }],
<add> [{ name: :needs, type: :method_call }],
<ide> [{ name: :install, type: :method_definition }],
<ide> [{ name: :post_install, type: :method_definition }],
<ide> [{ name: :caveats, type: :method_definition }], | 1 |
Java | Java | add simple integration test | e29eaaddc86965fd3cc3124fb7d37b1ef54a90c3 | <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/IntRecordingModule.java
<add>/**
<add> * Copyright (c) 2014-present, Facebook, Inc.
<add> * All rights reserved.
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.testing;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.concurrent.CountDownLatch;
<add>import java.util.concurrent.TimeUnit;
<add>
<add>import com.facebook.react.bridge.BaseJavaModule;
<add>import com.facebook.react.bridge.ReactMethod;
<add>
<add>/**
<add> * Native module provides single method {@link #record} which records its single int argument
<add> * in calls array
<add> */
<add>public class IntRecordingModule extends BaseJavaModule {
<add>
<add> private final List<Integer> mCalls = new ArrayList<>();
<add> private final CountDownLatch mCountDownLatch = new CountDownLatch(1);
<add>
<add> @Override
<add> public String getName() {
<add> return "Recording";
<add> }
<add>
<add> @ReactMethod
<add> public void record(int i) {
<add> mCalls.add(i);
<add> mCountDownLatch.countDown();
<add> }
<add>
<add> public void reset() {
<add> mCalls.clear();
<add> }
<add>
<add> public List<Integer> getCalls() {
<add> return mCalls;
<add> }
<add>
<add> public void waitForFirstCall() {
<add> try {
<add> if (!mCountDownLatch.await(15000, TimeUnit.MILLISECONDS)) {
<add> throw new RuntimeException("Timed out waiting for first call");
<add> }
<add> } catch (InterruptedException e) {
<add> throw new RuntimeException(e);
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactIntegrationTestCase.java
<ide> import java.util.concurrent.Semaphore;
<ide> import java.util.concurrent.TimeUnit;
<ide>
<add>import android.app.Application;
<ide> import android.support.test.InstrumentationRegistry;
<ide> import android.test.AndroidTestCase;
<ide> import android.view.View;
<ide> import com.facebook.react.bridge.LifecycleEventListener;
<ide> import com.facebook.react.bridge.SoftAssertions;
<ide> import com.facebook.react.bridge.UiThreadUtil;
<add>import com.facebook.react.common.ApplicationHolder;
<ide> import com.facebook.react.common.futures.SimpleSettableFuture;
<ide> import com.facebook.react.modules.core.Timing;
<ide>
<ide> public void run() {
<ide> mBridgeIdleSignaler = new ReactBridgeIdleSignaler();
<ide> mInstance.addBridgeIdleDebugListener(mBridgeIdleSignaler);
<ide> getContext().initializeWithInstance(mInstance);
<add> ApplicationHolder.setApplication((Application) getContext().getApplicationContext());
<ide> setupEvent.occur();
<ide> }
<ide> }); | 2 |
Javascript | Javascript | fix bug with view extension | 919aa2b91b253dda2202f7e816fc499b712b1a78 | <ide><path>packages/sproutcore-touch/lib/system/view.js
<ide> SC.View.reopen(
<ide> }
<ide> }
<ide>
<del> console.log('setting gestures property to ',gestures);
<ide> set(this, 'gestures', gestures);
<ide> }
<ide>
<del> return;
<add> return this._super();
<ide> }
<ide>
<ide> }); | 1 |
Javascript | Javascript | use jquery.parsejson instead of json.parse | ced9d155f010bc456745a55a63ca959db9d405d3 | <ide><path>src/data.js
<ide> function dataAttr( elem, key, data ) {
<ide> data === "null" ? null :
<ide> // Only convert to a number if it doesn't change the string
<ide> +data + "" === data ? +data :
<del> rbrace.test( data ) ? JSON.parse( data ) :
<add> rbrace.test( data ) ? jQuery.parseJSON( data ) :
<ide> data;
<ide> } catch( e ) {}
<ide>
<ide><path>test/unit/data.js
<ide> test("data-* attributes", function() {
<ide> var prop, i, l, metadata, elem,
<ide> obj, obj2, check, num, num2,
<ide> parseJSON = jQuery.parseJSON,
<del> nativeParse = typeof JSON !== "undefined" && JSON.parse,
<ide> div = jQuery("<div>"),
<ide> child = jQuery("<div data-myobj='old data' data-ignored=\"DOM\" data-other='test'></div>"),
<ide> dummy = jQuery("<div data-myobj='old data' data-ignored=\"DOM\" data-other='test'></div>");
<ide> test("data-* attributes", function() {
<ide> equal( child.data("other"), "test", "Make sure value was pulled in properly from a .data()." );
<ide>
<ide> // attribute parsing
<del> i = l = 0;
<add> i = 0;
<ide> jQuery.parseJSON = function() {
<ide> i++;
<ide> return parseJSON.apply( this, arguments );
<ide> };
<del> if ( nativeParse ) {
<del> JSON.parse = function() {
<del> l++;
<del> return nativeParse.apply( this, arguments );
<del> };
<del> }
<ide>
<ide> child
<ide> .attr("data-true", "true")
<ide> test("data-* attributes", function() {
<ide> strictEqual( child.data("space"), " ", "Whitespace string read from attribute");
<ide> strictEqual( child.data("null"), null, "Primitive null read from attribute");
<ide> strictEqual( child.data("string"), "test", "Typical string read from attribute");
<del> equal( i || l, 2, "Correct number of JSON parse attempts when reading from attributes" );
<add> equal( i, 2, "Correct number of JSON parse attempts when reading from attributes" );
<ide>
<ide> jQuery.parseJSON = parseJSON;
<del> if ( nativeParse ) {
<del> JSON.parse = nativeParse;
<del> }
<ide> child.remove();
<ide>
<ide> // tests from metadata plugin | 2 |
PHP | PHP | fix merge conflict issues and failing tests | 2af416676f8a0d64b7c4b8d34e2a1c721aba4fbc | <ide><path>Cake/ORM/Query.php
<ide> public function first() {
<ide> $this->limit(1);
<ide> }
<ide> $this->bufferResults();
<del><<<<<<< HEAD
<del> $this->_results = $this->execute();
<del> return $this->_results->first();
<del>=======
<ide> $this->_results = $this->all();
<del> return $this->_results->one();
<del>>>>>>>> Separate execute() into 2 methods.
<add> return $this->_results->first();
<ide> }
<ide>
<ide> /**
<ide> public function __call($method, $arguments) {
<ide> if ($this->type() === 'select') {
<ide> $resultSetClass = __NAMESPACE__ . '\ResultSetDecorator';
<ide> if (in_array($method, get_class_methods($resultSetClass))) {
<del> $object = $this->execute();
<del> return call_user_func_array([$object, $method], $arguments);
<add> $results = $this->all();
<add> return call_user_func_array([$results, $method], $arguments);
<ide> }
<ide> }
<ide>
<ide><path>Cake/Test/TestCase/ORM/ResultSetTest.php
<ide> public function testRewind() {
<ide> */
<ide> public function testRewindStreaming() {
<ide> $query = $this->table->find('all')->bufferResults(false);
<del> $results = $query->execute();
<add> $results = $query->all();
<ide> $first = $second = [];
<ide> foreach ($results as $result) {
<ide> $first[] = $result; | 2 |
Javascript | Javascript | fix indentation in angular.filter.html examples | 8bb9f12961a931edc15801383c05c917c6ba09fb | <ide><path>src/filters.js
<ide> angularFilter.uppercase = uppercase;
<ide> * @example
<ide> <doc:example>
<ide> <doc:source>
<del> Snippet: <textarea name="snippet" cols="60" rows="3">
<del> <p style="color:blue">an html
<del> <em onmouseover="this.textContent='PWN3D!'">click here</em>
<del> snippet</p></textarea>
<add> Snippet: <textarea name="snippet" cols="60" rows="3">
<add> <p style="color:blue">an html
<add> <em onmouseover="this.textContent='PWN3D!'">click here</em>
<add> snippet</p></textarea>
<ide> <table>
<ide> <tr>
<ide> <td>Filter</td> | 1 |
Mixed | Javascript | fix first render of with-react-helmet example | b05df7087212ba4384d8aec93c769089491a1b27 | <ide><path>examples/with-react-helmet/README.md
<ide> now
<ide>
<ide> This an minimalistic example of how to combine next.js and [react-helmet](https://github.com/nfl/react-helmet).
<ide> The title of the page shall be changed to "Hello next.js!"
<add>If you go to the page `/about`, the title will be overridden to "About | Hello next.js!"
<ide> The rest is all up to you.
<ide><path>examples/with-react-helmet/pages/_app.js
<add>import React from 'react'
<add>import App, { Container } from 'next/app'
<add>import Helmet from 'react-helmet'
<add>
<add>export default class MyApp extends App {
<add> static async getInitialProps ({ Component, ctx }) {
<add> let pageProps = {}
<add>
<add> if (Component.getInitialProps) {
<add> pageProps = await Component.getInitialProps(ctx)
<add> }
<add>
<add> return { pageProps }
<add> }
<add>
<add> render () {
<add> const { Component, pageProps } = this.props
<add>
<add> return (
<add> <Container>
<add> <Helmet
<add> htmlAttributes={{ lang: 'en' }}
<add> title='Hello next.js!'
<add> meta={[
<add> { name: 'viewport', content: 'width=device-width, initial-scale=1' },
<add> { property: 'og:title', content: 'Hello next.js!' }
<add> ]}
<add> />
<add> <Component {...pageProps} />
<add> </Container>
<add> )
<add> }
<add>}
<ide><path>examples/with-react-helmet/pages/_document.js
<ide> export default class extends Document {
<ide> .map(el => this.props.helmet[el].toComponent())
<ide> }
<ide>
<del> get helmetJsx () {
<del> return (
<del> <Helmet
<del> htmlAttributes={{ lang: 'en' }}
<del> title='Hello next.js!'
<del> meta={[
<del> { name: 'viewport', content: 'width=device-width, initial-scale=1' },
<del> { property: 'og:title', content: 'Hello next.js!' }
<del> ]}
<del> />
<del> )
<del> }
<del>
<ide> render () {
<ide> return (
<ide> <html {...this.helmetHtmlAttrComponents}>
<ide> <Head>
<del> {this.helmetJsx}
<ide> {this.helmetHeadComponents}
<ide> </Head>
<ide> <body {...this.helmetBodyAttrComponents}>
<ide><path>examples/with-react-helmet/pages/about.js
<ide> import React from 'react'
<ide> import Helmet from 'react-helmet'
<ide>
<del>export default class About extends React.Component {
<del> static async getInitialProps ({ req }) {
<del> if (req) {
<del> Helmet.renderStatic()
<del> }
<del> return { title: 'About' }
<del> }
<del>
<del> render () {
<del> const { title } = this.props
<del> return (
<del> <div>
<del> <Helmet
<del> title={`${title} | Hello next.js!`}
<del> meta={[{ property: 'og:title', content: title }]}
<del> />
<del> About the World
<del> </div>
<del> )
<del> }
<add>export default function About () {
<add> return (
<add> <div>
<add> <Helmet
<add> title='About | Hello next.js!'
<add> meta={[{ property: 'og:title', content: 'About' }]}
<add> />
<add> About the World
<add> </div>
<add> )
<ide> } | 4 |
Javascript | Javascript | add test coverage for fs.truncate | 74f854e769fbb595b007b25d7bd79e7fbdf043b8 | <ide><path>test/parallel/test-fs-truncate.js
<ide> function testFtruncate(cb) {
<ide> }));
<ide> }
<ide>
<add>{
<add> const file7 = path.resolve(tmp, 'truncate-file-7.txt');
<add> fs.writeFileSync(file7, 'Hi');
<add> fs.truncate(file7, undefined, common.mustCall(function(err) {
<add> assert.ifError(err);
<add> assert(fs.readFileSync(file7).equals(Buffer.from('')));
<add> }));
<add>}
<add>
<add>{
<add> const file8 = path.resolve(tmp, 'non-existent-truncate-file.txt');
<add> const validateError = (err) => {
<add> assert.strictEqual(file8, err.path);
<add> assert.strictEqual(
<add> err.message,
<add> `ENOENT: no such file or directory, open '${file8}'`);
<add> assert.strictEqual(err.code, 'ENOENT');
<add> assert.strictEqual(err.syscall, 'open');
<add> return true;
<add> };
<add> fs.truncate(file8, 0, common.mustCall(validateError));
<add>}
<add>
<add>['', false, null, {}, []].forEach((input) => {
<add> assert.throws(
<add> () => fs.truncate('/foo/bar', input),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError [ERR_INVALID_ARG_TYPE]',
<add> message: 'The "len" argument must be of type number. ' +
<add> `Received type ${typeof input}`
<add> }
<add> );
<add>});
<add>
<ide> ['', false, null, undefined, {}, []].forEach((input) => {
<ide> ['ftruncate', 'ftruncateSync'].forEach((fnName) => {
<ide> assert.throws( | 1 |
Javascript | Javascript | remove themes from donate pages | f737b24b6fc4d94320f8862f689b70e631ff520d | <ide><path>client/src/components/Donation/components/DonateFormChildViewForHOC.js
<ide> const propTypes = {
<ide> isSignedIn: PropTypes.bool,
<ide> stripe: PropTypes.shape({
<ide> createToken: PropTypes.func.isRequired
<del> }),
<del> theme: PropTypes.string
<add> })
<ide> };
<ide> const initialState = {
<ide> donationState: {
<ide> const initialState = {
<ide>
<ide> const mapStateToProps = createSelector(
<ide> userSelector,
<del> ({ email, theme }) => ({ email, theme })
<add> ({ email }) => ({ email })
<ide> );
<ide>
<ide> class DonateFormChildViewForHOC extends Component {
<ide> class DonateFormChildViewForHOC extends Component {
<ide>
<ide> renderDonateForm() {
<ide> const { isFormValid } = this.state;
<del> const { theme, getDonationButtonLabel } = this.props;
<add> const { getDonationButtonLabel } = this.props;
<ide> return (
<ide> <Form className='donation-form' onSubmit={this.handleSubmit}>
<ide> <FormGroup className='donation-email-container'>
<ide> class DonateFormChildViewForHOC extends Component {
<ide> value={this.getUserEmail()}
<ide> />
<ide> </FormGroup>
<del> <StripeCardForm
<del> getValidationState={this.getValidationState}
<del> theme={theme}
<del> />
<add> <StripeCardForm getValidationState={this.getValidationState} />
<ide> <Button
<ide> block={true}
<ide> bsStyle='primary'
<ide><path>client/src/components/layouts/Default.js
<ide> const propTypes = {
<ide> pathname: PropTypes.string.isRequired,
<ide> removeFlashMessage: PropTypes.func.isRequired,
<ide> showFooter: PropTypes.bool,
<del> theme: PropTypes.string
<add> theme: PropTypes.string,
<add> useTheme: PropTypes.bool
<ide> };
<ide>
<ide> const mapStateToProps = createSelector(
<ide> class DefaultLayout extends Component {
<ide> isSignedIn,
<ide> removeFlashMessage,
<ide> showFooter = true,
<del> theme = 'default'
<add> theme = 'default',
<add> useTheme = true
<ide> } = this.props;
<ide> return (
<ide> <Fragment>
<ide> <Helmet
<ide> bodyAttributes={{
<del> class: `${theme === 'default' ? 'light-palette' : 'dark-palette'}`
<add> class: useTheme
<add> ? `${theme === 'default' ? 'light-palette' : 'dark-palette'}`
<add> : 'light-palette'
<ide> }}
<ide> meta={[
<ide> {
<ide><path>client/utils/gatsby/layoutSelector.js
<ide> export default function layoutSelector({ element, props }) {
<ide> </DefaultLayout>
<ide> );
<ide> }
<add> if (/^\/donation(\/.*)*|^\/donate(\/.*)*/.test(pathname)) {
<add> return (
<add> <DefaultLayout pathname={pathname} useTheme={false}>
<add> {element}
<add> </DefaultLayout>
<add> );
<add> }
<ide> return <DefaultLayout pathname={pathname}>{element}</DefaultLayout>;
<ide> }
<ide> | 3 |
Java | Java | add relay as a category | 652dfd0b48f5b2df65e07ac1c8dd1025e5704caf | <ide><path>ReactAndroid/src/main/java/com/facebook/debug/tags/ReactDebugOverlayTags.java
<ide> public class ReactDebugOverlayTags {
<ide> "UI Manager",
<ide> "UI Manager View Operations (requires restart\nwarning: this is spammy)",
<ide> Color.CYAN);
<add> public static final DebugOverlayTag RELAY =
<add> new DebugOverlayTag("Relay", "including prefetching", Color.rgb(0xFF, 0x99, 0x00));
<ide> } | 1 |
Javascript | Javascript | expose module on entry dep | 07e29e2348fcabc1dbbc99807fdce0f3c4a5c133 | <ide><path>lib/Compilation.js
<ide> Compilation.prototype._addModuleChain = function process(context, dependency, on
<ide> Compilation.prototype.addEntry = function process(context, entry, name, callback) {
<ide> this._addModuleChain(context, entry, function(module) {
<ide>
<add> entry.module = module;
<ide> this.entries.push(module);
<ide> module.id = 0;
<ide> | 1 |
Javascript | Javascript | flip the switch on checkon | cb707d8bd0ccd40935a41f0814ff0b85a1e25c40 | <ide><path>src/attributes/val.js
<ide> jQuery.each([ "radio", "checkbox" ], function() {
<ide> }
<ide> }
<ide> };
<del> if ( support.checkOn ) {
<add> if ( !support.checkOn ) {
<ide> jQuery.valHooks[ this ].get = function( elem ) {
<ide> // Support: Webkit
<ide> // "" is returned instead of "on" if a value isn't specified | 1 |
Java | Java | add some test cases in stringutilstests | c5b8406def18c1b0f5791e5892643fd0b1937a04 | <ide><path>spring-core/src/test/java/org/springframework/util/StringUtilsTests.java
<ide> void containsWhitespace() {
<ide> assertThat(StringUtils.containsWhitespace("a")).isFalse();
<ide> assertThat(StringUtils.containsWhitespace("abc")).isFalse();
<ide> assertThat(StringUtils.containsWhitespace(" ")).isTrue();
<add> assertThat(StringUtils.containsWhitespace("\t")).isTrue();
<add> assertThat(StringUtils.containsWhitespace("\n")).isTrue();
<ide> assertThat(StringUtils.containsWhitespace(" a")).isTrue();
<ide> assertThat(StringUtils.containsWhitespace("abc ")).isTrue();
<ide> assertThat(StringUtils.containsWhitespace("a b")).isTrue();
<ide> void trimWhitespace() {
<ide> assertThat(StringUtils.trimWhitespace("")).isEqualTo("");
<ide> assertThat(StringUtils.trimWhitespace(" ")).isEqualTo("");
<ide> assertThat(StringUtils.trimWhitespace("\t")).isEqualTo("");
<add> assertThat(StringUtils.trimWhitespace("\n")).isEqualTo("");
<add> assertThat(StringUtils.trimWhitespace(" \t\n")).isEqualTo("");
<ide> assertThat(StringUtils.trimWhitespace(" a")).isEqualTo("a");
<ide> assertThat(StringUtils.trimWhitespace("a ")).isEqualTo("a");
<ide> assertThat(StringUtils.trimWhitespace(" a ")).isEqualTo("a");
<ide> void trimWhitespace() {
<ide>
<ide> @Test
<ide> void trimAllWhitespace() {
<add> assertThat(StringUtils.trimAllWhitespace(null)).isEqualTo(null);
<ide> assertThat(StringUtils.trimAllWhitespace("")).isEqualTo("");
<ide> assertThat(StringUtils.trimAllWhitespace(" ")).isEqualTo("");
<ide> assertThat(StringUtils.trimAllWhitespace("\t")).isEqualTo("");
<add> assertThat(StringUtils.trimAllWhitespace("\n")).isEqualTo("");
<add> assertThat(StringUtils.trimAllWhitespace(" \t\n")).isEqualTo("");
<ide> assertThat(StringUtils.trimAllWhitespace(" a")).isEqualTo("a");
<ide> assertThat(StringUtils.trimAllWhitespace("a ")).isEqualTo("a");
<ide> assertThat(StringUtils.trimAllWhitespace(" a ")).isEqualTo("a");
<ide> void trimLeadingWhitespace() {
<ide> assertThat(StringUtils.trimLeadingWhitespace("")).isEqualTo("");
<ide> assertThat(StringUtils.trimLeadingWhitespace(" ")).isEqualTo("");
<ide> assertThat(StringUtils.trimLeadingWhitespace("\t")).isEqualTo("");
<add> assertThat(StringUtils.trimLeadingWhitespace("\n")).isEqualTo("");
<add> assertThat(StringUtils.trimLeadingWhitespace(" \t\n")).isEqualTo("");
<ide> assertThat(StringUtils.trimLeadingWhitespace(" a")).isEqualTo("a");
<ide> assertThat(StringUtils.trimLeadingWhitespace("a ")).isEqualTo("a ");
<ide> assertThat(StringUtils.trimLeadingWhitespace(" a ")).isEqualTo("a ");
<ide> void trimTrailingWhitespace() {
<ide> assertThat(StringUtils.trimTrailingWhitespace("")).isEqualTo("");
<ide> assertThat(StringUtils.trimTrailingWhitespace(" ")).isEqualTo("");
<ide> assertThat(StringUtils.trimTrailingWhitespace("\t")).isEqualTo("");
<add> assertThat(StringUtils.trimTrailingWhitespace("\n")).isEqualTo("");
<add> assertThat(StringUtils.trimTrailingWhitespace(" \t\n")).isEqualTo("");
<ide> assertThat(StringUtils.trimTrailingWhitespace("a ")).isEqualTo("a");
<ide> assertThat(StringUtils.trimTrailingWhitespace(" a")).isEqualTo(" a");
<ide> assertThat(StringUtils.trimTrailingWhitespace(" a ")).isEqualTo(" a"); | 1 |
Text | Text | change emphasis style in blender | 3a9c4cf1d6f5c8a6eef191f9735787ef379cffbe | <ide><path>guide/english/3d/blender/index.md
<ide> ---
<ide> title: Blender
<ide> ---
<del>
<ide> ## Blender
<ide>
<ide> Blender is a free and open source 3D creation suite. It's used for modeling, creating photorealistic renders, simulation, model sculpting, architecture models, compositing, character design, animation, rigging, level design, 2D rendered scenes, motion graphics, game development, VFX, video editing and even much more!
<ide>
<del>The Blender software is cross-platform that runs on Windows, Linux and Mac. Blender is supported by The Blender Foundation a community from around the world. Developers, animators, scientists, experts and even hobbyists empower the software's development by constantly maintaining, fixing and making new features for a suitable and more responsive user experience.
<del>
<del>Blender is now especially useful as the 3D printer technology has become more of a household item for many. Blender allows the user to develop their idea and export it as an .obj that slicers can convert to .stl files or it can export in .stl format as well. If one develops their project in a CAD app that only exports as .obj, Blender can import the file and convert it to an .stl - a very popular filetype.
<add>The Blender software is cross-platform that runs on Windows, Linux and Mac.Blender is supported by The Blender Foundation a community from around the world. Developers, animators, scientists, experts and even hobbyists that empowers the softwares development by constantly maintaining, fixing and making new features for a suitable and more responsive user experience.
<ide>
<del>Blender is free and open source software, released under the *GNU General Public License (GPL)**.
<add>Blender is free and open source software, released under the **_GNU General Public License (GPL)_**.
<ide>
<del>#### More Information:
<add>#### More Information:
<ide>
<ide> * [Blender Official Website](https://www.blender.org)
<ide> * [Blender Documentation](https://docs.blender.org/) | 1 |
Ruby | Ruby | fix initializable tests | 5eb3b4d9a78268753d009404810619cf93cf6581 | <ide><path>railties/lib/rails/initializable.rb
<ide> def initializer(name, opts = {}, &blk)
<ide>
<ide> def run_initializers(*args)
<ide> return if @ran
<del> initializers_chain.each do |initializer|
<add> initializers_chain.tsort.each do |initializer|
<ide> instance_exec(*args, &initializer.block)
<ide> end
<ide> @ran = true | 1 |
Ruby | Ruby | fix tap variable naming | a0980f05a1399a434b057e551995847fa9db4e64 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def test_bot
<ide> safe_system "git", "push", "--force", remote, "master:master", ":refs/tags/#{tag}"
<ide>
<ide> # Bintray upload (will take over soon)
<del> bintray_repo = Bintray.repository(tap_name)
<add> bintray_repo = Bintray.repository(tap)
<ide> bintray_repo_url = "https://api.bintray.com/packages/homebrew/#{bintray_repo}"
<ide> formula_packaged = {}
<ide> | 1 |
Go | Go | use sequential file access | 7c29f5beed19b55ac8f14880752d4825ba23eccf | <ide><path>cli/command/image/load.go
<ide> package image
<ide> import (
<ide> "fmt"
<ide> "io"
<del> "os"
<ide>
<ide> "golang.org/x/net/context"
<ide>
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cli/command"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<add> "github.com/docker/docker/pkg/system"
<ide> "github.com/spf13/cobra"
<ide> )
<ide>
<ide> func runLoad(dockerCli *command.DockerCli, opts loadOptions) error {
<ide>
<ide> var input io.Reader = dockerCli.In()
<ide> if opts.input != "" {
<del> file, err := os.Open(opts.input)
<add> // We use system.OpenSequential to use sequential file access on Windows, avoiding
<add> // depleting the standby list un-necessarily. On Linux, this equates to a regular os.Open.
<add> file, err := system.OpenSequential(opts.input)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>image/tarexport/load.go
<ide> import (
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/symlink"
<add> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/reference"
<ide> )
<ide>
<ide> func (l *tarexporter) setParentID(id, parentID image.ID) error {
<ide> }
<ide>
<ide> func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string, foreignSrc distribution.Descriptor, progressOutput progress.Output) (layer.Layer, error) {
<del> rawTar, err := os.Open(filename)
<add> // We use system.OpenSequential to use sequential file access on Windows, avoiding
<add> // depleting the standby list. On Linux, this equates to a regular os.Open.
<add> rawTar, err := system.OpenSequential(filename)
<ide> if err != nil {
<ide> logrus.Debugf("Error reading embedded tar: %v", err)
<ide> return nil, err
<ide><path>image/tarexport/save.go
<ide> func (s *saveSession) saveLayer(id layer.ChainID, legacyImg image.V1Image, creat
<ide> }
<ide> os.Symlink(relPath, layerPath)
<ide> } else {
<del>
<del> tarFile, err := os.Create(layerPath)
<add> // Use system.CreateSequential rather than os.Create. This ensures sequential
<add> // file access on Windows to avoid eating into MM standby list.
<add> // On Linux, this equates to a regular os.Create.
<add> tarFile, err := system.CreateSequential(layerPath)
<ide> if err != nil {
<ide> return distribution.Descriptor{}, err
<ide> }
<ide><path>pkg/archive/archive.go
<ide> func (ta *tarAppender) addTarFile(path, name string) error {
<ide> }
<ide>
<ide> if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 {
<del> file, err := os.Open(path)
<add> // We use system.OpenSequential to ensure we use sequential file
<add> // access on Windows to avoid depleting the standby list.
<add> // On Linux, this equates to a regular os.Open.
<add> file, err := system.OpenSequential(path)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, L
<ide> }
<ide>
<ide> case tar.TypeReg, tar.TypeRegA:
<del> // Source is regular file
<del> file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode())
<add> // Source is regular file. We use system.OpenFileSequential to use sequential
<add> // file access to avoid depleting the standby list on Windows.
<add> // On Linux, this equates to a regular os.OpenFile
<add> file, err := system.OpenFileSequential(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode())
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>pkg/system/filesys.go
<ide> func MkdirAll(path string, perm os.FileMode) error {
<ide> func IsAbs(path string) bool {
<ide> return filepath.IsAbs(path)
<ide> }
<add>
<add>// The functions below here are wrappers for the equivalents in the os package.
<add>// They are passthrough on Unix platforms, and only relevant on Windows.
<add>
<add>// CreateSequential creates the named file with mode 0666 (before umask), truncating
<add>// it if it already exists. If successful, methods on the returned
<add>// File can be used for I/O; the associated file descriptor has mode
<add>// O_RDWR.
<add>// If there is an error, it will be of type *PathError.
<add>func CreateSequential(name string) (*os.File, error) {
<add> return os.Create(name)
<add>}
<add>
<add>// OpenSequential opens the named file for reading. If successful, methods on
<add>// the returned file can be used for reading; the associated file
<add>// descriptor has mode O_RDONLY.
<add>// If there is an error, it will be of type *PathError.
<add>func OpenSequential(name string) (*os.File, error) {
<add> return os.Open(name)
<add>}
<add>
<add>// OpenFileSequential is the generalized open call; most users will use Open
<add>// or Create instead. It opens the named file with specified flag
<add>// (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,
<add>// methods on the returned File can be used for I/O.
<add>// If there is an error, it will be of type *PathError.
<add>func OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) {
<add> return os.OpenFile(name, flag, perm)
<add>}
<ide><path>pkg/system/filesys_windows.go
<ide> func IsAbs(path string) bool {
<ide> }
<ide> return true
<ide> }
<add>
<add>// The origin of the functions below here are the golang OS and syscall packages,
<add>// slightly modified to only cope with files, not directories due to the
<add>// specific use case.
<add>//
<add>// The alteration is to allow a file on Windows to be opened with
<add>// FILE_FLAG_SEQUENTIAL_SCAN (particular for docker load), to avoid eating
<add>// the standby list, particularly when accessing large files such as layer.tar.
<add>
<add>// CreateSequential creates the named file with mode 0666 (before umask), truncating
<add>// it if it already exists. If successful, methods on the returned
<add>// File can be used for I/O; the associated file descriptor has mode
<add>// O_RDWR.
<add>// If there is an error, it will be of type *PathError.
<add>func CreateSequential(name string) (*os.File, error) {
<add> return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0)
<add>}
<add>
<add>// OpenSequential opens the named file for reading. If successful, methods on
<add>// the returned file can be used for reading; the associated file
<add>// descriptor has mode O_RDONLY.
<add>// If there is an error, it will be of type *PathError.
<add>func OpenSequential(name string) (*os.File, error) {
<add> return OpenFileSequential(name, os.O_RDONLY, 0)
<add>}
<add>
<add>// OpenFileSequential is the generalized open call; most users will use Open
<add>// or Create instead.
<add>// If there is an error, it will be of type *PathError.
<add>func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) {
<add> if name == "" {
<add> return nil, &os.PathError{"open", name, syscall.ENOENT}
<add> }
<add> r, errf := syscallOpenFileSequential(name, flag, 0)
<add> if errf == nil {
<add> return r, nil
<add> }
<add> return nil, &os.PathError{"open", name, errf}
<add>}
<add>
<add>func syscallOpenFileSequential(name string, flag int, _ os.FileMode) (file *os.File, err error) {
<add> r, e := syscallOpenSequential(name, flag|syscall.O_CLOEXEC, 0)
<add> if e != nil {
<add> return nil, e
<add> }
<add> return os.NewFile(uintptr(r), name), nil
<add>}
<add>
<add>func makeInheritSa() *syscall.SecurityAttributes {
<add> var sa syscall.SecurityAttributes
<add> sa.Length = uint32(unsafe.Sizeof(sa))
<add> sa.InheritHandle = 1
<add> return &sa
<add>}
<add>
<add>func syscallOpenSequential(path string, mode int, _ uint32) (fd syscall.Handle, err error) {
<add> if len(path) == 0 {
<add> return syscall.InvalidHandle, syscall.ERROR_FILE_NOT_FOUND
<add> }
<add> pathp, err := syscall.UTF16PtrFromString(path)
<add> if err != nil {
<add> return syscall.InvalidHandle, err
<add> }
<add> var access uint32
<add> switch mode & (syscall.O_RDONLY | syscall.O_WRONLY | syscall.O_RDWR) {
<add> case syscall.O_RDONLY:
<add> access = syscall.GENERIC_READ
<add> case syscall.O_WRONLY:
<add> access = syscall.GENERIC_WRITE
<add> case syscall.O_RDWR:
<add> access = syscall.GENERIC_READ | syscall.GENERIC_WRITE
<add> }
<add> if mode&syscall.O_CREAT != 0 {
<add> access |= syscall.GENERIC_WRITE
<add> }
<add> if mode&syscall.O_APPEND != 0 {
<add> access &^= syscall.GENERIC_WRITE
<add> access |= syscall.FILE_APPEND_DATA
<add> }
<add> sharemode := uint32(syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE)
<add> var sa *syscall.SecurityAttributes
<add> if mode&syscall.O_CLOEXEC == 0 {
<add> sa = makeInheritSa()
<add> }
<add> var createmode uint32
<add> switch {
<add> case mode&(syscall.O_CREAT|syscall.O_EXCL) == (syscall.O_CREAT | syscall.O_EXCL):
<add> createmode = syscall.CREATE_NEW
<add> case mode&(syscall.O_CREAT|syscall.O_TRUNC) == (syscall.O_CREAT | syscall.O_TRUNC):
<add> createmode = syscall.CREATE_ALWAYS
<add> case mode&syscall.O_CREAT == syscall.O_CREAT:
<add> createmode = syscall.OPEN_ALWAYS
<add> case mode&syscall.O_TRUNC == syscall.O_TRUNC:
<add> createmode = syscall.TRUNCATE_EXISTING
<add> default:
<add> createmode = syscall.OPEN_EXISTING
<add> }
<add> // Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang.
<add> //https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
<add> const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN
<add> h, e := syscall.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0)
<add> return h, e
<add>} | 6 |
Ruby | Ruby | use assert_predicate and assert_not_predicate | 94333a4c31bd10c1f358c538a167e6a4589bae2d | <ide><path>actioncable/test/channel/base_test.rb
<ide> def rm_rf
<ide> @channel.subscribe_to_channel
<ide>
<ide> assert @channel.room
<del> assert @channel.subscribed?
<add> assert_predicate @channel, :subscribed?
<ide>
<ide> @channel.unsubscribe_from_channel
<ide>
<del> assert ! @channel.room
<del> assert ! @channel.subscribed?
<add> assert_not @channel.room
<add> assert_not_predicate @channel, :subscribed?
<ide> end
<ide>
<ide> test "connection identifiers" do
<ide><path>actioncable/test/channel/stream_test.rb
<ide> def open_connection
<ide>
<ide> Connection.new(@server, env).tap do |connection|
<ide> connection.process
<del> assert connection.websocket.possible?
<add> assert_predicate connection.websocket, :possible?
<ide>
<ide> wait_for_async
<del> assert connection.websocket.alive?
<add> assert_predicate connection.websocket, :alive?
<ide> end
<ide> end
<ide>
<ide><path>actioncable/test/client_test.rb
<ide> def test_server_restart
<ide>
<ide> ActionCable.server.restart
<ide> c.wait_for_close
<del> assert c.closed?
<add> assert_predicate c, :closed?
<ide> end
<ide> end
<ide> end
<ide><path>actioncable/test/connection/base_test.rb
<ide> def send_async(method, *args)
<ide> connection = open_connection
<ide> connection.process
<ide>
<del> assert connection.websocket.possible?
<add> assert_predicate connection.websocket, :possible?
<ide>
<ide> wait_for_async
<del> assert connection.websocket.alive?
<add> assert_predicate connection.websocket, :alive?
<ide> end
<ide> end
<ide>
<ide> def send_async(method, *args)
<ide>
<ide> statistics = connection.statistics
<ide>
<del> assert statistics[:identifier].blank?
<add> assert_predicate statistics[:identifier], :blank?
<ide> assert_kind_of Time, statistics[:started_at]
<ide> assert_equal [], statistics[:subscriptions]
<ide> end
<ide><path>actioncable/test/connection/subscriptions_test.rb
<ide> def speak(data)
<ide> setup_connection
<ide>
<ide> @subscriptions.execute_command "command" => "subscribe"
<del> assert @subscriptions.identifiers.empty?
<add> assert_predicate @subscriptions.identifiers, :empty?
<ide> end
<ide> end
<ide>
<ide> def speak(data)
<ide> channel.expects(:unsubscribe_from_channel)
<ide>
<ide> @subscriptions.execute_command "command" => "unsubscribe", "identifier" => @chat_identifier
<del> assert @subscriptions.identifiers.empty?
<add> assert_predicate @subscriptions.identifiers, :empty?
<ide> end
<ide> end
<ide>
<ide> def speak(data)
<ide> setup_connection
<ide>
<ide> @subscriptions.execute_command "command" => "unsubscribe"
<del> assert @subscriptions.identifiers.empty?
<add> assert_predicate @subscriptions.identifiers, :empty?
<ide> end
<ide> end
<ide>
<ide><path>actioncable/test/subscription_adapter/common.rb
<ide> def subscribe_as_queue(channel, adapter = @rx_adapter)
<ide> subscribed = Concurrent::Event.new
<ide> adapter.subscribe(channel, callback, Proc.new { subscribed.set })
<ide> subscribed.wait(WAIT_WHEN_EXPECTING_EVENT)
<del> assert subscribed.set?
<add> assert_predicate subscribed, :set?
<ide>
<ide> yield queue
<ide>
<ide><path>actionmailer/test/caching_test.rb
<ide> def test_html_safety
<ide>
<ide> html_safe = @mailer.read_fragment("name")
<ide> assert_equal content, html_safe
<del> assert html_safe.html_safe?
<add> assert_predicate html_safe, :html_safe?
<ide> end
<ide> end
<ide>
<ide> class HasDependenciesMailer < ActionMailer::Base
<ide> end
<ide>
<ide> def test_view_cache_dependencies_are_empty_by_default
<del> assert NoDependenciesMailer.new.view_cache_dependencies.empty?
<add> assert_predicate NoDependenciesMailer.new.view_cache_dependencies, :empty?
<ide> end
<ide>
<ide> def test_view_cache_dependencies_are_listed_in_declaration_order
<ide><path>actionpack/test/controller/action_pack_assertions_test.rb
<ide> def test_template_objects_missing
<ide>
<ide> def test_empty_flash
<ide> process :flash_me_naked
<del> assert flash.empty?
<add> assert_predicate flash, :empty?
<ide> end
<ide>
<ide> def test_flash_exist
<ide> process :flash_me
<del> assert flash.any?
<del> assert flash["hello"].present?
<add> assert_predicate flash, :any?
<add> assert_predicate flash["hello"], :present?
<ide> end
<ide>
<ide> def test_flash_does_not_exist
<ide> process :nothing
<del> assert flash.empty?
<add> assert_predicate flash, :empty?
<ide> end
<ide>
<ide> def test_session_exist
<ide> def test_session_exist
<ide>
<ide> def session_does_not_exist
<ide> process :nothing
<del> assert session.empty?
<add> assert_predicate session, :empty?
<ide> end
<ide>
<ide> def test_redirection_location
<ide> def test_no_redirect_url
<ide>
<ide> def test_server_error_response_code
<ide> process :response500
<del> assert @response.server_error?
<add> assert_predicate @response, :server_error?
<ide>
<ide> process :response599
<del> assert @response.server_error?
<add> assert_predicate @response, :server_error?
<ide>
<ide> process :response404
<del> assert !@response.server_error?
<add> assert_not_predicate @response, :server_error?
<ide> end
<ide>
<ide> def test_missing_response_code
<ide> process :response404
<del> assert @response.not_found?
<add> assert_predicate @response, :not_found?
<ide> end
<ide>
<ide> def test_client_error_response_code
<ide> process :response404
<del> assert @response.client_error?
<add> assert_predicate @response, :client_error?
<ide> end
<ide>
<ide> def test_redirect_url_match
<ide> process :redirect_external
<del> assert @response.redirect?
<add> assert_predicate @response, :redirect?
<ide> assert_match(/rubyonrails/, @response.redirect_url)
<ide> assert !/perloffrails/.match(@response.redirect_url)
<ide> end
<ide>
<ide> def test_redirection
<ide> process :redirect_internal
<del> assert @response.redirect?
<add> assert_predicate @response, :redirect?
<ide>
<ide> process :redirect_external
<del> assert @response.redirect?
<add> assert_predicate @response, :redirect?
<ide>
<ide> process :nothing
<del> assert !@response.redirect?
<add> assert_not_predicate @response, :redirect?
<ide> end
<ide>
<ide> def test_successful_response_code
<ide> process :nothing
<del> assert @response.successful?
<add> assert_predicate @response, :successful?
<ide> end
<ide>
<ide> def test_response_object
<ide><path>actionpack/test/controller/api/conditional_get_test.rb
<ide> def test_request_not_modified
<ide> @request.if_modified_since = @last_modified
<ide> get :one
<ide> assert_equal 304, @response.status.to_i
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal @last_modified, @response.headers["Last-Modified"]
<ide> end
<ide> end
<ide><path>actionpack/test/controller/base_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_performed?
<del> assert !@empty.performed?
<add> assert_not_predicate @empty, :performed?
<ide> @empty.response_body = ["sweet"]
<del> assert @empty.performed?
<add> assert_predicate @empty, :performed?
<ide> end
<ide>
<ide> def test_action_methods
<ide><path>actionpack/test/controller/caching_test.rb
<ide> def test_html_safety
<ide>
<ide> html_safe = @controller.read_fragment("name")
<ide> assert_equal content, html_safe
<del> assert html_safe.html_safe?
<add> assert_predicate html_safe, :html_safe?
<ide> end
<ide> end
<ide>
<ide> class HasDependenciesController < ActionController::Base
<ide> end
<ide>
<ide> def test_view_cache_dependencies_are_empty_by_default
<del> assert NoDependenciesController.new.view_cache_dependencies.empty?
<add> assert_predicate NoDependenciesController.new.view_cache_dependencies, :empty?
<ide> end
<ide>
<ide> def test_view_cache_dependencies_are_listed_in_declaration_order
<ide><path>actionpack/test/controller/filters_test.rb
<ide> def test_a_rescuing_around_action
<ide> response = test_process(RescuedController)
<ide> end
<ide>
<del> assert response.successful?
<add> assert_predicate response, :successful?
<ide> assert_equal("I rescued this: #<FilterTest::ErrorToRescue: Something made the bad noise.>", response.body)
<ide> end
<ide>
<ide><path>actionpack/test/controller/flash_hash_test.rb
<ide> def test_from_session_value_on_json_serializer
<ide> end
<ide>
<ide> def test_empty?
<del> assert @hash.empty?
<add> assert_predicate @hash, :empty?
<ide> @hash["zomg"] = "bears"
<del> assert !@hash.empty?
<add> assert_not_predicate @hash, :empty?
<ide> @hash.clear
<del> assert @hash.empty?
<add> assert_predicate @hash, :empty?
<ide> end
<ide>
<ide> def test_each
<ide><path>actionpack/test/controller/integration_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_https_bang_works_and_sets_truth_by_default
<del> assert !@session.https?
<add> assert_not_predicate @session, :https?
<ide> @session.https!
<del> assert @session.https?
<add> assert_predicate @session, :https?
<ide> @session.https! false
<del> assert !@session.https?
<add> assert_not_predicate @session, :https?
<ide> end
<ide>
<ide> def test_host!
<ide> def test_post_then_get_with_parameters_do_not_leak_across_requests
<ide>
<ide> get "/get_with_params", params: { foo: "bar" }
<ide>
<del> assert request.env["rack.input"].string.empty?
<add> assert_predicate request.env["rack.input"].string, :empty?
<ide> assert_equal "foo=bar", request.env["QUERY_STRING"]
<ide> assert_equal "foo=bar", request.query_string
<ide> assert_equal "bar", request.parameters["foo"]
<del> assert request.parameters["leaks"].nil?
<add> assert_predicate request.parameters["leaks"], :nil?
<ide> end
<ide> end
<ide>
<ide><path>actionpack/test/controller/output_escaping_test.rb
<ide>
<ide> class OutputEscapingTest < ActiveSupport::TestCase
<ide> test "escape_html shouldn't die when passed nil" do
<del> assert ERB::Util.h(nil).blank?
<add> assert_predicate ERB::Util.h(nil), :blank?
<ide> end
<ide>
<ide> test "escapeHTML should escape strings" do
<ide><path>actionpack/test/controller/parameters/accessors_test.rb
<ide> class ParametersAccessorsTest < ActiveSupport::TestCase
<ide>
<ide> test "[] retains permitted status" do
<ide> @params.permit!
<del> assert @params[:person].permitted?
<del> assert @params[:person][:name].permitted?
<add> assert_predicate @params[:person], :permitted?
<add> assert_predicate @params[:person][:name], :permitted?
<ide> end
<ide>
<ide> test "[] retains unpermitted status" do
<del> assert_not @params[:person].permitted?
<del> assert_not @params[:person][:name].permitted?
<add> assert_not_predicate @params[:person], :permitted?
<add> assert_not_predicate @params[:person][:name], :permitted?
<ide> end
<ide>
<ide> test "as_json returns the JSON representation of the parameters hash" do
<ide> class ParametersAccessorsTest < ActiveSupport::TestCase
<ide>
<ide> test "empty? returns true when params contains no key/value pairs" do
<ide> params = ActionController::Parameters.new
<del> assert params.empty?
<add> assert_predicate params, :empty?
<ide> end
<ide>
<ide> test "empty? returns false when any params are present" do
<del> assert_not @params.empty?
<add> assert_not_predicate @params, :empty?
<ide> end
<ide>
<ide> test "except retains permitted status" do
<ide> @params.permit!
<del> assert @params.except(:person).permitted?
<del> assert @params[:person].except(:name).permitted?
<add> assert_predicate @params.except(:person), :permitted?
<add> assert_predicate @params[:person].except(:name), :permitted?
<ide> end
<ide>
<ide> test "except retains unpermitted status" do
<del> assert_not @params.except(:person).permitted?
<del> assert_not @params[:person].except(:name).permitted?
<add> assert_not_predicate @params.except(:person), :permitted?
<add> assert_not_predicate @params[:person].except(:name), :permitted?
<ide> end
<ide>
<ide> test "fetch retains permitted status" do
<ide> @params.permit!
<del> assert @params.fetch(:person).permitted?
<del> assert @params[:person].fetch(:name).permitted?
<add> assert_predicate @params.fetch(:person), :permitted?
<add> assert_predicate @params[:person].fetch(:name), :permitted?
<ide> end
<ide>
<ide> test "fetch retains unpermitted status" do
<del> assert_not @params.fetch(:person).permitted?
<del> assert_not @params[:person].fetch(:name).permitted?
<add> assert_not_predicate @params.fetch(:person), :permitted?
<add> assert_not_predicate @params[:person].fetch(:name), :permitted?
<ide> end
<ide>
<ide> test "has_key? returns true if the given key is present in the params" do
<ide> class ParametersAccessorsTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> test "reject retains permitted status" do
<del> assert_not @params.reject { |k| k == "person" }.permitted?
<add> assert_not_predicate @params.reject { |k| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "reject retains unpermitted status" do
<ide> @params.permit!
<del> assert @params.reject { |k| k == "person" }.permitted?
<add> assert_predicate @params.reject { |k| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "select retains permitted status" do
<ide> @params.permit!
<del> assert @params.select { |k| k == "person" }.permitted?
<add> assert_predicate @params.select { |k| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "select retains unpermitted status" do
<del> assert_not @params.select { |k| k == "person" }.permitted?
<add> assert_not_predicate @params.select { |k| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "slice retains permitted status" do
<ide> @params.permit!
<del> assert @params.slice(:person).permitted?
<add> assert_predicate @params.slice(:person), :permitted?
<ide> end
<ide>
<ide> test "slice retains unpermitted status" do
<del> assert_not @params.slice(:person).permitted?
<add> assert_not_predicate @params.slice(:person), :permitted?
<ide> end
<ide>
<ide> test "transform_keys retains permitted status" do
<ide> @params.permit!
<del> assert @params.transform_keys { |k| k }.permitted?
<add> assert_predicate @params.transform_keys { |k| k }, :permitted?
<ide> end
<ide>
<ide> test "transform_keys retains unpermitted status" do
<del> assert_not @params.transform_keys { |k| k }.permitted?
<add> assert_not_predicate @params.transform_keys { |k| k }, :permitted?
<ide> end
<ide>
<ide> test "transform_values retains permitted status" do
<ide> @params.permit!
<del> assert @params.transform_values { |v| v }.permitted?
<add> assert_predicate @params.transform_values { |v| v }, :permitted?
<ide> end
<ide>
<ide> test "transform_values retains unpermitted status" do
<del> assert_not @params.transform_values { |v| v }.permitted?
<add> assert_not_predicate @params.transform_values { |v| v }, :permitted?
<ide> end
<ide>
<ide> test "value? returns true if the given value is present in the params" do
<ide> class ParametersAccessorsTest < ActiveSupport::TestCase
<ide>
<ide> test "values_at retains permitted status" do
<ide> @params.permit!
<del> assert @params.values_at(:person).first.permitted?
<del> assert @params[:person].values_at(:name).first.permitted?
<add> assert_predicate @params.values_at(:person).first, :permitted?
<add> assert_predicate @params[:person].values_at(:name).first, :permitted?
<ide> end
<ide>
<ide> test "values_at retains unpermitted status" do
<del> assert_not @params.values_at(:person).first.permitted?
<del> assert_not @params[:person].values_at(:name).first.permitted?
<add> assert_not_predicate @params.values_at(:person).first, :permitted?
<add> assert_not_predicate @params[:person].values_at(:name).first, :permitted?
<ide> end
<ide>
<ide> test "is equal to Parameters instance with same params" do
<ide><path>actionpack/test/controller/parameters/always_permitted_parameters_test.rb
<ide> def teardown
<ide> book: { pages: 65 },
<ide> format: "json")
<ide> permitted = params.permit book: [:pages]
<del> assert permitted.permitted?
<add> assert_predicate permitted, :permitted?
<ide> end
<ide> end
<ide><path>actionpack/test/controller/parameters/dup_test.rb
<ide> class ParametersDupTest < ActiveSupport::TestCase
<ide> test "a duplicate maintains the original's permitted status" do
<ide> @params.permit!
<ide> dupped_params = @params.dup
<del> assert dupped_params.permitted?
<add> assert_predicate dupped_params, :permitted?
<ide> end
<ide>
<ide> test "a duplicate maintains the original's parameters" do
<ide> class ParametersDupTest < ActiveSupport::TestCase
<ide> dupped_params = @params.deep_dup
<ide> dupped_params.permit!
<ide>
<del> assert_not @params.permitted?
<add> assert_not_predicate @params, :permitted?
<ide> end
<ide>
<ide> test "deep_dup @permitted is being copied" do
<ide> @params.permit!
<del> assert @params.deep_dup.permitted?
<add> assert_predicate @params.deep_dup, :permitted?
<ide> end
<ide> end
<ide><path>actionpack/test/controller/parameters/multi_parameter_attributes_test.rb
<ide> class MultiParameterAttributesTest < ActiveSupport::TestCase
<ide>
<ide> permitted = params.permit book: [ :shipped_at, :price ]
<ide>
<del> assert permitted.permitted?
<add> assert_predicate permitted, :permitted?
<ide>
<ide> assert_equal "2012", permitted[:book]["shipped_at(1i)"]
<ide> assert_equal "3", permitted[:book]["shipped_at(2i)"]
<ide><path>actionpack/test/controller/parameters/mutators_test.rb
<ide> class ParametersMutatorsTest < ActiveSupport::TestCase
<ide>
<ide> test "delete retains permitted status" do
<ide> @params.permit!
<del> assert @params.delete(:person).permitted?
<add> assert_predicate @params.delete(:person), :permitted?
<ide> end
<ide>
<ide> test "delete retains unpermitted status" do
<del> assert_not @params.delete(:person).permitted?
<add> assert_not_predicate @params.delete(:person), :permitted?
<ide> end
<ide>
<ide> test "delete returns the value when the key is present" do
<ide> class ParametersMutatorsTest < ActiveSupport::TestCase
<ide>
<ide> test "delete_if retains permitted status" do
<ide> @params.permit!
<del> assert @params.delete_if { |k| k == "person" }.permitted?
<add> assert_predicate @params.delete_if { |k| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "delete_if retains unpermitted status" do
<del> assert_not @params.delete_if { |k| k == "person" }.permitted?
<add> assert_not_predicate @params.delete_if { |k| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "extract! retains permitted status" do
<ide> @params.permit!
<del> assert @params.extract!(:person).permitted?
<add> assert_predicate @params.extract!(:person), :permitted?
<ide> end
<ide>
<ide> test "extract! retains unpermitted status" do
<del> assert_not @params.extract!(:person).permitted?
<add> assert_not_predicate @params.extract!(:person), :permitted?
<ide> end
<ide>
<ide> test "keep_if retains permitted status" do
<ide> @params.permit!
<del> assert @params.keep_if { |k, v| k == "person" }.permitted?
<add> assert_predicate @params.keep_if { |k, v| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "keep_if retains unpermitted status" do
<del> assert_not @params.keep_if { |k, v| k == "person" }.permitted?
<add> assert_not_predicate @params.keep_if { |k, v| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "reject! retains permitted status" do
<ide> @params.permit!
<del> assert @params.reject! { |k| k == "person" }.permitted?
<add> assert_predicate @params.reject! { |k| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "reject! retains unpermitted status" do
<del> assert_not @params.reject! { |k| k == "person" }.permitted?
<add> assert_not_predicate @params.reject! { |k| k == "person" }, :permitted?
<ide> end
<ide>
<ide> test "select! retains permitted status" do
<ide> @params.permit!
<del> assert @params.select! { |k| k != "person" }.permitted?
<add> assert_predicate @params.select! { |k| k != "person" }, :permitted?
<ide> end
<ide>
<ide> test "select! retains unpermitted status" do
<del> assert_not @params.select! { |k| k != "person" }.permitted?
<add> assert_not_predicate @params.select! { |k| k != "person" }, :permitted?
<ide> end
<ide>
<ide> test "slice! retains permitted status" do
<ide> @params.permit!
<del> assert @params.slice!(:person).permitted?
<add> assert_predicate @params.slice!(:person), :permitted?
<ide> end
<ide>
<ide> test "slice! retains unpermitted status" do
<del> assert_not @params.slice!(:person).permitted?
<add> assert_not_predicate @params.slice!(:person), :permitted?
<ide> end
<ide>
<ide> test "transform_keys! retains permitted status" do
<ide> @params.permit!
<del> assert @params.transform_keys! { |k| k }.permitted?
<add> assert_predicate @params.transform_keys! { |k| k }, :permitted?
<ide> end
<ide>
<ide> test "transform_keys! retains unpermitted status" do
<del> assert_not @params.transform_keys! { |k| k }.permitted?
<add> assert_not_predicate @params.transform_keys! { |k| k }, :permitted?
<ide> end
<ide>
<ide> test "transform_values! retains permitted status" do
<ide> @params.permit!
<del> assert @params.transform_values! { |v| v }.permitted?
<add> assert_predicate @params.transform_values! { |v| v }, :permitted?
<ide> end
<ide>
<ide> test "transform_values! retains unpermitted status" do
<del> assert_not @params.transform_values! { |v| v }.permitted?
<add> assert_not_predicate @params.transform_values! { |v| v }, :permitted?
<ide> end
<ide> end
<ide><path>actionpack/test/controller/parameters/nested_parameters_permit_test.rb
<ide> def assert_filtered_out(params, key)
<ide>
<ide> permitted = params.permit book: [ :title, { authors: [ :name ] }, { details: :pages }, :id ]
<ide>
<del> assert permitted.permitted?
<add> assert_predicate permitted, :permitted?
<ide> assert_equal "Romeo and Juliet", permitted[:book][:title]
<ide> assert_equal "William Shakespeare", permitted[:book][:authors][0][:name]
<ide> assert_equal "Christopher Marlowe", permitted[:book][:authors][1][:name]
<ide><path>actionpack/test/controller/parameters/parameters_permit_test.rb
<ide> def walk_permitted(params)
<ide> test "if nothing is permitted, the hash becomes empty" do
<ide> params = ActionController::Parameters.new(id: "1234")
<ide> permitted = params.permit
<del> assert permitted.permitted?
<del> assert permitted.empty?
<add> assert_predicate permitted, :permitted?
<add> assert_predicate permitted, :empty?
<ide> end
<ide>
<ide> test "key: permitted scalar values" do
<ide> def walk_permitted(params)
<ide> test "hashes in array values get wrapped" do
<ide> params = ActionController::Parameters.new(foo: [{}, {}])
<ide> params[:foo].each do |hash|
<del> assert !hash.permitted?
<add> assert_not_predicate hash, :permitted?
<ide> end
<ide> end
<ide>
<ide> def walk_permitted(params)
<ide>
<ide> permitted = params.permit(users: [:id])
<ide> permitted[:users] << { injected: 1 }
<del> assert_not permitted[:users].last.permitted?
<add> assert_not_predicate permitted[:users].last, :permitted?
<ide> end
<ide>
<ide> test "fetch doesnt raise ParameterMissing exception if there is a default" do
<ide> def walk_permitted(params)
<ide> end
<ide>
<ide> test "not permitted is sticky beyond merges" do
<del> assert !@params.merge(a: "b").permitted?
<add> assert_not_predicate @params.merge(a: "b"), :permitted?
<ide> end
<ide>
<ide> test "permitted is sticky beyond merges" do
<ide> @params.permit!
<del> assert @params.merge(a: "b").permitted?
<add> assert_predicate @params.merge(a: "b"), :permitted?
<ide> end
<ide>
<ide> test "merge with parameters" do
<ide> def walk_permitted(params)
<ide> end
<ide>
<ide> test "not permitted is sticky beyond merge!" do
<del> assert_not @params.merge!(a: "b").permitted?
<add> assert_not_predicate @params.merge!(a: "b"), :permitted?
<ide> end
<ide>
<ide> test "permitted is sticky beyond merge!" do
<ide> @params.permit!
<del> assert @params.merge!(a: "b").permitted?
<add> assert_predicate @params.merge!(a: "b"), :permitted?
<ide> end
<ide>
<ide> test "merge! with parameters" do
<ide> def walk_permitted(params)
<ide>
<ide> test "permit is recursive" do
<ide> @params.permit!
<del> assert @params.permitted?
<del> assert @params[:person].permitted?
<del> assert @params[:person][:name].permitted?
<del> assert @params[:person][:addresses][0].permitted?
<add> assert_predicate @params, :permitted?
<add> assert_predicate @params[:person], :permitted?
<add> assert_predicate @params[:person][:name], :permitted?
<add> assert_predicate @params[:person][:addresses][0], :permitted?
<ide> end
<ide>
<ide> test "permitted takes a default value when Parameters.permit_all_parameters is set" do
<ide> def walk_permitted(params)
<ide> age: "32", name: { first: "David", last: "Heinemeier Hansson" }
<ide> })
<ide>
<del> assert params.slice(:person).permitted?
<del> assert params[:person][:name].permitted?
<add> assert_predicate params.slice(:person), :permitted?
<add> assert_predicate params[:person][:name], :permitted?
<ide> ensure
<ide> ActionController::Parameters.permit_all_parameters = false
<ide> end
<ide><path>actionpack/test/controller/parameters/serialization_test.rb
<ide> class ParametersSerializationTest < ActiveSupport::TestCase
<ide> roundtripped = YAML.load(YAML.dump(params))
<ide>
<ide> assert_equal params, roundtripped
<del> assert_not roundtripped.permitted?
<add> assert_not_predicate roundtripped, :permitted?
<ide> end
<ide>
<ide> test "yaml backwardscompatible with psych 2.0.8 format" do
<ide> class ParametersSerializationTest < ActiveSupport::TestCase
<ide> end_of_yaml
<ide>
<ide> assert_equal :value, params[:key]
<del> assert_not params.permitted?
<add> assert_not_predicate params, :permitted?
<ide> end
<ide>
<ide> test "yaml backwardscompatible with psych 2.0.9+ format" do
<ide> class ParametersSerializationTest < ActiveSupport::TestCase
<ide> end_of_yaml
<ide>
<ide> assert_equal :value, params[:key]
<del> assert_not params.permitted?
<add> assert_not_predicate params, :permitted?
<ide> end
<ide> end
<ide><path>actionpack/test/controller/render_test.rb
<ide> def test_request_not_modified
<ide> @request.if_modified_since = @last_modified
<ide> get :conditional_hello
<ide> assert_equal 304, @response.status.to_i
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal @last_modified, @response.headers["Last-Modified"]
<ide> end
<ide>
<ide> def test_request_modified
<ide> @request.if_modified_since = "Thu, 16 Jul 2008 00:00:00 GMT"
<ide> get :conditional_hello
<ide> assert_equal 200, @response.status.to_i
<del> assert @response.body.present?
<add> assert_predicate @response.body, :present?
<ide> assert_equal @last_modified, @response.headers["Last-Modified"]
<ide> end
<ide>
<ide> def test_request_not_modified_with_record
<ide> @request.if_modified_since = @last_modified
<ide> get :conditional_hello_with_record
<ide> assert_equal 304, @response.status.to_i
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_not_nil @response.etag
<ide> assert_equal @last_modified, @response.headers["Last-Modified"]
<ide> end
<ide> def test_request_modified_with_record
<ide> @request.if_modified_since = "Thu, 16 Jul 2008 00:00:00 GMT"
<ide> get :conditional_hello_with_record
<ide> assert_equal 200, @response.status.to_i
<del> assert @response.body.present?
<add> assert_predicate @response.body, :present?
<ide> assert_equal @last_modified, @response.headers["Last-Modified"]
<ide> end
<ide>
<ide> def test_request_not_modified_with_collection_of_records
<ide> @request.if_modified_since = @last_modified
<ide> get :conditional_hello_with_collection_of_records
<ide> assert_equal 304, @response.status.to_i
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal @last_modified, @response.headers["Last-Modified"]
<ide> end
<ide>
<ide> def test_request_modified_with_collection_of_records
<ide> @request.if_modified_since = "Thu, 16 Jul 2008 00:00:00 GMT"
<ide> get :conditional_hello_with_collection_of_records
<ide> assert_equal 200, @response.status.to_i
<del> assert @response.body.present?
<add> assert_predicate @response.body, :present?
<ide> assert_equal @last_modified, @response.headers["Last-Modified"]
<ide> end
<ide>
<ide> def setup
<ide>
<ide> def test_head_created
<ide> post :head_created
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_response :created
<ide> end
<ide>
<ide> def test_head_created_with_application_json_content_type
<ide> post :head_created_with_application_json_content_type
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal "application/json", @response.header["Content-Type"]
<ide> assert_response :created
<ide> end
<ide>
<ide> def test_head_ok_with_image_png_content_type
<ide> post :head_ok_with_image_png_content_type
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal "image/png", @response.header["Content-Type"]
<ide> assert_response :ok
<ide> end
<ide>
<ide> def test_head_with_location_header
<ide> get :head_with_location_header
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal "/foo", @response.headers["Location"]
<ide> assert_response :ok
<ide> end
<ide> def test_head_with_location_object
<ide> end
<ide>
<ide> get :head_with_location_object
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"]
<ide> assert_response :ok
<ide> end
<ide> end
<ide>
<ide> def test_head_with_custom_header
<ide> get :head_with_custom_header
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal "something", @response.headers["X-Custom-Header"]
<ide> assert_response :ok
<ide> end
<ide>
<ide> def test_head_with_www_authenticate_header
<ide> get :head_with_www_authenticate_header
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> assert_equal "something", @response.headers["WWW-Authenticate"]
<ide> assert_response :ok
<ide> end
<ide> def test_cache_with_public
<ide> assert_response :ok
<ide> assert_equal "max-age=#{100.years}, public", @response.headers["Cache-Control"]
<ide> assert_not_nil @response.etag
<del> assert @response.weak_etag?
<add> assert_predicate @response, :weak_etag?
<ide> end
<ide>
<ide> def test_cache_with_private
<ide> get :cache_me_forever
<ide> assert_response :ok
<ide> assert_equal "max-age=#{100.years}, private", @response.headers["Cache-Control"]
<ide> assert_not_nil @response.etag
<del> assert @response.weak_etag?
<add> assert_predicate @response, :weak_etag?
<ide> end
<ide>
<ide> def test_cache_response_code_with_if_modified_since
<ide><path>actionpack/test/controller/request_forgery_protection_test.rb
<ide> def test_should_allow_all_methods_without_token
<ide> test "should not emit a csrf-token meta tag" do
<ide> SecureRandom.stub :base64, @token do
<ide> get :meta
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/controller/test_case_test.rb
<ide> def test_params_reset_between_post_requests
<ide> assert_equal "bar", @request.params[:foo]
<ide>
<ide> post :no_op
<del> assert @request.params[:foo].blank?
<add> assert_predicate @request.params[:foo], :blank?
<ide> end
<ide>
<ide> def test_filtered_parameters_reset_between_requests
<ide><path>actionpack/test/dispatch/live_response_test.rb
<ide> def test_headers_cannot_be_written_after_webserver_reads
<ide> }
<ide>
<ide> latch.wait
<del> assert @response.headers.frozen?
<add> assert_predicate @response.headers, :frozen?
<ide> e = assert_raises(ActionDispatch::IllegalStateError) do
<ide> @response.headers["Content-Length"] = "zomg"
<ide> end
<ide><path>actionpack/test/dispatch/request_test.rb
<ide> class RequestPort < BaseRequestTest
<ide>
<ide> test "standard_port?" do
<ide> request = stub_request
<del> assert !request.ssl?
<del> assert request.standard_port?
<add> assert_not_predicate request, :ssl?
<add> assert_predicate request, :standard_port?
<ide>
<ide> request = stub_request "HTTPS" => "on"
<del> assert request.ssl?
<del> assert request.standard_port?
<add> assert_predicate request, :ssl?
<add> assert_predicate request, :standard_port?
<ide>
<ide> request = stub_request "HTTP_HOST" => "www.example.org:8080"
<del> assert !request.ssl?
<del> assert !request.standard_port?
<add> assert_not_predicate request, :ssl?
<add> assert_not_predicate request, :standard_port?
<ide>
<ide> request = stub_request "HTTP_HOST" => "www.example.org:8443", "HTTPS" => "on"
<del> assert request.ssl?
<del> assert !request.standard_port?
<add> assert_predicate request, :ssl?
<add> assert_not_predicate request, :standard_port?
<ide> end
<ide>
<ide> test "optional port" do
<ide> class RequestCGI < BaseRequestTest
<ide> class LocalhostTest < BaseRequestTest
<ide> test "IPs that match localhost" do
<ide> request = stub_request("REMOTE_IP" => "127.1.1.1", "REMOTE_ADDR" => "127.1.1.1")
<del> assert request.local?
<add> assert_predicate request, :local?
<ide> end
<ide> end
<ide>
<ide> class RequestProtocol < BaseRequestTest
<ide> test "xml http request" do
<ide> request = stub_request
<ide>
<del> assert !request.xml_http_request?
<del> assert !request.xhr?
<add> assert_not_predicate request, :xml_http_request?
<add> assert_not_predicate request, :xhr?
<ide>
<ide> request = stub_request "HTTP_X_REQUESTED_WITH" => "DefinitelyNotAjax1.0"
<del> assert !request.xml_http_request?
<del> assert !request.xhr?
<add> assert_not_predicate request, :xml_http_request?
<add> assert_not_predicate request, :xhr?
<ide>
<ide> request = stub_request "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"
<del> assert request.xml_http_request?
<del> assert request.xhr?
<add> assert_predicate request, :xml_http_request?
<add> assert_predicate request, :xhr?
<ide> end
<ide>
<ide> test "reports ssl" do
<del> assert !stub_request.ssl?
<del> assert stub_request("HTTPS" => "on").ssl?
<add> assert_not_predicate stub_request, :ssl?
<add> assert_predicate stub_request("HTTPS" => "on"), :ssl?
<ide> end
<ide>
<ide> test "reports ssl when proxied via lighttpd" do
<del> assert stub_request("HTTP_X_FORWARDED_PROTO" => "https").ssl?
<add> assert_predicate stub_request("HTTP_X_FORWARDED_PROTO" => "https"), :ssl?
<ide> end
<ide>
<ide> test "scheme returns https when proxied" do
<ide> request = stub_request "rack.url_scheme" => "http"
<del> assert !request.ssl?
<add> assert_not_predicate request, :ssl?
<ide> assert_equal "http", request.scheme
<ide>
<ide> request = stub_request(
<ide> "rack.url_scheme" => "http",
<ide> "HTTP_X_FORWARDED_PROTO" => "https"
<ide> )
<del> assert request.ssl?
<add> assert_predicate request, :ssl?
<ide> assert_equal "https", request.scheme
<ide> end
<ide> end
<ide> class RequestMethod < BaseRequestTest
<ide>
<ide> assert_equal "GET", request.request_method
<ide> assert_equal "GET", request.env["REQUEST_METHOD"]
<del> assert request.get?
<add> assert_predicate request, :get?
<ide> end
<ide>
<ide> test "invalid http method raises exception" do
<ide> class RequestMethod < BaseRequestTest
<ide>
<ide> assert_equal "POST", request.method
<ide> assert_equal "PATCH", request.request_method
<del> assert request.patch?
<add> assert_predicate request, :patch?
<ide> end
<ide>
<ide> test "post masquerading as put" do
<ide> class RequestMethod < BaseRequestTest
<ide> )
<ide> assert_equal "POST", request.method
<ide> assert_equal "PUT", request.request_method
<del> assert request.put?
<add> assert_predicate request, :put?
<ide> end
<ide>
<ide> test "post uneffected by local inflections" do
<ide> class RequestMethod < BaseRequestTest
<ide> request = stub_request "REQUEST_METHOD" => "POST"
<ide> assert_equal :post, ActionDispatch::Request::HTTP_METHOD_LOOKUP["POST"]
<ide> assert_equal :post, request.method_symbol
<del> assert request.post?
<add> assert_predicate request, :post?
<ide> ensure
<ide> # Reset original acronym set
<ide> ActiveSupport::Inflector.inflections do |inflect|
<ide> class RequestFormat < BaseRequestTest
<ide> "QUERY_STRING" => ""
<ide> )
<ide>
<del> assert request.xhr?
<add> assert_predicate request, :xhr?
<ide> assert_equal Mime[:js], request.format
<ide> end
<ide>
<ide> test "can override format with parameter negative" do
<ide> request = stub_request("QUERY_STRING" => "format=txt")
<ide>
<del> assert !request.format.xml?
<add> assert_not_predicate request.format, :xml?
<ide> end
<ide>
<ide> test "can override format with parameter positive" do
<ide> request = stub_request("QUERY_STRING" => "format=xml")
<ide>
<del> assert request.format.xml?
<add> assert_predicate request.format, :xml?
<ide> end
<ide>
<ide> test "formats text/html with accept header" do
<ide> class RequestFormat < BaseRequestTest
<ide> request = stub_request("QUERY_STRING" => "format=hello")
<ide>
<ide> assert_nil request.format
<del> assert_not request.format.html?
<del> assert_not request.format.xml?
<del> assert_not request.format.json?
<add> assert_not_predicate request.format, :html?
<add> assert_not_predicate request.format, :xml?
<add> assert_not_predicate request.format, :json?
<ide> end
<ide>
<ide> test "format does not throw exceptions when malformed parameters" do
<ide> request = stub_request("QUERY_STRING" => "x[y]=1&x[y][][w]=2")
<ide> assert request.formats
<del> assert request.format.html?
<add> assert_predicate request.format, :html?
<ide> end
<ide>
<ide> test "formats with xhr request" do
<ide> def setup
<ide> test "setting variant to a symbol" do
<ide> @request.variant = :phone
<ide>
<del> assert @request.variant.phone?
<del> assert_not @request.variant.tablet?
<add> assert_predicate @request.variant, :phone?
<add> assert_not_predicate @request.variant, :tablet?
<ide> assert @request.variant.any?(:phone, :tablet)
<ide> assert_not @request.variant.any?(:tablet, :desktop)
<ide> end
<ide>
<ide> test "setting variant to an array of symbols" do
<ide> @request.variant = [:phone, :tablet]
<ide>
<del> assert @request.variant.phone?
<del> assert @request.variant.tablet?
<del> assert_not @request.variant.desktop?
<add> assert_predicate @request.variant, :phone?
<add> assert_predicate @request.variant, :tablet?
<add> assert_not_predicate @request.variant, :desktop?
<ide> assert @request.variant.any?(:tablet, :desktop)
<ide> assert_not @request.variant.any?(:desktop, :watch)
<ide> end
<ide>
<ide> test "clearing variant" do
<ide> @request.variant = nil
<ide>
<del> assert @request.variant.empty?
<del> assert_not @request.variant.phone?
<add> assert_predicate @request.variant, :empty?
<add> assert_not_predicate @request.variant, :phone?
<ide> assert_not @request.variant.any?(:phone, :tablet)
<ide> end
<ide>
<ide> def setup
<ide>
<ide> class RequestFormData < BaseRequestTest
<ide> test "media_type is from the FORM_DATA_MEDIA_TYPES array" do
<del> assert stub_request("CONTENT_TYPE" => "application/x-www-form-urlencoded").form_data?
<del> assert stub_request("CONTENT_TYPE" => "multipart/form-data").form_data?
<add> assert_predicate stub_request("CONTENT_TYPE" => "application/x-www-form-urlencoded"), :form_data?
<add> assert_predicate stub_request("CONTENT_TYPE" => "multipart/form-data"), :form_data?
<ide> end
<ide>
<ide> test "media_type is not from the FORM_DATA_MEDIA_TYPES array" do
<del> assert !stub_request("CONTENT_TYPE" => "application/xml").form_data?
<del> assert !stub_request("CONTENT_TYPE" => "multipart/related").form_data?
<add> assert_not_predicate stub_request("CONTENT_TYPE" => "application/xml"), :form_data?
<add> assert_not_predicate stub_request("CONTENT_TYPE" => "multipart/related"), :form_data?
<ide> end
<ide>
<ide> test "no Content-Type header is provided and the request_method is POST" do
<ide> request = stub_request("REQUEST_METHOD" => "POST")
<ide>
<ide> assert_equal "", request.media_type
<ide> assert_equal "POST", request.request_method
<del> assert !request.form_data?
<add> assert_not_predicate request, :form_data?
<ide> end
<ide> end
<ide>
<ide><path>actionpack/test/dispatch/response_test.rb
<ide> def test_can_wait_until_commit
<ide> @response.await_commit
<ide> }
<ide> @response.commit!
<del> assert @response.committed?
<add> assert_predicate @response, :committed?
<ide> assert t.join(0.5)
<ide> end
<ide>
<ide> def test_stream_close
<ide> @response.stream.close
<del> assert @response.stream.closed?
<add> assert_predicate @response.stream, :closed?
<ide> end
<ide>
<ide> def test_stream_write
<ide> def test_only_set_charset_still_defaults_to_text_html
<ide> }
<ide> resp.to_a
<ide>
<del> assert resp.etag?
<del> assert resp.weak_etag?
<del> assert_not resp.strong_etag?
<add> assert_predicate resp, :etag?
<add> assert_predicate resp, :weak_etag?
<add> assert_not_predicate resp, :strong_etag?
<ide> assert_equal('W/"202cb962ac59075b964b07152d234b70"', resp.etag)
<ide> assert_equal({ public: true }, resp.cache_control)
<ide>
<ide> def test_only_set_charset_still_defaults_to_text_html
<ide> }
<ide> resp.to_a
<ide>
<del> assert resp.etag?
<del> assert_not resp.weak_etag?
<del> assert resp.strong_etag?
<add> assert_predicate resp, :etag?
<add> assert_not_predicate resp, :weak_etag?
<add> assert_predicate resp, :strong_etag?
<ide> assert_equal('"202cb962ac59075b964b07152d234b70"', resp.etag)
<ide> end
<ide>
<ide><path>actionpack/test/dispatch/routing_test.rb
<ide> def test_action_from_path_is_not_frozen
<ide> end
<ide>
<ide> get "/search"
<del> assert !@request.params[:action].frozen?
<add> assert_not_predicate @request.params[:action], :frozen?
<ide> end
<ide>
<ide> def test_multiple_positional_args_with_the_same_name
<ide> class TestOptimizedNamedRoutes < ActionDispatch::IntegrationTest
<ide> def app; APP end
<ide>
<ide> test "enabled when not mounted and default_url_options is empty" do
<del> assert Routes.url_helpers.optimize_routes_generation?
<add> assert_predicate Routes.url_helpers, :optimize_routes_generation?
<ide> end
<ide>
<ide> test "named route called as singleton method" do
<ide><path>actionpack/test/dispatch/uploaded_file_test.rb
<ide> def test_delegate_respects_respond_to?
<ide> def test_delegate_eof_to_tempfile
<ide> tf = Class.new { def eof?; true end; }
<ide> uf = Http::UploadedFile.new(tempfile: tf.new)
<del> assert uf.eof?
<add> assert_predicate uf, :eof?
<ide> end
<ide>
<ide> def test_respond_to?
<ide><path>actionpack/test/journey/nodes/symbol_test.rb
<ide> module Nodes
<ide> class TestSymbol < ActiveSupport::TestCase
<ide> def test_default_regexp?
<ide> sym = Symbol.new "foo"
<del> assert sym.default_regexp?
<add> assert_predicate sym, :default_regexp?
<ide>
<ide> sym.regexp = nil
<del> assert_not sym.default_regexp?
<add> assert_not_predicate sym, :default_regexp?
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/journey/routes_test.rb
<ide> def test_clear
<ide> assert_equal 1, routes.length
<ide>
<ide> routes.clear
<del> assert routes.empty?
<add> assert_predicate routes, :empty?
<ide> assert_equal 0, routes.length
<ide> end
<ide>
<ide><path>actionview/test/template/asset_tag_helper_test.rb
<ide> def test_javascript_include_tag_with_missing_source
<ide> end
<ide>
<ide> def test_javascript_include_tag_is_html_safe
<del> assert javascript_include_tag("prototype").html_safe?
<add> assert_predicate javascript_include_tag("prototype"), :html_safe?
<ide> end
<ide>
<ide> def test_javascript_include_tag_relative_protocol
<ide> def test_stylesheet_link_tag_without_request
<ide> end
<ide>
<ide> def test_stylesheet_link_tag_is_html_safe
<del> assert stylesheet_link_tag("dir/file").html_safe?
<del> assert stylesheet_link_tag("dir/other/file", "dir/file2").html_safe?
<add> assert_predicate stylesheet_link_tag("dir/file"), :html_safe?
<add> assert_predicate stylesheet_link_tag("dir/other/file", "dir/file2"), :html_safe?
<ide> end
<ide>
<ide> def test_stylesheet_link_tag_escapes_options
<ide><path>actionview/test/template/atom_feed_helper_test.rb
<ide> def test_providing_builder_to_atom_feed
<ide> get :index, params: { id: "provide_builder" }
<ide> # because we pass in the non-default builder, the content generated by the
<ide> # helper should go 'nowhere'. Leaving the response body blank.
<del> assert @response.body.blank?
<add> assert_predicate @response.body, :blank?
<ide> end
<ide> end
<ide>
<ide><path>actionview/test/template/capture_helper_test.rb
<ide> def test_content_for_should_be_html_safe_after_flush_empty
<ide> content_for :title do
<ide> content_tag(:p, "title")
<ide> end
<del> assert content_for(:title).html_safe?
<add> assert_predicate content_for(:title), :html_safe?
<ide> content_for :title, "", flush: true
<ide> content_for(:title) do
<ide> content_tag(:p, "title")
<ide> end
<del> assert content_for(:title).html_safe?
<add> assert_predicate content_for(:title), :html_safe?
<ide> end
<ide>
<ide> def test_provide
<ide><path>actionview/test/template/date_helper_test.rb
<ide> def test_select_time_should_not_change_passed_options_hash
<ide> end
<ide>
<ide> def test_select_html_safety
<del> assert select_day(16).html_safe?
<del> assert select_month(8).html_safe?
<del> assert select_year(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe?
<del> assert select_minute(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe?
<del> assert select_second(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe?
<add> assert_predicate select_day(16), :html_safe?
<add> assert_predicate select_month(8), :html_safe?
<add> assert_predicate select_year(Time.mktime(2003, 8, 16, 8, 4, 18)), :html_safe?
<add> assert_predicate select_minute(Time.mktime(2003, 8, 16, 8, 4, 18)), :html_safe?
<add> assert_predicate select_second(Time.mktime(2003, 8, 16, 8, 4, 18)), :html_safe?
<ide>
<del> assert select_minute(8, use_hidden: true).html_safe?
<del> assert select_month(8, prompt: "Choose month").html_safe?
<add> assert_predicate select_minute(8, use_hidden: true), :html_safe?
<add> assert_predicate select_month(8, prompt: "Choose month"), :html_safe?
<ide>
<del> assert select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, { class: "selector" }).html_safe?
<del> assert select_date(Time.mktime(2003, 8, 16), date_separator: " / ", start_year: 2003, end_year: 2005, prefix: "date[first]").html_safe?
<add> assert_predicate select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, { class: "selector" }), :html_safe?
<add> assert_predicate select_date(Time.mktime(2003, 8, 16), date_separator: " / ", start_year: 2003, end_year: 2005, prefix: "date[first]"), :html_safe?
<ide> end
<ide>
<ide> def test_object_select_html_safety
<ide> @post = Post.new
<ide> @post.written_on = Date.new(2004, 6, 15)
<ide>
<del> assert date_select("post", "written_on", default: Time.local(2006, 9, 19, 15, 16, 35), include_blank: true).html_safe?
<del> assert time_select("post", "written_on", ignore_date: true).html_safe?
<add> assert_predicate date_select("post", "written_on", default: Time.local(2006, 9, 19, 15, 16, 35), include_blank: true), :html_safe?
<add> assert_predicate time_select("post", "written_on", ignore_date: true), :html_safe?
<ide> end
<ide>
<ide> def test_time_tag_with_date
<ide><path>actionview/test/template/erb_util_test.rb
<ide> def test_json_escape_is_idempotent
<ide>
<ide> def test_json_escape_returns_unsafe_strings_when_passed_unsafe_strings
<ide> value = json_escape("asdf")
<del> assert !value.html_safe?
<add> assert_not_predicate value, :html_safe?
<ide> end
<ide>
<ide> def test_json_escape_returns_safe_strings_when_passed_safe_strings
<ide> value = json_escape("asdf".html_safe)
<del> assert value.html_safe?
<add> assert_predicate value, :html_safe?
<ide> end
<ide>
<ide> def test_html_escape_is_html_safe
<ide> escaped = h("<p>")
<ide> assert_equal "<p>", escaped
<del> assert escaped.html_safe?
<add> assert_predicate escaped, :html_safe?
<ide> end
<ide>
<ide> def test_html_escape_passes_html_escape_unmodified
<ide> escaped = h("<p>".html_safe)
<ide> assert_equal "<p>", escaped
<del> assert escaped.html_safe?
<add> assert_predicate escaped, :html_safe?
<ide> end
<ide>
<ide> def test_rest_in_ascii
<ide> def test_html_escape_once
<ide>
<ide> def test_html_escape_once_returns_unsafe_strings_when_passed_unsafe_strings
<ide> value = html_escape_once("1 < 2 & 3")
<del> assert !value.html_safe?
<add> assert_not_predicate value, :html_safe?
<ide> end
<ide>
<ide> def test_html_escape_once_returns_safe_strings_when_passed_safe_strings
<ide> value = html_escape_once("1 < 2 & 3".html_safe)
<del> assert value.html_safe?
<add> assert_predicate value, :html_safe?
<ide> end
<ide> end
<ide><path>actionview/test/template/form_helper/form_with_test.rb
<ide> def test_form_with_skip_enforcing_utf8_true
<ide> actual = form_with(skip_enforcing_utf8: true)
<ide> expected = whole_form("http://www.example.com", skip_enforcing_utf8: true)
<ide> assert_dom_equal expected, actual
<del> assert actual.html_safe?
<add> assert_predicate actual, :html_safe?
<ide> end
<ide>
<ide> def test_form_with_with_block_in_erb
<ide><path>actionview/test/template/form_helper_test.rb
<ide> def test_text_field_with_custom_type
<ide> end
<ide>
<ide> def test_check_box_is_html_safe
<del> assert check_box("post", "secret").html_safe?
<add> assert_predicate check_box("post", "secret"), :html_safe?
<ide> end
<ide>
<ide> def test_check_box_checked_if_object_value_is_same_that_check_value
<ide> def test_check_box_with_nil_unchecked_value
<ide> end
<ide>
<ide> def test_check_box_with_nil_unchecked_value_is_html_safe
<del> assert check_box("post", "secret", {}, "on", nil).html_safe?
<add> assert_predicate check_box("post", "secret", {}, "on", nil), :html_safe?
<ide> end
<ide>
<ide> def test_check_box_with_multiple_behavior
<ide><path>actionview/test/template/form_options_helper_test.rb
<ide> def test_option_groups_from_collection_for_select_with_callable_group_label_meth
<ide> end
<ide>
<ide> def test_option_groups_from_collection_for_select_returns_html_safe_string
<del> assert option_groups_from_collection_for_select(dummy_continents, "countries", "continent_name", "country_id", "country_name", "dk").html_safe?
<add> assert_predicate option_groups_from_collection_for_select(dummy_continents, "countries", "continent_name", "country_id", "country_name", "dk"), :html_safe?
<ide> end
<ide>
<ide> def test_grouped_options_for_select_with_array
<ide> def test_grouped_options_for_select_with_selected_and_prompt_true
<ide> end
<ide>
<ide> def test_grouped_options_for_select_returns_html_safe_string
<del> assert grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]]).html_safe?
<add> assert_predicate grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]]), :html_safe?
<ide> end
<ide>
<ide> def test_grouped_options_for_select_with_prompt_returns_html_escaped_string
<ide> def test_time_zone_options_with_priority_zones_does_not_mutate_time_zones
<ide> end
<ide>
<ide> def test_time_zone_options_returns_html_safe_string
<del> assert time_zone_options_for_select.html_safe?
<add> assert_predicate time_zone_options_for_select, :html_safe?
<ide> end
<ide>
<ide> def test_select
<ide><path>actionview/test/template/form_tag_helper_test.rb
<ide> def test_form_tag_enforce_utf8_true
<ide> actual = form_tag({}, { enforce_utf8: true })
<ide> expected = whole_form("http://www.example.com", enforce_utf8: true)
<ide> assert_dom_equal expected, actual
<del> assert actual.html_safe?
<add> assert_predicate actual, :html_safe?
<ide> end
<ide>
<ide> def test_form_tag_enforce_utf8_false
<ide> actual = form_tag({}, { enforce_utf8: false })
<ide> expected = whole_form("http://www.example.com", enforce_utf8: false)
<ide> assert_dom_equal expected, actual
<del> assert actual.html_safe?
<add> assert_predicate actual, :html_safe?
<ide> end
<ide>
<ide> def test_form_tag_with_block_in_erb
<ide><path>actionview/test/template/lookup_context_test.rb
<ide> def teardown
<ide>
<ide> test "allows me to freeze and retrieve frozen formats" do
<ide> @lookup_context.formats.freeze
<del> assert @lookup_context.formats.frozen?
<add> assert_predicate @lookup_context.formats, :frozen?
<ide> end
<ide>
<ide> test "provides getters and setters for variants" do
<ide><path>actionview/test/template/number_helper_test.rb
<ide> def test_number_to_human_with_custom_translation_scope
<ide> end
<ide>
<ide> def test_number_helpers_outputs_are_html_safe
<del> assert number_to_human(1).html_safe?
<del> assert !number_to_human("<script></script>").html_safe?
<del> assert number_to_human("asdf".html_safe).html_safe?
<del> assert number_to_human("1".html_safe).html_safe?
<del>
<del> assert number_to_human_size(1).html_safe?
<del> assert number_to_human_size(1000000).html_safe?
<del> assert !number_to_human_size("<script></script>").html_safe?
<del> assert number_to_human_size("asdf".html_safe).html_safe?
<del> assert number_to_human_size("1".html_safe).html_safe?
<del>
<del> assert number_with_precision(1, strip_insignificant_zeros: false).html_safe?
<del> assert number_with_precision(1, strip_insignificant_zeros: true).html_safe?
<del> assert !number_with_precision("<script></script>").html_safe?
<del> assert number_with_precision("asdf".html_safe).html_safe?
<del> assert number_with_precision("1".html_safe).html_safe?
<del>
<del> assert number_to_currency(1).html_safe?
<del> assert !number_to_currency("<script></script>").html_safe?
<del> assert number_to_currency("asdf".html_safe).html_safe?
<del> assert number_to_currency("1".html_safe).html_safe?
<del>
<del> assert number_to_percentage(1).html_safe?
<del> assert !number_to_percentage("<script></script>").html_safe?
<del> assert number_to_percentage("asdf".html_safe).html_safe?
<del> assert number_to_percentage("1".html_safe).html_safe?
<del>
<del> assert number_to_phone(1).html_safe?
<add> assert_predicate number_to_human(1), :html_safe?
<add> assert_not_predicate number_to_human("<script></script>"), :html_safe?
<add> assert_predicate number_to_human("asdf".html_safe), :html_safe?
<add> assert_predicate number_to_human("1".html_safe), :html_safe?
<add>
<add> assert_predicate number_to_human_size(1), :html_safe?
<add> assert_predicate number_to_human_size(1000000), :html_safe?
<add> assert_not_predicate number_to_human_size("<script></script>"), :html_safe?
<add> assert_predicate number_to_human_size("asdf".html_safe), :html_safe?
<add> assert_predicate number_to_human_size("1".html_safe), :html_safe?
<add>
<add> assert_predicate number_with_precision(1, strip_insignificant_zeros: false), :html_safe?
<add> assert_predicate number_with_precision(1, strip_insignificant_zeros: true), :html_safe?
<add> assert_not_predicate number_with_precision("<script></script>"), :html_safe?
<add> assert_predicate number_with_precision("asdf".html_safe), :html_safe?
<add> assert_predicate number_with_precision("1".html_safe), :html_safe?
<add>
<add> assert_predicate number_to_currency(1), :html_safe?
<add> assert_not_predicate number_to_currency("<script></script>"), :html_safe?
<add> assert_predicate number_to_currency("asdf".html_safe), :html_safe?
<add> assert_predicate number_to_currency("1".html_safe), :html_safe?
<add>
<add> assert_predicate number_to_percentage(1), :html_safe?
<add> assert_not_predicate number_to_percentage("<script></script>"), :html_safe?
<add> assert_predicate number_to_percentage("asdf".html_safe), :html_safe?
<add> assert_predicate number_to_percentage("1".html_safe), :html_safe?
<add>
<add> assert_predicate number_to_phone(1), :html_safe?
<ide> assert_equal "<script></script>", number_to_phone("<script></script>")
<del> assert number_to_phone("<script></script>").html_safe?
<del> assert number_to_phone("asdf".html_safe).html_safe?
<del> assert number_to_phone("1".html_safe).html_safe?
<del>
<del> assert number_with_delimiter(1).html_safe?
<del> assert !number_with_delimiter("<script></script>").html_safe?
<del> assert number_with_delimiter("asdf".html_safe).html_safe?
<del> assert number_with_delimiter("1".html_safe).html_safe?
<add> assert_predicate number_to_phone("<script></script>"), :html_safe?
<add> assert_predicate number_to_phone("asdf".html_safe), :html_safe?
<add> assert_predicate number_to_phone("1".html_safe), :html_safe?
<add>
<add> assert_predicate number_with_delimiter(1), :html_safe?
<add> assert_not_predicate number_with_delimiter("<script></script>"), :html_safe?
<add> assert_predicate number_with_delimiter("asdf".html_safe), :html_safe?
<add> assert_predicate number_with_delimiter("1".html_safe), :html_safe?
<ide> end
<ide>
<ide> def test_number_helpers_should_raise_error_if_invalid_when_specified
<ide><path>actionview/test/template/output_safety_helper_test.rb
<ide> def setup
<ide> test "raw returns the safe string" do
<ide> result = raw(@string)
<ide> assert_equal @string, result
<del> assert result.html_safe?
<add> assert_predicate result, :html_safe?
<ide> end
<ide>
<ide> test "raw handles nil values correctly" do
<ide> def setup
<ide>
<ide> test "to_sentence should escape non-html_safe values" do
<ide> actual = to_sentence(%w(< > & ' "))
<del> assert actual.html_safe?
<add> assert_predicate actual, :html_safe?
<ide> assert_equal("<, >, &, ', and "", actual)
<ide>
<ide> actual = to_sentence(%w(<script>))
<del> assert actual.html_safe?
<add> assert_predicate actual, :html_safe?
<ide> assert_equal("<script>", actual)
<ide> end
<ide>
<ide> def setup
<ide> url = "https://example.com"
<ide> expected = %(<a href="#{url}">#{url}</a> and <p><marquee>shady stuff</marquee><br /></p>)
<ide> actual = to_sentence([link_to(url, url), ptag])
<del> assert actual.html_safe?
<add> assert_predicate actual, :html_safe?
<ide> assert_equal(expected, actual)
<ide> end
<ide>
<ide> test "to_sentence handles blank strings" do
<ide> actual = to_sentence(["", "two", "three"])
<del> assert actual.html_safe?
<add> assert_predicate actual, :html_safe?
<ide> assert_equal ", two, and three", actual
<ide> end
<ide>
<ide> test "to_sentence handles nil values" do
<ide> actual = to_sentence([nil, "two", "three"])
<del> assert actual.html_safe?
<add> assert_predicate actual, :html_safe?
<ide> assert_equal ", two, and three", actual
<ide> end
<ide>
<ide><path>actionview/test/template/sanitize_helper_test.rb
<ide> def test_strip_tags_will_not_encode_special_characters
<ide> end
<ide>
<ide> def test_sanitize_is_marked_safe
<del> assert sanitize("<html><script></script></html>").html_safe?
<add> assert_predicate sanitize("<html><script></script></html>"), :html_safe?
<ide> end
<ide> end
<ide><path>actionview/test/template/tag_helper_test.rb
<ide> def test_tag_builder_options_converts_boolean_option
<ide>
<ide> def test_content_tag
<ide> assert_equal "<a href=\"create\">Create</a>", content_tag("a", "Create", "href" => "create")
<del> assert content_tag("a", "Create", "href" => "create").html_safe?
<add> assert_predicate content_tag("a", "Create", "href" => "create"), :html_safe?
<ide> assert_equal content_tag("a", "Create", "href" => "create"),
<ide> content_tag("a", "Create", href: "create")
<ide> assert_equal "<p><script>evil_js</script></p>",
<ide> def test_content_tag
<ide>
<ide> def test_tag_builder_with_content
<ide> assert_equal "<div id=\"post_1\">Content</div>", tag.div("Content", id: "post_1")
<del> assert tag.div("Content", id: "post_1").html_safe?
<add> assert_predicate tag.div("Content", id: "post_1"), :html_safe?
<ide> assert_equal tag.div("Content", id: "post_1"),
<ide> tag.div("Content", "id": "post_1")
<ide> assert_equal "<p><script>evil_js</script></p>",
<ide><path>actionview/test/template/text_helper_test.rb
<ide> def test_concat
<ide> end
<ide>
<ide> def test_simple_format_should_be_html_safe
<del> assert simple_format("<b> test with html tags </b>").html_safe?
<add> assert_predicate simple_format("<b> test with html tags </b>"), :html_safe?
<ide> end
<ide>
<ide> def test_simple_format_included_in_isolation
<ide> helper_klass = Class.new { include ActionView::Helpers::TextHelper }
<del> assert helper_klass.new.simple_format("<b> test with html tags </b>").html_safe?
<add> assert_predicate helper_klass.new.simple_format("<b> test with html tags </b>"), :html_safe?
<ide> end
<ide>
<ide> def test_simple_format
<ide> def test_truncate_with_link_options
<ide> end
<ide>
<ide> def test_truncate_should_be_html_safe
<del> assert truncate("Hello World!", length: 12).html_safe?
<add> assert_predicate truncate("Hello World!", length: 12), :html_safe?
<ide> end
<ide>
<ide> def test_truncate_should_escape_the_input
<ide> def test_truncate_should_not_escape_the_input_with_escape_false
<ide>
<ide> def test_truncate_with_escape_false_should_be_html_safe
<ide> truncated = truncate("Hello <script>code!</script>World!!", length: 12, escape: false)
<del> assert truncated.html_safe?
<add> assert_predicate truncated, :html_safe?
<ide> end
<ide>
<ide> def test_truncate_with_block_should_be_html_safe
<ide> truncated = truncate("Here's a long test and I need a continue to read link", length: 27) { link_to "Continue", "#" }
<del> assert truncated.html_safe?
<add> assert_predicate truncated, :html_safe?
<ide> end
<ide>
<ide> def test_truncate_with_block_should_escape_the_input
<ide> def test_truncate_with_block_should_not_escape_the_input_with_escape_false
<ide>
<ide> def test_truncate_with_block_with_escape_false_should_be_html_safe
<ide> truncated = truncate("<script>code!</script>Here's a long test and I need a continue to read link", length: 27, escape: false) { link_to "Continue", "#" }
<del> assert truncated.html_safe?
<add> assert_predicate truncated, :html_safe?
<ide> end
<ide>
<ide> def test_truncate_with_block_should_escape_the_block
<ide> def test_truncate_with_block_should_escape_the_block
<ide> end
<ide>
<ide> def test_highlight_should_be_html_safe
<del> assert highlight("This is a beautiful morning", "beautiful").html_safe?
<add> assert_predicate highlight("This is a beautiful morning", "beautiful"), :html_safe?
<ide> end
<ide>
<ide> def test_highlight
<ide> def test_excerpt_with_regex
<ide> end
<ide>
<ide> def test_excerpt_should_not_be_html_safe
<del> assert !excerpt("This is a beautiful! morning", "beautiful", radius: 5).html_safe?
<add> assert_not_predicate excerpt("This is a beautiful! morning", "beautiful", radius: 5), :html_safe?
<ide> end
<ide>
<ide> def test_excerpt_in_borderline_cases
<ide><path>actionview/test/template/translation_helper_test.rb
<ide> def test_returns_missing_translation_message_wrapped_into_span
<ide> def test_returns_missing_translation_message_with_unescaped_interpolation
<ide> expected = '<span class="translation_missing" title="translation missing: en.translations.missing, name: Kir, year: 2015, vulnerable: &quot; onclick=&quot;alert()&quot;">Missing</span>'
<ide> assert_equal expected, translate(:"translations.missing", name: "Kir", year: "2015", vulnerable: %{" onclick="alert()"})
<del> assert translate(:"translations.missing").html_safe?
<add> assert_predicate translate(:"translations.missing"), :html_safe?
<ide> end
<ide>
<ide> def test_returns_missing_translation_message_does_filters_out_i18n_options
<ide> def test_translate_does_not_mark_plain_text_as_safe_html
<ide> end
<ide>
<ide> def test_translate_marks_translations_named_html_as_safe_html
<del> assert translate(:'translations.html').html_safe?
<add> assert_predicate translate(:'translations.html'), :html_safe?
<ide> end
<ide>
<ide> def test_translate_marks_translations_with_a_html_suffix_as_safe_html
<del> assert translate(:'translations.hello_html').html_safe?
<add> assert_predicate translate(:'translations.hello_html'), :html_safe?
<ide> end
<ide>
<ide> def test_translate_escapes_interpolations_in_translations_with_a_html_suffix
<ide><path>actionview/test/template/url_helper_test.rb
<ide> def test_mail_to_with_nil
<ide> end
<ide>
<ide> def test_mail_to_returns_html_safe_string
<del> assert mail_to("david@loudthinking.com").html_safe?
<add> assert_predicate mail_to("david@loudthinking.com"), :html_safe?
<ide> end
<ide>
<ide> def test_mail_to_with_block
<ide><path>activemodel/test/cases/attribute_set_test.rb
<ide> class AttributeSetTest < ActiveModel::TestCase
<ide>
<ide> clone.freeze
<ide>
<del> assert clone.frozen?
<del> assert_not attributes.frozen?
<add> assert_predicate clone, :frozen?
<add> assert_not_predicate attributes, :frozen?
<ide> end
<ide>
<ide> test "to_hash returns a hash of the type cast values" do
<ide> class AttributeSetTest < ActiveModel::TestCase
<ide>
<ide> test "known columns are built with uninitialized attributes" do
<ide> attributes = attributes_with_uninitialized_key
<del> assert attributes[:foo].initialized?
<del> assert_not attributes[:bar].initialized?
<add> assert_predicate attributes[:foo], :initialized?
<add> assert_not_predicate attributes[:bar], :initialized?
<ide> end
<ide>
<ide> test "uninitialized attributes are not included in the attributes hash" do
<ide> class AttributeSetTest < ActiveModel::TestCase
<ide>
<ide> assert attributes.key?(:foo)
<ide> assert_equal [:foo], attributes.keys
<del> assert attributes[:foo].initialized?
<add> assert_predicate attributes[:foo], :initialized?
<ide> end
<ide>
<ide> class MyType
<ide><path>activemodel/test/cases/attribute_test.rb
<ide> def assert_valid_value(*)
<ide>
<ide> test "an attribute has not been read by default" do
<ide> attribute = Attribute.from_database(:foo, 1, Type::Value.new)
<del> assert_not attribute.has_been_read?
<add> assert_not_predicate attribute, :has_been_read?
<ide> end
<ide>
<ide> test "an attribute has been read when its value is calculated" do
<ide> attribute = Attribute.from_database(:foo, 1, Type::Value.new)
<ide> attribute.value
<del> assert attribute.has_been_read?
<add> assert_predicate attribute, :has_been_read?
<ide> end
<ide>
<ide> test "an attribute is not changed if it hasn't been assigned or mutated" do
<ide> attribute = Attribute.from_database(:foo, 1, Type::Value.new)
<ide>
<del> assert_not attribute.changed?
<add> assert_not_predicate attribute, :changed?
<ide> end
<ide>
<ide> test "an attribute is changed if it's been assigned a new value" do
<ide> attribute = Attribute.from_database(:foo, 1, Type::Value.new)
<ide> changed = attribute.with_value_from_user(2)
<ide>
<del> assert changed.changed?
<add> assert_predicate changed, :changed?
<ide> end
<ide>
<ide> test "an attribute is not changed if it's assigned the same value" do
<ide> attribute = Attribute.from_database(:foo, 1, Type::Value.new)
<ide> unchanged = attribute.with_value_from_user(1)
<ide>
<del> assert_not unchanged.changed?
<add> assert_not_predicate unchanged, :changed?
<ide> end
<ide>
<ide> test "an attribute can not be mutated if it has not been read,
<ide> and skips expensive calculations" do
<ide> type_which_raises_from_all_methods = Object.new
<ide> attribute = Attribute.from_database(:foo, "bar", type_which_raises_from_all_methods)
<ide>
<del> assert_not attribute.changed_in_place?
<add> assert_not_predicate attribute, :changed_in_place?
<ide> end
<ide>
<ide> test "an attribute is changed if it has been mutated" do
<ide> attribute = Attribute.from_database(:foo, "bar", Type::String.new)
<ide> attribute.value << "!"
<ide>
<del> assert attribute.changed_in_place?
<del> assert attribute.changed?
<add> assert_predicate attribute, :changed_in_place?
<add> assert_predicate attribute, :changed?
<ide> end
<ide>
<ide> test "an attribute can forget its changes" do
<ide> def assert_valid_value(*)
<ide> forgotten = changed.forgetting_assignment
<ide>
<ide> assert changed.changed? # sanity check
<del> assert_not forgotten.changed?
<add> assert_not_predicate forgotten, :changed?
<ide> end
<ide>
<ide> test "with_value_from_user validates the value" do
<ide><path>activemodel/test/cases/attributes_dirty_test.rb
<ide> def reload
<ide> end
<ide>
<ide> test "setting attribute will result in change" do
<del> assert !@model.changed?
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :changed?
<add> assert_not_predicate @model, :name_changed?
<ide> @model.name = "Ringo"
<del> assert @model.changed?
<del> assert @model.name_changed?
<add> assert_predicate @model, :changed?
<add> assert_predicate @model, :name_changed?
<ide> end
<ide>
<ide> test "list of changed attribute keys" do
<ide> def reload
<ide> test "attribute mutation" do
<ide> @model.name = "Yam"
<ide> @model.save
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :name_changed?
<ide> @model.name.replace("Hadad")
<del> assert @model.name_changed?
<add> assert_predicate @model, :name_changed?
<ide> end
<ide>
<ide> test "resetting attribute" do
<ide> @model.name = "Bob"
<ide> @model.restore_name!
<ide> assert_nil @model.name
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :name_changed?
<ide> end
<ide>
<ide> test "setting color to same value should not result in change being recorded" do
<ide> @model.color = "red"
<del> assert @model.color_changed?
<add> assert_predicate @model, :color_changed?
<ide> @model.save
<del> assert !@model.color_changed?
<del> assert !@model.changed?
<add> assert_not_predicate @model, :color_changed?
<add> assert_not_predicate @model, :changed?
<ide> @model.color = "red"
<del> assert !@model.color_changed?
<del> assert !@model.changed?
<add> assert_not_predicate @model, :color_changed?
<add> assert_not_predicate @model, :changed?
<ide> end
<ide>
<ide> test "saving should reset model's changed status" do
<ide> @model.name = "Alf"
<del> assert @model.changed?
<add> assert_predicate @model, :changed?
<ide> @model.save
<del> assert !@model.changed?
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :changed?
<add> assert_not_predicate @model, :name_changed?
<ide> end
<ide>
<ide> test "saving should preserve previous changes" do
<ide> def reload
<ide> test "saving should preserve model's previous changed status" do
<ide> @model.name = "Jericho Cane"
<ide> @model.save
<del> assert @model.name_previously_changed?
<add> assert_predicate @model, :name_previously_changed?
<ide> end
<ide>
<ide> test "previous value is preserved when changed after save" do
<ide> def reload
<ide>
<ide> test "using attribute_will_change! with a symbol" do
<ide> @model.size = 1
<del> assert @model.size_changed?
<add> assert_predicate @model, :size_changed?
<ide> end
<ide>
<ide> test "reload should reset all changes" do
<ide> def reload
<ide>
<ide> @model.restore_attributes
<ide>
<del> assert_not @model.changed?
<add> assert_not_predicate @model, :changed?
<ide> assert_equal "Dmitry", @model.name
<ide> assert_equal "Red", @model.color
<ide> end
<ide> def reload
<ide>
<ide> @model.restore_attributes(["name"])
<ide>
<del> assert @model.changed?
<add> assert_predicate @model, :changed?
<ide> assert_equal "Dmitry", @model.name
<ide> assert_equal "White", @model.color
<ide> end
<ide><path>activemodel/test/cases/dirty_test.rb
<ide> def reload
<ide> end
<ide>
<ide> test "setting attribute will result in change" do
<del> assert !@model.changed?
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :changed?
<add> assert_not_predicate @model, :name_changed?
<ide> @model.name = "Ringo"
<del> assert @model.changed?
<del> assert @model.name_changed?
<add> assert_predicate @model, :changed?
<add> assert_predicate @model, :name_changed?
<ide> end
<ide>
<ide> test "list of changed attribute keys" do
<ide> def reload
<ide>
<ide> test "attribute mutation" do
<ide> @model.instance_variable_set("@name", "Yam".dup)
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :name_changed?
<ide> @model.name.replace("Hadad")
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :name_changed?
<ide> @model.name_will_change!
<ide> @model.name.replace("Baal")
<del> assert @model.name_changed?
<add> assert_predicate @model, :name_changed?
<ide> end
<ide>
<ide> test "resetting attribute" do
<ide> @model.name = "Bob"
<ide> @model.restore_name!
<ide> assert_nil @model.name
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :name_changed?
<ide> end
<ide>
<ide> test "setting color to same value should not result in change being recorded" do
<ide> @model.color = "red"
<del> assert @model.color_changed?
<add> assert_predicate @model, :color_changed?
<ide> @model.save
<del> assert !@model.color_changed?
<del> assert !@model.changed?
<add> assert_not_predicate @model, :color_changed?
<add> assert_not_predicate @model, :changed?
<ide> @model.color = "red"
<del> assert !@model.color_changed?
<del> assert !@model.changed?
<add> assert_not_predicate @model, :color_changed?
<add> assert_not_predicate @model, :changed?
<ide> end
<ide>
<ide> test "saving should reset model's changed status" do
<ide> @model.name = "Alf"
<del> assert @model.changed?
<add> assert_predicate @model, :changed?
<ide> @model.save
<del> assert !@model.changed?
<del> assert !@model.name_changed?
<add> assert_not_predicate @model, :changed?
<add> assert_not_predicate @model, :name_changed?
<ide> end
<ide>
<ide> test "saving should preserve previous changes" do
<ide> def reload
<ide> test "saving should preserve model's previous changed status" do
<ide> @model.name = "Jericho Cane"
<ide> @model.save
<del> assert @model.name_previously_changed?
<add> assert_predicate @model, :name_previously_changed?
<ide> end
<ide>
<ide> test "previous value is preserved when changed after save" do
<ide> def reload
<ide>
<ide> test "using attribute_will_change! with a symbol" do
<ide> @model.size = 1
<del> assert @model.size_changed?
<add> assert_predicate @model, :size_changed?
<ide> end
<ide>
<ide> test "reload should reset all changes" do
<ide> def reload
<ide>
<ide> @model.restore_attributes
<ide>
<del> assert_not @model.changed?
<add> assert_not_predicate @model, :changed?
<ide> assert_equal "Dmitry", @model.name
<ide> assert_equal "Red", @model.color
<ide> end
<ide> def reload
<ide>
<ide> @model.restore_attributes(["name"])
<ide>
<del> assert @model.changed?
<add> assert_predicate @model, :changed?
<ide> assert_equal "Dmitry", @model.name
<ide> assert_equal "White", @model.color
<ide> end
<ide><path>activemodel/test/cases/errors_test.rb
<ide> def test_no_key
<ide>
<ide> assert_equal 1, person.errors.count
<ide> person.errors.clear
<del> assert person.errors.empty?
<add> assert_predicate person.errors, :empty?
<ide> end
<ide>
<ide> test "error access is indifferent" do
<ide> def test_no_key
<ide> test "detecting whether there are errors with empty?, blank?, include?" do
<ide> person = Person.new
<ide> person.errors[:foo]
<del> assert person.errors.empty?
<del> assert person.errors.blank?
<add> assert_predicate person.errors, :empty?
<add> assert_predicate person.errors, :blank?
<ide> assert_not_includes person.errors, :foo
<ide> end
<ide>
<ide> def test_no_key
<ide>
<ide> assert_equal 1, person.errors.details.count
<ide> person.errors.clear
<del> assert person.errors.details.empty?
<add> assert_predicate person.errors.details, :empty?
<ide> end
<ide>
<ide> test "copy errors" do
<ide><path>activemodel/test/cases/type/boolean_test.rb
<ide> module Type
<ide> class BooleanTest < ActiveModel::TestCase
<ide> def test_type_cast_boolean
<ide> type = Type::Boolean.new
<del> assert type.cast("").nil?
<del> assert type.cast(nil).nil?
<add> assert_predicate type.cast(""), :nil?
<add> assert_predicate type.cast(nil), :nil?
<ide>
<ide> assert type.cast(true)
<ide> assert type.cast(1)
<ide><path>activemodel/test/cases/validations/absence_validation_test.rb
<ide> def test_validates_absence_of
<ide> t = Topic.new
<ide> t.title = "foo"
<ide> t.content = "bar"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["must be blank"], t.errors[:title]
<ide> assert_equal ["must be blank"], t.errors[:content]
<ide> t.title = ""
<ide> t.content = "something"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["must be blank"], t.errors[:content]
<ide> assert_equal [], t.errors[:title]
<ide> t.content = ""
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_absence_of_with_array_arguments
<ide> Topic.validates_absence_of %w(title content)
<ide> t = Topic.new
<ide> t.title = "foo"
<ide> t.content = "bar"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["must be blank"], t.errors[:title]
<ide> assert_equal ["must be blank"], t.errors[:content]
<ide> end
<ide> def test_validates_absence_of_with_custom_error_using_quotes
<ide> Person.validates_absence_of :karma, message: "This string contains 'single' and \"double\" quotes"
<ide> p = Person.new
<ide> p.karma = "good"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide> assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last
<ide> end
<ide>
<ide> def test_validates_absence_of_for_ruby_class
<ide> Person.validates_absence_of :karma
<ide> p = Person.new
<ide> p.karma = "good"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide> assert_equal ["must be blank"], p.errors[:karma]
<ide> p.karma = nil
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> end
<ide>
<ide> def test_validates_absence_of_for_ruby_class_with_custom_reader
<ide> CustomReader.validates_absence_of :karma
<ide> p = CustomReader.new
<ide> p[:karma] = "excellent"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide> assert_equal ["must be blank"], p.errors[:karma]
<ide> p[:karma] = ""
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> end
<ide> end
<ide><path>activemodel/test/cases/validations/acceptance_validation_test.rb
<ide> def test_terms_of_service_agreement_no_acceptance
<ide> Topic.validates_acceptance_of(:terms_of_service)
<ide>
<ide> t = Topic.new("title" => "We should not be confirmed")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_terms_of_service_agreement
<ide> Topic.validates_acceptance_of(:terms_of_service)
<ide>
<ide> t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["must be accepted"], t.errors[:terms_of_service]
<ide>
<ide> t.terms_of_service = "1"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_eula
<ide> Topic.validates_acceptance_of(:eula, message: "must be abided")
<ide>
<ide> t = Topic.new("title" => "We should be confirmed", "eula" => "")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["must be abided"], t.errors[:eula]
<ide>
<ide> t.eula = "1"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_terms_of_service_agreement_with_accept_value
<ide> Topic.validates_acceptance_of(:terms_of_service, accept: "I agree.")
<ide>
<ide> t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["must be accepted"], t.errors[:terms_of_service]
<ide>
<ide> t.terms_of_service = "I agree."
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_terms_of_service_agreement_with_multiple_accept_values
<ide> Topic.validates_acceptance_of(:terms_of_service, accept: [1, "I concur."])
<ide>
<ide> t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["must be accepted"], t.errors[:terms_of_service]
<ide>
<ide> t.terms_of_service = 1
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.terms_of_service = "I concur."
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_acceptance_of_for_ruby_class
<ide> def test_validates_acceptance_of_for_ruby_class
<ide> p = Person.new
<ide> p.karma = ""
<ide>
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide> assert_equal ["must be accepted"], p.errors[:karma]
<ide>
<ide> p.karma = "1"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide>
<ide> def test_validates_acceptance_of_true
<ide> Topic.validates_acceptance_of(:terms_of_service)
<ide>
<del> assert Topic.new(terms_of_service: true).valid?
<add> assert_predicate Topic.new(terms_of_service: true), :valid?
<ide> end
<ide> end
<ide><path>activemodel/test/cases/validations/conditional_validation_test.rb
<ide> def test_if_validation_using_method_true
<ide> # When the method returns true
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_true)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_if_validation_using_array_of_true_methods
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: [:condition_is_true, :condition_is_true])
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_unless_validation_using_array_of_false_methods
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: [:condition_is_false, :condition_is_false])
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_unless_validation_using_method_true
<ide> # When the method returns true
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: :condition_is_true)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> assert_empty t.errors[:title]
<ide> end
<ide>
<ide> def test_if_validation_using_array_of_true_and_false_methods
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: [:condition_is_true, :condition_is_false])
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> assert_empty t.errors[:title]
<ide> end
<ide>
<ide> def test_unless_validation_using_array_of_true_and_felse_methods
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: [:condition_is_true, :condition_is_false])
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> assert_empty t.errors[:title]
<ide> end
<ide>
<ide> def test_if_validation_using_method_false
<ide> # When the method returns false
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_false)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> assert_empty t.errors[:title]
<ide> end
<ide>
<ide> def test_unless_validation_using_method_false
<ide> # When the method returns false
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: :condition_is_false)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_if_validation_using_block_true
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
<ide> if: Proc.new { |r| r.content.size > 4 })
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_unless_validation_using_block_true
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
<ide> unless: Proc.new { |r| r.content.size > 4 })
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> assert_empty t.errors[:title]
<ide> end
<ide>
<ide> def test_if_validation_using_block_false
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
<ide> if: Proc.new { |r| r.title != "uhohuhoh" })
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> assert_empty t.errors[:title]
<ide> end
<ide>
<ide> def test_unless_validation_using_block_false
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
<ide> unless: Proc.new { |r| r.title != "uhohuhoh" })
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validation_using_conbining_if_true_and_unless_true_conditions
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_true, unless: :condition_is_true)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> assert_empty t.errors[:title]
<ide> end
<ide>
<ide> def test_validation_using_conbining_if_true_and_unless_false_conditions
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_true, unless: :condition_is_false)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide> end
<ide><path>activemodel/test/cases/validations/confirmation_validation_test.rb
<ide> def test_no_title_confirmation
<ide> Topic.validates_confirmation_of(:title)
<ide>
<ide> t = Topic.new(author_name: "Plutarch")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title_confirmation = "Parallel Lives"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.title_confirmation = nil
<ide> t.title = "Parallel Lives"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title_confirmation = "Parallel Lives"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_title_confirmation
<ide> Topic.validates_confirmation_of(:title)
<ide>
<ide> t = Topic.new("title" => "We should be confirmed", "title_confirmation" => "")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.title_confirmation = "We should be confirmed"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_confirmation_of_with_boolean_attribute
<ide> Topic.validates_confirmation_of(:approved)
<ide>
<ide> t = Topic.new(approved: true, approved_confirmation: nil)
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.approved_confirmation = false
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.approved_confirmation = true
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_confirmation_of_for_ruby_class
<ide> Person.validates_confirmation_of :karma
<ide>
<ide> p = Person.new
<ide> p.karma_confirmation = "None"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide>
<ide> assert_equal ["doesn't match Karma"], p.errors[:karma_confirmation]
<ide>
<ide> p.karma = "None"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide> def test_title_confirmation_with_i18n_attribute
<ide> Topic.validates_confirmation_of(:title)
<ide>
<ide> t = Topic.new("title" => "We should be confirmed", "title_confirmation" => "")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["doesn't match Test Title"], t.errors[:title_confirmation]
<ide> ensure
<ide> I18n.load_path.replace @old_load_path
<ide> def test_title_confirmation_with_case_sensitive_option_true
<ide> Topic.validates_confirmation_of(:title, case_sensitive: true)
<ide>
<ide> t = Topic.new(title: "title", title_confirmation: "Title")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> end
<ide>
<ide> def test_title_confirmation_with_case_sensitive_option_false
<ide> Topic.validates_confirmation_of(:title, case_sensitive: false)
<ide>
<ide> t = Topic.new(title: "title", title_confirmation: "Title")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide> end
<ide><path>activemodel/test/cases/validations/exclusion_validation_test.rb
<ide> def teardown
<ide> def test_validates_exclusion_of
<ide> Topic.validates_exclusion_of(:title, in: %w( abe monkey ))
<ide>
<del> assert Topic.new("title" => "something", "content" => "abc").valid?
<del> assert Topic.new("title" => "monkey", "content" => "abc").invalid?
<add> assert_predicate Topic.new("title" => "something", "content" => "abc"), :valid?
<add> assert_predicate Topic.new("title" => "monkey", "content" => "abc"), :invalid?
<ide> end
<ide>
<ide> def test_validates_exclusion_of_with_formatted_message
<ide> def test_validates_exclusion_of_with_formatted_message
<ide> assert Topic.new("title" => "something", "content" => "abc")
<ide>
<ide> t = Topic.new("title" => "monkey")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["option monkey is restricted"], t.errors[:title]
<ide> end
<ide>
<ide> def test_validates_exclusion_of_with_within_option
<ide> assert Topic.new("title" => "something", "content" => "abc")
<ide>
<ide> t = Topic.new("title" => "monkey")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> end
<ide>
<ide> def test_validates_exclusion_of_for_ruby_class
<ide> Person.validates_exclusion_of :karma, in: %w( abe monkey )
<ide>
<ide> p = Person.new
<ide> p.karma = "abe"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide>
<ide> assert_equal ["is reserved"], p.errors[:karma]
<ide>
<ide> p.karma = "Lifo"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide> def test_validates_exclusion_of_with_lambda
<ide> t = Topic.new
<ide> t.title = "elephant"
<ide> t.author_name = "sikachu"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.title = "wasabi"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_exclusion_of_with_range
<ide> Topic.validates_exclusion_of :content, in: ("a".."g")
<ide>
<del> assert Topic.new(content: "g").invalid?
<del> assert Topic.new(content: "h").valid?
<add> assert_predicate Topic.new(content: "g"), :invalid?
<add> assert_predicate Topic.new(content: "h"), :valid?
<ide> end
<ide>
<ide> def test_validates_exclusion_of_with_time_range
<ide> Topic.validates_exclusion_of :created_at, in: 6.days.ago..2.days.ago
<ide>
<del> assert Topic.new(created_at: 5.days.ago).invalid?
<del> assert Topic.new(created_at: 3.days.ago).invalid?
<del> assert Topic.new(created_at: 7.days.ago).valid?
<del> assert Topic.new(created_at: 1.day.ago).valid?
<add> assert_predicate Topic.new(created_at: 5.days.ago), :invalid?
<add> assert_predicate Topic.new(created_at: 3.days.ago), :invalid?
<add> assert_predicate Topic.new(created_at: 7.days.ago), :valid?
<add> assert_predicate Topic.new(created_at: 1.day.ago), :valid?
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_symbol
<ide> def p.reserved_karmas
<ide> %w(abe)
<ide> end
<ide>
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide> assert_equal ["is reserved"], p.errors[:karma]
<ide>
<ide> p = Person.new
<ide> def p.reserved_karmas
<ide> %w()
<ide> end
<ide>
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide><path>activemodel/test/cases/validations/format_validation_test.rb
<ide> def test_validate_format
<ide> t = Topic.new("title" => "i'm incorrect", "content" => "Validation macros rule!")
<ide> assert t.invalid?, "Shouldn't be valid"
<ide> assert_equal ["is bad data"], t.errors[:title]
<del> assert t.errors[:content].empty?
<add> assert_predicate t.errors[:content], :empty?
<ide>
<ide> t.title = "Validation macros rule!"
<ide>
<del> assert t.valid?
<del> assert t.errors[:title].empty?
<add> assert_predicate t, :valid?
<add> assert_predicate t.errors[:title], :empty?
<ide>
<ide> assert_raise(ArgumentError) { Topic.validates_format_of(:title, :content) }
<ide> end
<ide>
<ide> def test_validate_format_with_allow_blank
<ide> Topic.validates_format_of(:title, with: /\AValidation\smacros \w+!\z/, allow_blank: true)
<del> assert Topic.new("title" => "Shouldn't be valid").invalid?
<del> assert Topic.new("title" => "").valid?
<del> assert Topic.new("title" => nil).valid?
<del> assert Topic.new("title" => "Validation macros rule!").valid?
<add> assert_predicate Topic.new("title" => "Shouldn't be valid"), :invalid?
<add> assert_predicate Topic.new("title" => ""), :valid?
<add> assert_predicate Topic.new("title" => nil), :valid?
<add> assert_predicate Topic.new("title" => "Validation macros rule!"), :valid?
<ide> end
<ide>
<ide> # testing ticket #3142
<ide> def test_validate_format_numeric
<ide> assert t.invalid?, "Shouldn't be valid"
<ide>
<ide> assert_equal ["is bad data"], t.errors[:title]
<del> assert t.errors[:content].empty?
<add> assert_predicate t.errors[:content], :empty?
<ide>
<ide> t.title = "-11"
<ide> assert t.invalid?, "Shouldn't be valid"
<ide> def test_validate_format_numeric
<ide>
<ide> t.title = "1"
<ide>
<del> assert t.valid?
<del> assert t.errors[:title].empty?
<add> assert_predicate t, :valid?
<add> assert_predicate t.errors[:title], :empty?
<ide> end
<ide>
<ide> def test_validate_format_with_formatted_message
<ide> Topic.validates_format_of(:title, with: /\AValid Title\z/, message: "can't be %{value}")
<ide> t = Topic.new(title: "Invalid title")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["can't be Invalid title"], t.errors[:title]
<ide> end
<ide>
<ide> def test_validates_format_of_with_lambda
<ide> t = Topic.new
<ide> t.title = "digit"
<ide> t.content = "Pixies"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.content = "1234"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_format_of_without_lambda
<ide> def test_validates_format_of_without_lambda
<ide> t = Topic.new
<ide> t.title = "characters"
<ide> t.content = "1234"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.content = "Pixies"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_format_of_for_ruby_class
<ide> Person.validates_format_of :karma, with: /\A\d+\z/
<ide>
<ide> p = Person.new
<ide> p.karma = "Pixies"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide>
<ide> assert_equal ["is invalid"], p.errors[:karma]
<ide>
<ide> p.karma = "1234"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide><path>activemodel/test/cases/validations/inclusion_validation_test.rb
<ide> def teardown
<ide>
<ide> def test_validates_inclusion_of_range
<ide> Topic.validates_inclusion_of(:title, in: "aaa".."bbb")
<del> assert Topic.new("title" => "bbc", "content" => "abc").invalid?
<del> assert Topic.new("title" => "aa", "content" => "abc").invalid?
<del> assert Topic.new("title" => "aaab", "content" => "abc").invalid?
<del> assert Topic.new("title" => "aaa", "content" => "abc").valid?
<del> assert Topic.new("title" => "abc", "content" => "abc").valid?
<del> assert Topic.new("title" => "bbb", "content" => "abc").valid?
<add> assert_predicate Topic.new("title" => "bbc", "content" => "abc"), :invalid?
<add> assert_predicate Topic.new("title" => "aa", "content" => "abc"), :invalid?
<add> assert_predicate Topic.new("title" => "aaab", "content" => "abc"), :invalid?
<add> assert_predicate Topic.new("title" => "aaa", "content" => "abc"), :valid?
<add> assert_predicate Topic.new("title" => "abc", "content" => "abc"), :valid?
<add> assert_predicate Topic.new("title" => "bbb", "content" => "abc"), :valid?
<ide> end
<ide>
<ide> def test_validates_inclusion_of_time_range
<ide> range_begin = 1.year.ago
<ide> range_end = Time.now
<ide> Topic.validates_inclusion_of(:created_at, in: range_begin..range_end)
<del> assert Topic.new(title: "aaa", created_at: 2.years.ago).invalid?
<del> assert Topic.new(title: "aaa", created_at: 3.months.ago).valid?
<del> assert Topic.new(title: "aaa", created_at: 37.weeks.from_now).invalid?
<del> assert Topic.new(title: "aaa", created_at: range_begin).valid?
<del> assert Topic.new(title: "aaa", created_at: range_end).valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 2.years.ago), :invalid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 3.months.ago), :valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 37.weeks.from_now), :invalid?
<add> assert_predicate Topic.new(title: "aaa", created_at: range_begin), :valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: range_end), :valid?
<ide> end
<ide>
<ide> def test_validates_inclusion_of_date_range
<ide> range_begin = 1.year.until(Date.today)
<ide> range_end = Date.today
<ide> Topic.validates_inclusion_of(:created_at, in: range_begin..range_end)
<del> assert Topic.new(title: "aaa", created_at: 2.years.until(Date.today)).invalid?
<del> assert Topic.new(title: "aaa", created_at: 3.months.until(Date.today)).valid?
<del> assert Topic.new(title: "aaa", created_at: 37.weeks.since(Date.today)).invalid?
<del> assert Topic.new(title: "aaa", created_at: 1.year.until(Date.today)).valid?
<del> assert Topic.new(title: "aaa", created_at: Date.today).valid?
<del> assert Topic.new(title: "aaa", created_at: range_begin).valid?
<del> assert Topic.new(title: "aaa", created_at: range_end).valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 2.years.until(Date.today)), :invalid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 3.months.until(Date.today)), :valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 37.weeks.since(Date.today)), :invalid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 1.year.until(Date.today)), :valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: Date.today), :valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: range_begin), :valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: range_end), :valid?
<ide> end
<ide>
<ide> def test_validates_inclusion_of_date_time_range
<ide> range_begin = 1.year.until(DateTime.current)
<ide> range_end = DateTime.current
<ide> Topic.validates_inclusion_of(:created_at, in: range_begin..range_end)
<del> assert Topic.new(title: "aaa", created_at: 2.years.until(DateTime.current)).invalid?
<del> assert Topic.new(title: "aaa", created_at: 3.months.until(DateTime.current)).valid?
<del> assert Topic.new(title: "aaa", created_at: 37.weeks.since(DateTime.current)).invalid?
<del> assert Topic.new(title: "aaa", created_at: range_begin).valid?
<del> assert Topic.new(title: "aaa", created_at: range_end).valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 2.years.until(DateTime.current)), :invalid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 3.months.until(DateTime.current)), :valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: 37.weeks.since(DateTime.current)), :invalid?
<add> assert_predicate Topic.new(title: "aaa", created_at: range_begin), :valid?
<add> assert_predicate Topic.new(title: "aaa", created_at: range_end), :valid?
<ide> end
<ide>
<ide> def test_validates_inclusion_of
<ide> Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ))
<ide>
<del> assert Topic.new("title" => "a!", "content" => "abc").invalid?
<del> assert Topic.new("title" => "a b", "content" => "abc").invalid?
<del> assert Topic.new("title" => nil, "content" => "def").invalid?
<add> assert_predicate Topic.new("title" => "a!", "content" => "abc"), :invalid?
<add> assert_predicate Topic.new("title" => "a b", "content" => "abc"), :invalid?
<add> assert_predicate Topic.new("title" => nil, "content" => "def"), :invalid?
<ide>
<ide> t = Topic.new("title" => "a", "content" => "I know you are but what am I?")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> t.title = "uhoh"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is not included in the list"], t.errors[:title]
<ide>
<ide> assert_raise(ArgumentError) { Topic.validates_inclusion_of(:title, in: nil) }
<ide> def test_validates_inclusion_of
<ide> def test_validates_inclusion_of_with_allow_nil
<ide> Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ), allow_nil: true)
<ide>
<del> assert Topic.new("title" => "a!", "content" => "abc").invalid?
<del> assert Topic.new("title" => "", "content" => "abc").invalid?
<del> assert Topic.new("title" => nil, "content" => "abc").valid?
<add> assert_predicate Topic.new("title" => "a!", "content" => "abc"), :invalid?
<add> assert_predicate Topic.new("title" => "", "content" => "abc"), :invalid?
<add> assert_predicate Topic.new("title" => nil, "content" => "abc"), :valid?
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_formatted_message
<ide> Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ), message: "option %{value} is not in the list")
<ide>
<del> assert Topic.new("title" => "a", "content" => "abc").valid?
<add> assert_predicate Topic.new("title" => "a", "content" => "abc"), :valid?
<ide>
<ide> t = Topic.new("title" => "uhoh", "content" => "abc")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["option uhoh is not in the list"], t.errors[:title]
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_within_option
<ide> Topic.validates_inclusion_of(:title, within: %w( a b c d e f g ))
<ide>
<del> assert Topic.new("title" => "a", "content" => "abc").valid?
<add> assert_predicate Topic.new("title" => "a", "content" => "abc"), :valid?
<ide>
<ide> t = Topic.new("title" => "uhoh", "content" => "abc")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> end
<ide>
<ide> def test_validates_inclusion_of_for_ruby_class
<ide> Person.validates_inclusion_of :karma, in: %w( abe monkey )
<ide>
<ide> p = Person.new
<ide> p.karma = "Lifo"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide>
<ide> assert_equal ["is not included in the list"], p.errors[:karma]
<ide>
<ide> p.karma = "monkey"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide> def test_validates_inclusion_of_with_lambda
<ide> t = Topic.new
<ide> t.title = "wasabi"
<ide> t.author_name = "sikachu"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.title = "elephant"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_symbol
<ide> def p.available_karmas
<ide> %w()
<ide> end
<ide>
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide> assert_equal ["is not included in the list"], p.errors[:karma]
<ide>
<ide> p = Person.new
<ide> def p.available_karmas
<ide> %w(Lifo)
<ide> end
<ide>
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide><path>activemodel/test/cases/validations/length_validation_test.rb
<ide> def teardown
<ide> def test_validates_length_of_with_allow_nil
<ide> Topic.validates_length_of(:title, is: 5, allow_nil: true)
<ide>
<del> assert Topic.new("title" => "ab").invalid?
<del> assert Topic.new("title" => "").invalid?
<del> assert Topic.new("title" => nil).valid?
<del> assert Topic.new("title" => "abcde").valid?
<add> assert_predicate Topic.new("title" => "ab"), :invalid?
<add> assert_predicate Topic.new("title" => ""), :invalid?
<add> assert_predicate Topic.new("title" => nil), :valid?
<add> assert_predicate Topic.new("title" => "abcde"), :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_with_allow_blank
<ide> Topic.validates_length_of(:title, is: 5, allow_blank: true)
<ide>
<del> assert Topic.new("title" => "ab").invalid?
<del> assert Topic.new("title" => "").valid?
<del> assert Topic.new("title" => nil).valid?
<del> assert Topic.new("title" => "abcde").valid?
<add> assert_predicate Topic.new("title" => "ab"), :invalid?
<add> assert_predicate Topic.new("title" => ""), :valid?
<add> assert_predicate Topic.new("title" => nil), :valid?
<add> assert_predicate Topic.new("title" => "abcde"), :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_minimum
<ide> Topic.validates_length_of :title, minimum: 5
<ide>
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "not"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is too short (minimum is 5 characters)"], t.errors[:title]
<ide>
<ide> t.title = ""
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is too short (minimum is 5 characters)"], t.errors[:title]
<ide>
<ide> t.title = nil
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_using_maximum_should_allow_nil
<ide> Topic.validates_length_of :title, maximum: 10
<ide> t = Topic.new
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_optionally_validates_length_of_using_minimum
<ide> Topic.validates_length_of :title, minimum: 5, allow_nil: true
<ide>
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = nil
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_maximum
<ide> Topic.validates_length_of :title, maximum: 5
<ide>
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "notvalid"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is too long (maximum is 5 characters)"], t.errors[:title]
<ide>
<ide> t.title = ""
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_optionally_validates_length_of_using_maximum
<ide> Topic.validates_length_of :title, maximum: 5, allow_nil: true
<ide>
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = nil
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_within
<ide> Topic.validates_length_of(:title, :content, within: 3..5)
<ide>
<ide> t = Topic.new("title" => "a!", "content" => "I'm ooooooooh so very long")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
<ide> assert_equal ["is too long (maximum is 5 characters)"], t.errors[:content]
<ide>
<ide> t.title = nil
<ide> t.content = nil
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
<ide> assert_equal ["is too short (minimum is 3 characters)"], t.errors[:content]
<ide>
<ide> t.title = "abe"
<ide> t.content = "mad"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_within_with_exclusive_range
<ide> Topic.validates_length_of(:title, within: 4...10)
<ide>
<ide> t = Topic.new("title" => "9 chars!!")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "Now I'm 10"
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["is too long (maximum is 9 characters)"], t.errors[:title]
<ide>
<ide> t.title = "Four"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_optionally_validates_length_of_using_within
<ide> Topic.validates_length_of :title, :content, within: 3..5, allow_nil: true
<ide>
<ide> t = Topic.new("title" => "abc", "content" => "abcd")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = nil
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_is
<ide> Topic.validates_length_of :title, is: 5
<ide>
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "notvalid"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is the wrong length (should be 5 characters)"], t.errors[:title]
<ide>
<ide> t.title = ""
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.title = nil
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> end
<ide>
<ide> def test_optionally_validates_length_of_using_is
<ide> Topic.validates_length_of :title, is: 5, allow_nil: true
<ide>
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = nil
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_bignum
<ide> def test_validates_length_of_nasty_params
<ide> def test_validates_length_of_custom_errors_for_minimum_with_message
<ide> Topic.validates_length_of(:title, minimum: 5, message: "boo %{count}")
<ide> t = Topic.new("title" => "uhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["boo 5"], t.errors[:title]
<ide> end
<ide>
<ide> def test_validates_length_of_custom_errors_for_minimum_with_too_short
<ide> Topic.validates_length_of(:title, minimum: 5, too_short: "hoo %{count}")
<ide> t = Topic.new("title" => "uhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors[:title]
<ide> end
<ide>
<ide> def test_validates_length_of_custom_errors_for_maximum_with_message
<ide> Topic.validates_length_of(:title, maximum: 5, message: "boo %{count}")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["boo 5"], t.errors[:title]
<ide> end
<ide>
<ide> def test_validates_length_of_custom_errors_for_in
<ide> Topic.validates_length_of(:title, in: 10..20, message: "hoo %{count}")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 10"], t.errors["title"]
<ide>
<ide> t = Topic.new("title" => "uhohuhohuhohuhohuhohuhohuhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 20"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_custom_errors_for_maximum_with_too_long
<ide> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_custom_errors_for_both_too_short_and_too_long
<ide> Topic.validates_length_of :title, minimum: 3, maximum: 5, too_short: "too short", too_long: "too long"
<ide>
<ide> t = Topic.new(title: "a")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["too short"], t.errors["title"]
<ide>
<ide> t = Topic.new(title: "aaaaaa")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["too long"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_custom_errors_for_is_with_message
<ide> Topic.validates_length_of(:title, is: 5, message: "boo %{count}")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["boo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_custom_errors_for_is_with_wrong_length
<ide> Topic.validates_length_of(:title, is: 5, wrong_length: "hoo %{count}")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["hoo 5"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_using_minimum_utf8
<ide> Topic.validates_length_of :title, minimum: 5
<ide>
<ide> t = Topic.new("title" => "一二三四五", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "一二三四"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_using_maximum_utf8
<ide> Topic.validates_length_of :title, maximum: 5
<ide>
<ide> t = Topic.new("title" => "一二三四五", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "一二34五六"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is too long (maximum is 5 characters)"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_using_within_utf8
<ide> Topic.validates_length_of(:title, :content, within: 3..5)
<ide>
<ide> t = Topic.new("title" => "一二", "content" => "12三四五六七")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
<ide> assert_equal ["is too long (maximum is 5 characters)"], t.errors[:content]
<ide> t.title = "一二三"
<ide> t.content = "12三"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_optionally_validates_length_of_using_within_utf8
<ide> def test_validates_length_of_using_is_utf8
<ide> Topic.validates_length_of :title, is: 5
<ide>
<ide> t = Topic.new("title" => "一二345", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "一二345六"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is the wrong length (should be 5 characters)"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validates_length_of_for_integer
<ide> Topic.validates_length_of(:approved, is: 4)
<ide>
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever", approved: 1)
<del> assert t.invalid?
<del> assert t.errors[:approved].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:approved], :any?
<ide>
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever", approved: 1234)
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_for_ruby_class
<ide> Person.validates_length_of :karma, minimum: 5
<ide>
<ide> p = Person.new
<ide> p.karma = "Pix"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide>
<ide> assert_equal ["is too short (minimum is 5 characters)"], p.errors[:karma]
<ide>
<ide> p.karma = "The Smiths"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide> def test_validates_length_of_for_infinite_maxima
<ide> Topic.validates_length_of(:title, within: 5..Float::INFINITY)
<ide>
<ide> t = Topic.new("title" => "1234")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide>
<ide> t.title = "12345"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> Topic.validates_length_of(:author_name, maximum: Float::INFINITY)
<ide>
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.author_name = "A very long author name that should still be valid." * 100
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_maximum_should_not_allow_nil_when_nil_not_allowed
<ide> Topic.validates_length_of :title, maximum: 10, allow_nil: false
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_maximum_should_not_allow_nil_and_empty_string_when_blank_not_allowed
<ide> Topic.validates_length_of :title, maximum: 10, allow_blank: false
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.title = ""
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_both_minimum_and_maximum_should_not_allow_nil
<ide> Topic.validates_length_of :title, minimum: 5, maximum: 10
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_minimum_0_should_not_allow_nil
<ide> Topic.validates_length_of :title, minimum: 0
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.title = ""
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_is_0_should_not_allow_nil
<ide> Topic.validates_length_of :title, is: 0
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> t.title = ""
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_with_diff_in_option
<ide> Topic.validates_length_of(:title, is: 5)
<ide> Topic.validates_length_of(:title, is: 5, if: Proc.new { false })
<ide>
<del> assert Topic.new("title" => "david").valid?
<del> assert Topic.new("title" => "david2").invalid?
<add> assert_predicate Topic.new("title" => "david"), :valid?
<add> assert_predicate Topic.new("title" => "david2"), :invalid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_proc_as_maximum
<ide> Topic.validates_length_of :title, maximum: ->(model) { 5 }
<ide>
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "notvalid"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is too long (maximum is 5 characters)"], t.errors[:title]
<ide>
<ide> t.title = ""
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_length_of_using_proc_as_maximum_with_model_method
<ide> Topic.send(:define_method, :max_title_length, lambda { 5 })
<ide> Topic.validates_length_of :title, maximum: Proc.new(&:max_title_length)
<ide>
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide>
<ide> t.title = "notvalid"
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["is too long (maximum is 5 characters)"], t.errors[:title]
<ide>
<ide> t.title = ""
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide> end
<ide><path>activemodel/test/cases/validations/numericality_validation_test.rb
<ide> def test_validates_numericality_with_numeric_message
<ide> Topic.validates_numericality_of :approved, less_than: 4, message: "smaller than %{count}"
<ide> topic = Topic.new("title" => "numeric test", "approved" => 10)
<ide>
<del> assert !topic.valid?
<add> assert_not_predicate topic, :valid?
<ide> assert_equal ["smaller than 4"], topic.errors[:approved]
<ide>
<ide> Topic.validates_numericality_of :approved, greater_than: 4, message: "greater than %{count}"
<ide> topic = Topic.new("title" => "numeric test", "approved" => 1)
<ide>
<del> assert !topic.valid?
<add> assert_not_predicate topic, :valid?
<ide> assert_equal ["greater than 4"], topic.errors[:approved]
<ide> end
<ide>
<ide> def test_validates_numericality_of_for_ruby_class
<ide>
<ide> p = Person.new
<ide> p.karma = "Pix"
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide>
<ide> assert_equal ["is not a number"], p.errors[:karma]
<ide>
<ide> p.karma = "1234"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> ensure
<ide> Person.clear_validators!
<ide> end
<ide> def test_validates_numericality_with_exponent_number
<ide> topic = Topic.new
<ide> topic.approved = (base + 1).to_s
<ide>
<del> assert topic.invalid?
<add> assert_predicate topic, :invalid?
<ide> end
<ide>
<ide> def test_validates_numericality_with_invalid_args
<ide><path>activemodel/test/cases/validations/presence_validation_test.rb
<ide> def test_validate_presences
<ide> Topic.validates_presence_of(:title, :content)
<ide>
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["can't be blank"], t.errors[:title]
<ide> assert_equal ["can't be blank"], t.errors[:content]
<ide>
<ide> t.title = "something"
<ide> t.content = " "
<ide>
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["can't be blank"], t.errors[:content]
<ide>
<ide> t.content = "like stuff"
<ide>
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_accepts_array_arguments
<ide> Topic.validates_presence_of %w(title content)
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["can't be blank"], t.errors[:title]
<ide> assert_equal ["can't be blank"], t.errors[:content]
<ide> end
<ide>
<ide> def test_validates_acceptance_of_with_custom_error_using_quotes
<ide> Person.validates_presence_of :karma, message: "This string contains 'single' and \"double\" quotes"
<ide> p = Person.new
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide> assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last
<ide> end
<ide>
<ide> def test_validates_presence_of_for_ruby_class
<ide> Person.validates_presence_of :karma
<ide>
<ide> p = Person.new
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide>
<ide> assert_equal ["can't be blank"], p.errors[:karma]
<ide>
<ide> p.karma = "Cold"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> end
<ide>
<ide> def test_validates_presence_of_for_ruby_class_with_custom_reader
<ide> CustomReader.validates_presence_of :karma
<ide>
<ide> p = CustomReader.new
<del> assert p.invalid?
<add> assert_predicate p, :invalid?
<ide>
<ide> assert_equal ["can't be blank"], p.errors[:karma]
<ide>
<ide> p[:karma] = "Cold"
<del> assert p.valid?
<add> assert_predicate p, :valid?
<ide> end
<ide>
<ide> def test_validates_presence_of_with_allow_nil_option
<ide> def test_validates_presence_of_with_allow_nil_option
<ide> assert t.valid?, t.errors.full_messages
<ide>
<ide> t.title = ""
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["can't be blank"], t.errors[:title]
<ide>
<ide> t.title = " "
<ide><path>activemodel/test/cases/validations/validates_test.rb
<ide> def test_validates_with_attribute_specified_as_string
<ide>
<ide> person = Person.new
<ide> person.title = 123
<del> assert person.valid?
<add> assert_predicate person, :valid?
<ide> end
<ide>
<ide> def test_validates_with_built_in_validation_and_options
<ide> def test_validates_with_if_as_local_conditions
<ide> def test_validates_with_if_as_shared_conditions
<ide> Person.validates :karma, presence: true, email: true, if: :condition_is_false
<ide> person = Person.new
<del> assert person.valid?
<add> assert_predicate person, :valid?
<ide> end
<ide>
<ide> def test_validates_with_unless_as_local_conditions
<ide> def test_validates_with_unless_as_local_conditions
<ide> def test_validates_with_unless_shared_conditions
<ide> Person.validates :karma, presence: true, email: true, unless: :condition_is_true
<ide> person = Person.new
<del> assert person.valid?
<add> assert_predicate person, :valid?
<ide> end
<ide>
<ide> def test_validates_with_allow_nil_shared_conditions
<ide> Person.validates :karma, length: { minimum: 20 }, email: true, allow_nil: true
<ide> person = Person.new
<del> assert person.valid?
<add> assert_predicate person, :valid?
<ide> end
<ide>
<ide> def test_validates_with_regexp
<ide> Person.validates :karma, format: /positive|negative/
<ide> person = Person.new
<del> assert person.invalid?
<add> assert_predicate person, :invalid?
<ide> assert_equal ["is invalid"], person.errors[:karma]
<ide> person.karma = "positive"
<del> assert person.valid?
<add> assert_predicate person, :valid?
<ide> end
<ide>
<ide> def test_validates_with_array
<ide> Person.validates :gender, inclusion: %w(m f)
<ide> person = Person.new
<del> assert person.invalid?
<add> assert_predicate person, :invalid?
<ide> assert_equal ["is not included in the list"], person.errors[:gender]
<ide> person.gender = "m"
<del> assert person.valid?
<add> assert_predicate person, :valid?
<ide> end
<ide>
<ide> def test_validates_with_range
<ide> Person.validates :karma, length: 6..20
<ide> person = Person.new
<del> assert person.invalid?
<add> assert_predicate person, :invalid?
<ide> assert_equal ["is too short (minimum is 6 characters)"], person.errors[:karma]
<ide> person.karma = "something"
<del> assert person.valid?
<add> assert_predicate person, :valid?
<ide> end
<ide>
<ide> def test_validates_with_validator_class_and_options
<ide> def test_defining_extra_default_keys_for_validates
<ide> topic = Topic.new
<ide> topic.title = "What's happening"
<ide> topic.title_confirmation = "Not this"
<del> assert !topic.valid?
<add> assert_not_predicate topic, :valid?
<ide> assert_equal ["Y U NO CONFIRM"], topic.errors[:title_confirmation]
<ide> end
<ide> end
<ide><path>activemodel/test/cases/validations/with_validation_test.rb
<ide> def check_validity!
<ide> test "with multiple classes" do
<ide> Topic.validates_with(ValidatorThatAddsErrors, OtherValidatorThatAddsErrors)
<ide> topic = Topic.new
<del> assert topic.invalid?
<add> assert_predicate topic, :invalid?
<ide> assert_includes topic.errors[:base], ERROR_MESSAGE
<ide> assert_includes topic.errors[:base], OTHER_ERROR_MESSAGE
<ide> end
<ide> def check_validity!
<ide> validator.expect(:is_a?, false, [String])
<ide>
<ide> Topic.validates_with(validator, if: :condition_is_true, foo: :bar)
<del> assert topic.valid?
<add> assert_predicate topic, :valid?
<ide> validator.verify
<ide> end
<ide>
<ide> test "validates_with with options" do
<ide> Topic.validates_with(ValidatorThatValidatesOptions, field: :first_name)
<ide> topic = Topic.new
<del> assert topic.invalid?
<add> assert_predicate topic, :invalid?
<ide> assert_includes topic.errors[:base], ERROR_MESSAGE
<ide> end
<ide>
<ide> test "validates_with each validator" do
<ide> Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content])
<ide> topic = Topic.new title: "Title", content: "Content"
<del> assert topic.invalid?
<add> assert_predicate topic, :invalid?
<ide> assert_equal ["Value is Title"], topic.errors[:title]
<ide> assert_equal ["Value is Content"], topic.errors[:content]
<ide> end
<ide> def check_validity!
<ide> test "each validator skip nil values if :allow_nil is set to true" do
<ide> Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content], allow_nil: true)
<ide> topic = Topic.new content: ""
<del> assert topic.invalid?
<del> assert topic.errors[:title].empty?
<add> assert_predicate topic, :invalid?
<add> assert_predicate topic.errors[:title], :empty?
<ide> assert_equal ["Value is "], topic.errors[:content]
<ide> end
<ide>
<ide> test "each validator skip blank values if :allow_blank is set to true" do
<ide> Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content], allow_blank: true)
<ide> topic = Topic.new content: ""
<del> assert topic.valid?
<del> assert topic.errors[:title].empty?
<del> assert topic.errors[:content].empty?
<add> assert_predicate topic, :valid?
<add> assert_predicate topic.errors[:title], :empty?
<add> assert_predicate topic.errors[:content], :empty?
<ide> end
<ide>
<ide> test "validates_with can validate with an instance method" do
<ide> Topic.validates :title, with: :my_validation
<ide>
<ide> topic = Topic.new title: "foo"
<del> assert topic.valid?
<del> assert topic.errors[:title].empty?
<add> assert_predicate topic, :valid?
<add> assert_predicate topic.errors[:title], :empty?
<ide>
<ide> topic = Topic.new
<del> assert !topic.valid?
<add> assert_not_predicate topic, :valid?
<ide> assert_equal ["is missing"], topic.errors[:title]
<ide> end
<ide>
<ide> test "optionally pass in the attribute being validated when validating with an instance method" do
<ide> Topic.validates :title, :content, with: :my_validation_with_arg
<ide>
<ide> topic = Topic.new title: "foo"
<del> assert !topic.valid?
<del> assert topic.errors[:title].empty?
<add> assert_not_predicate topic, :valid?
<add> assert_predicate topic.errors[:title], :empty?
<ide> assert_equal ["is missing"], topic.errors[:content]
<ide> end
<ide> end
<ide><path>activemodel/test/cases/validations_test.rb
<ide> def test_single_field_validation
<ide> def test_single_attr_validation_and_error_msg
<ide> r = Reply.new
<ide> r.title = "There's no content!"
<del> assert r.invalid?
<add> assert_predicate r, :invalid?
<ide> assert r.errors[:content].any?, "A reply without content should mark that attribute as invalid"
<ide> assert_equal ["is Empty"], r.errors["content"], "A reply without content should contain an error"
<ide> assert_equal 1, r.errors.count
<ide> end
<ide>
<ide> def test_double_attr_validation_and_error_msg
<ide> r = Reply.new
<del> assert r.invalid?
<add> assert_predicate r, :invalid?
<ide>
<ide> assert r.errors[:title].any?, "A reply without title should mark that attribute as invalid"
<ide> assert_equal ["is Empty"], r.errors["title"], "A reply without title should contain an error"
<ide> def test_errors_on_base_with_symbol_message
<ide>
<ide> def test_errors_empty_after_errors_on_check
<ide> t = Topic.new
<del> assert t.errors[:id].empty?
<del> assert t.errors.empty?
<add> assert_predicate t.errors[:id], :empty?
<add> assert_predicate t.errors, :empty?
<ide> end
<ide>
<ide> def test_validates_each
<ide> def test_validates_each
<ide> hits += 1
<ide> end
<ide> t = Topic.new("title" => "valid", "content" => "whatever")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal 4, hits
<ide> assert_equal %w(gotcha gotcha), t.errors[:title]
<ide> assert_equal %w(gotcha gotcha), t.errors[:content]
<ide> def test_validates_each_custom_reader
<ide> hits += 1
<ide> end
<ide> t = CustomReader.new("title" => "valid", "content" => "whatever")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal 4, hits
<ide> assert_equal %w(gotcha gotcha), t.errors[:title]
<ide> assert_equal %w(gotcha gotcha), t.errors[:content]
<ide> def test_validates_each_custom_reader
<ide> def test_validate_block
<ide> Topic.validate { errors.add("title", "will never be valid") }
<ide> t = Topic.new("title" => "Title", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["will never be valid"], t.errors["title"]
<ide> end
<ide>
<ide> def test_validate_block_with_params
<ide> Topic.validate { |topic| topic.errors.add("title", "will never be valid") }
<ide> t = Topic.new("title" => "Title", "content" => "whatever")
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide> assert_equal ["will never be valid"], t.errors["title"]
<ide> end
<ide>
<ide> def validator_c
<ide> def test_errors_conversions
<ide> Topic.validates_presence_of %w(title content)
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> xml = t.errors.to_xml
<ide> assert_match %r{<errors>}, xml
<ide> def test_validation_order
<ide> Topic.validates_length_of :title, minimum: 2
<ide>
<ide> t = Topic.new("title" => "")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal "can't be blank", t.errors["title"].first
<ide> Topic.validates_presence_of :title, :author_name
<ide> Topic.validate { errors.add("author_email_address", "will never be valid") }
<ide> Topic.validates_length_of :title, :content, minimum: 2
<ide>
<ide> t = Topic.new title: ""
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide>
<ide> assert_equal :title, key = t.errors.keys[0]
<ide> assert_equal "can't be blank", t.errors[key][0]
<ide> def test_validation_with_if_and_on
<ide> t = Topic.new(title: "")
<ide>
<ide> # If block should not fire
<del> assert t.valid?
<del> assert t.author_name.nil?
<add> assert_predicate t, :valid?
<add> assert_predicate t.author_name, :nil?
<ide>
<ide> # If block should fire
<ide> assert t.invalid?(:update)
<ide> def test_invalid_should_be_the_opposite_of_valid
<ide> Topic.validates_presence_of :title
<ide>
<ide> t = Topic.new
<del> assert t.invalid?
<del> assert t.errors[:title].any?
<add> assert_predicate t, :invalid?
<add> assert_predicate t.errors[:title], :any?
<ide>
<ide> t.title = "Things are going to change"
<del> assert !t.invalid?
<add> assert_not_predicate t, :invalid?
<ide> end
<ide>
<ide> def test_validation_with_message_as_proc
<ide> Topic.validates_presence_of(:title, message: proc { "no blanks here".upcase })
<ide>
<ide> t = Topic.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["NO BLANKS HERE"], t.errors[:title]
<ide> end
<ide>
<ide> def test_validations_on_the_instance_level
<ide> Topic.validates :content, length: { minimum: 10 }
<ide>
<ide> topic = Topic.new
<del> assert topic.invalid?
<add> assert_predicate topic, :invalid?
<ide> assert_equal 3, topic.errors.size
<ide>
<ide> topic.title = "Some Title"
<ide> topic.author_name = "Some Author"
<ide> topic.content = "Some Content Whose Length is more than 10."
<del> assert topic.valid?
<add> assert_predicate topic, :valid?
<ide> end
<ide>
<ide> def test_validate
<ide> def test_strict_validation_in_validates
<ide>
<ide> def test_strict_validation_not_fails
<ide> Topic.validates :title, strict: true, presence: true
<del> assert Topic.new(title: "hello").valid?
<add> assert_predicate Topic.new(title: "hello"), :valid?
<ide> end
<ide>
<ide> def test_strict_validation_particular_validator
<ide> def test_validates_with_bang
<ide>
<ide> def test_validates_with_false_hash_value
<ide> Topic.validates :title, presence: false
<del> assert Topic.new.valid?
<add> assert_predicate Topic.new, :valid?
<ide> end
<ide>
<ide> def test_strict_validation_error_message
<ide> def test_dup_validity_is_independent
<ide>
<ide> duped = topic.dup
<ide> duped.title = nil
<del> assert duped.invalid?
<add> assert_predicate duped, :invalid?
<ide>
<ide> topic.title = nil
<ide> duped.title = "Mathematics"
<del> assert topic.invalid?
<del> assert duped.valid?
<add> assert_predicate topic, :invalid?
<add> assert_predicate duped, :valid?
<ide> end
<ide>
<ide> def test_validation_with_message_as_proc_that_takes_a_record_as_a_parameter
<ide> Topic.validates_presence_of(:title, message: proc { |record| "You have failed me for the last time, #{record.author_name}." })
<ide>
<ide> t = Topic.new(author_name: "Admiral")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["You have failed me for the last time, Admiral."], t.errors[:title]
<ide> end
<ide>
<ide> def test_validation_with_message_as_proc_that_takes_record_and_data_as_a_parameters
<ide> Topic.validates_presence_of(:title, message: proc { |record, data| "#{data[:attribute]} is missing. You have failed me for the last time, #{record.author_name}." })
<ide>
<ide> t = Topic.new(author_name: "Admiral")
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> assert_equal ["Title is missing. You have failed me for the last time, Admiral."], t.errors[:title]
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/fixtures.rb
<ide> class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
<ide> # self.use_transactional_tests = true
<ide> #
<ide> # test "godzilla" do
<del> # assert !Foo.all.empty?
<add> # assert_not_empty Foo.all
<ide> # Foo.destroy_all
<del> # assert Foo.all.empty?
<add> # assert_empty Foo.all
<ide> # end
<ide> #
<ide> # test "godzilla aftermath" do
<del> # assert !Foo.all.empty?
<add> # assert_not_empty Foo.all
<ide> # end
<ide> # end
<ide> #
<ide><path>activerecord/test/cases/adapter_test.rb
<ide> def test_indexes
<ide> idx_name = "accounts_idx"
<ide>
<ide> indexes = @connection.indexes("accounts")
<del> assert indexes.empty?
<add> assert_predicate indexes, :empty?
<ide>
<ide> @connection.add_index :accounts, :firm_id, name: idx_name
<ide> indexes = @connection.indexes("accounts")
<ide> def setup
<ide> unless in_memory_db?
<ide> test "transaction state is reset after a reconnect" do
<ide> @connection.begin_transaction
<del> assert @connection.transaction_open?
<add> assert_predicate @connection, :transaction_open?
<ide> @connection.reconnect!
<del> assert !@connection.transaction_open?
<add> assert_not_predicate @connection, :transaction_open?
<ide> end
<ide>
<ide> test "transaction state is reset after a disconnect" do
<ide> @connection.begin_transaction
<del> assert @connection.transaction_open?
<add> assert_predicate @connection, :transaction_open?
<ide> @connection.disconnect!
<del> assert !@connection.transaction_open?
<add> assert_not_predicate @connection, :transaction_open?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb
<ide> def test_columns_include_collation_different_from_table
<ide> end
<ide>
<ide> def test_case_sensitive
<del> assert !CollationTest.columns_hash["string_ci_column"].case_sensitive?
<del> assert CollationTest.columns_hash["string_cs_column"].case_sensitive?
<add> assert_not_predicate CollationTest.columns_hash["string_ci_column"], :case_sensitive?
<add> assert_predicate CollationTest.columns_hash["string_cs_column"], :case_sensitive?
<ide> end
<ide>
<ide> def test_case_insensitive_comparison_for_ci_column
<ide><path>activerecord/test/cases/adapters/mysql2/connection_test.rb
<ide> def test_truncate
<ide> end
<ide>
<ide> def test_no_automatic_reconnection_after_timeout
<del> assert @connection.active?
<add> assert_predicate @connection, :active?
<ide> @connection.update("set @@wait_timeout=1")
<ide> sleep 2
<del> assert !@connection.active?
<add> assert_not_predicate @connection, :active?
<ide> ensure
<ide> # Repair all fixture connections so other tests won't break.
<ide> @fixture_connections.each(&:verify!)
<ide> end
<ide>
<ide> def test_successful_reconnection_after_timeout_with_manual_reconnect
<del> assert @connection.active?
<add> assert_predicate @connection, :active?
<ide> @connection.update("set @@wait_timeout=1")
<ide> sleep 2
<ide> @connection.reconnect!
<del> assert @connection.active?
<add> assert_predicate @connection, :active?
<ide> end
<ide>
<ide> def test_successful_reconnection_after_timeout_with_verify
<del> assert @connection.active?
<add> assert_predicate @connection, :active?
<ide> @connection.update("set @@wait_timeout=1")
<ide> sleep 2
<ide> @connection.verify!
<del> assert @connection.active?
<add> assert_predicate @connection, :active?
<ide> end
<ide>
<ide> def test_execute_after_disconnect
<ide><path>activerecord/test/cases/adapters/mysql2/enum_test.rb
<ide> def test_enum_limit
<ide>
<ide> def test_should_not_be_unsigned
<ide> column = EnumTest.columns_hash["enum_column"]
<del> assert_not column.unsigned?
<add> assert_not_predicate column, :unsigned?
<ide> end
<ide>
<ide> def test_should_not_be_bigint
<ide> column = EnumTest.columns_hash["enum_column"]
<del> assert_not column.bigint?
<add> assert_not_predicate column, :bigint?
<ide> end
<ide> end
<ide><path>activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb
<ide> class UnsignedType < ActiveRecord::Base
<ide> end
<ide>
<ide> @connection.columns("unsigned_types").select { |c| /^unsigned_/.match?(c.name) }.each do |column|
<del> assert column.unsigned?
<add> assert_predicate column, :unsigned?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/adapters/postgresql/array_test.rb
<ide> def setup
<ide> def test_column
<ide> assert_equal :string, @column.type
<ide> assert_equal "character varying(255)", @column.sql_type
<del> assert @column.array?
<del> assert_not @type.binary?
<add> assert_predicate @column, :array?
<add> assert_not_predicate @type, :binary?
<ide>
<ide> ratings_column = PgArray.columns_hash["ratings"]
<ide> assert_equal :integer, ratings_column.type
<del> assert ratings_column.array?
<add> assert_predicate ratings_column, :array?
<ide> end
<ide>
<ide> def test_not_compatible_with_serialize_array
<ide> def test_change_column_with_array
<ide>
<ide> assert_equal :text, column.type
<ide> assert_equal [], PgArray.column_defaults["snippets"]
<del> assert column.array?
<add> assert_predicate column, :array?
<ide> end
<ide>
<ide> def test_change_column_cant_make_non_array_column_to_array
<ide> def test_string_quoting_rules_match_pg_behavior
<ide> x = PgArray.create!(tags: tags)
<ide> x.reload
<ide>
<del> assert_not x.changed?
<add> assert_not_predicate x, :changed?
<ide> end
<ide>
<ide> def test_quoting_non_standard_delimiters
<ide> def test_mutate_array
<ide> x.reload
<ide>
<ide> assert_equal %w(one two three), x.tags
<del> assert_not x.changed?
<add> assert_not_predicate x, :changed?
<ide> end
<ide>
<ide> def test_mutate_value_in_array
<ide> def test_mutate_value_in_array
<ide> x.reload
<ide>
<ide> assert_equal [{ "a" => "c" }, { "b" => "b" }], x.hstores
<del> assert_not x.changed?
<add> assert_not_predicate x, :changed?
<ide> end
<ide>
<ide> def test_datetime_with_timezone_awareness
<ide><path>activerecord/test/cases/adapters/postgresql/bit_string_test.rb
<ide> def test_bit_string_column
<ide> column = PostgresqlBitString.columns_hash["a_bit"]
<ide> assert_equal :bit, column.type
<ide> assert_equal "bit(8)", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlBitString.type_for_attribute("a_bit")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_bit_string_varying_column
<ide> column = PostgresqlBitString.columns_hash["a_bit_varying"]
<ide> assert_equal :bit_varying, column.type
<ide> assert_equal "bit varying(4)", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlBitString.type_for_attribute("a_bit_varying")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_default
<ide><path>activerecord/test/cases/adapters/postgresql/bytea_test.rb
<ide> def test_read_nil_value
<ide> def test_write_value
<ide> data = "\u001F"
<ide> record = ByteaDataType.create(payload: data)
<del> assert_not record.new_record?
<add> assert_not_predicate record, :new_record?
<ide> assert_equal(data, record.payload)
<ide> end
<ide>
<ide> def test_write_binary
<ide> data = File.read(File.join(__dir__, "..", "..", "..", "assets", "example.log"))
<ide> assert(data.size > 1)
<ide> record = ByteaDataType.create(payload: data)
<del> assert_not record.new_record?
<add> assert_not_predicate record, :new_record?
<ide> assert_equal(data, record.payload)
<ide> assert_equal(data, ByteaDataType.where(id: record.id).first.payload)
<ide> end
<ide>
<ide> def test_write_nil
<ide> record = ByteaDataType.create(payload: nil)
<del> assert_not record.new_record?
<add> assert_not_predicate record, :new_record?
<ide> assert_nil(record.payload)
<ide> assert_nil(ByteaDataType.where(id: record.id).first.payload)
<ide> end
<ide><path>activerecord/test/cases/adapters/postgresql/change_schema_test.rb
<ide> def test_change_type_with_array
<ide> connection.change_column :strings, :somedate, :timestamp, array: true, cast_as: :timestamp
<ide> column = connection.columns(:strings).find { |c| c.name == "somedate" }
<ide> assert_equal :datetime, column.type
<del> assert column.array?
<add> assert_predicate column, :array?
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/adapters/postgresql/citext_test.rb
<ide> def test_column
<ide> column = Citext.columns_hash["cival"]
<ide> assert_equal :citext, column.type
<ide> assert_equal "citext", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = Citext.type_for_attribute("cival")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_change_table_supports_json
<ide><path>activerecord/test/cases/adapters/postgresql/composite_test.rb
<ide> def test_column
<ide> column = PostgresqlComposite.columns_hash["address"]
<ide> assert_nil column.type
<ide> assert_equal "full_address", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlComposite.type_for_attribute("address")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_composite_mapping
<ide> def test_column
<ide> column = PostgresqlComposite.columns_hash["address"]
<ide> assert_equal :full_address, column.type
<ide> assert_equal "full_address", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlComposite.type_for_attribute("address")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_composite_mapping
<ide><path>activerecord/test/cases/adapters/postgresql/connection_test.rb
<ide> def test_reconnection_after_actual_disconnection_with_verify
<ide> original_connection_pid = @connection.query("select pg_backend_pid()")
<ide>
<ide> # Sanity check.
<del> assert @connection.active?
<add> assert_predicate @connection, :active?
<ide>
<ide> if @connection.send(:postgresql_version) >= 90200
<ide> secondary_connection = ActiveRecord::Base.connection_pool.checkout
<ide> def test_reconnection_after_actual_disconnection_with_verify
<ide>
<ide> @connection.verify!
<ide>
<del> assert @connection.active?
<add> assert_predicate @connection, :active?
<ide>
<ide> # If we get no exception here, then either we re-connected successfully, or
<ide> # we never actually got disconnected.
<ide><path>activerecord/test/cases/adapters/postgresql/domain_test.rb
<ide> def test_column
<ide> column = PostgresqlDomain.columns_hash["price"]
<ide> assert_equal :decimal, column.type
<ide> assert_equal "custom_money", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlDomain.type_for_attribute("price")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_domain_acts_like_basetype
<ide><path>activerecord/test/cases/adapters/postgresql/enum_test.rb
<ide> def test_column
<ide> column = PostgresqlEnum.columns_hash["current_mood"]
<ide> assert_equal :enum, column.type
<ide> assert_equal "mood", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlEnum.type_for_attribute("current_mood")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_enum_defaults
<ide> def test_no_oid_warning
<ide> @connection.execute "INSERT INTO postgresql_enums VALUES (1, 'sad');"
<ide> stderr_output = capture(:stderr) { PostgresqlEnum.first }
<ide>
<del> assert stderr_output.blank?
<add> assert_predicate stderr_output, :blank?
<ide> end
<ide>
<ide> def test_enum_type_cast
<ide><path>activerecord/test/cases/adapters/postgresql/full_text_test.rb
<ide> def test_tsvector_column
<ide> column = Tsvector.columns_hash["text_vector"]
<ide> assert_equal :tsvector, column.type
<ide> assert_equal "tsvector", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = Tsvector.type_for_attribute("text_vector")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_update_tsvector
<ide><path>activerecord/test/cases/adapters/postgresql/geometric_test.rb
<ide> def test_column
<ide> column = PostgresqlPoint.columns_hash["x"]
<ide> assert_equal :point, column.type
<ide> assert_equal "point", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlPoint.type_for_attribute("x")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_default
<ide> def test_mutation
<ide> p.reload
<ide>
<ide> assert_equal ActiveRecord::Point.new(10.0, 25.0), p.x
<del> assert_not p.changed?
<add> assert_not_predicate p, :changed?
<ide> end
<ide>
<ide> def test_array_assignment
<ide> def test_legacy_column
<ide> column = PostgresqlPoint.columns_hash["legacy_x"]
<ide> assert_equal :point, column.type
<ide> assert_equal "point", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlPoint.type_for_attribute("legacy_x")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_legacy_default
<ide> def test_legacy_mutation
<ide> p.reload
<ide>
<ide> assert_equal [10.0, 25.0], p.legacy_x
<del> assert_not p.changed?
<add> assert_not_predicate p, :changed?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/adapters/postgresql/hstore_test.rb
<ide> def test_disable_enable_hstore
<ide> def test_column
<ide> assert_equal :hstore, @column.type
<ide> assert_equal "hstore", @column.sql_type
<del> assert_not @column.array?
<add> assert_not_predicate @column, :array?
<ide>
<del> assert_not @type.binary?
<add> assert_not_predicate @type, :binary?
<ide> end
<ide>
<ide> def test_default
<ide> def test_changes_in_place
<ide> hstore.reload
<ide>
<ide> assert_equal "four", hstore.settings["three"]
<del> assert_not hstore.changed?
<add> assert_not_predicate hstore, :changed?
<ide> end
<ide>
<ide> def test_dirty_from_user_equal
<ide> def test_dirty_from_user_equal
<ide>
<ide> hstore.settings = { "key" => "value", "alongkey" => "anything" }
<ide> assert_equal settings, hstore.settings
<del> assert_not hstore.changed?
<add> assert_not_predicate hstore, :changed?
<ide> end
<ide>
<ide> def test_hstore_dirty_from_database_equal
<ide> def test_hstore_dirty_from_database_equal
<ide>
<ide> assert_equal settings, hstore.settings
<ide> hstore.settings = settings
<del> assert_not hstore.changed?
<add> assert_not_predicate hstore, :changed?
<ide> end
<ide>
<ide> def test_gen1
<ide><path>activerecord/test/cases/adapters/postgresql/ltree_test.rb
<ide> def test_column
<ide> column = Ltree.columns_hash["path"]
<ide> assert_equal :ltree, column.type
<ide> assert_equal "ltree", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = Ltree.type_for_attribute("path")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_write
<ide><path>activerecord/test/cases/adapters/postgresql/money_test.rb
<ide> def test_column
<ide> assert_equal :money, column.type
<ide> assert_equal "money", column.sql_type
<ide> assert_equal 2, column.scale
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlMoney.type_for_attribute("wealth")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_default
<ide><path>activerecord/test/cases/adapters/postgresql/network_test.rb
<ide> def test_cidr_column
<ide> column = PostgresqlNetworkAddress.columns_hash["cidr_address"]
<ide> assert_equal :cidr, column.type
<ide> assert_equal "cidr", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlNetworkAddress.type_for_attribute("cidr_address")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_inet_column
<ide> column = PostgresqlNetworkAddress.columns_hash["inet_address"]
<ide> assert_equal :inet, column.type
<ide> assert_equal "inet", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlNetworkAddress.type_for_attribute("inet_address")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_macaddr_column
<ide> column = PostgresqlNetworkAddress.columns_hash["mac_address"]
<ide> assert_equal :macaddr, column.type
<ide> assert_equal "macaddr", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = PostgresqlNetworkAddress.type_for_attribute("mac_address")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_network_types
<ide><path>activerecord/test/cases/adapters/postgresql/serial_test.rb
<ide> def test_serial_column
<ide> column = PostgresqlSerial.columns_hash["seq"]
<ide> assert_equal :integer, column.type
<ide> assert_equal "integer", column.sql_type
<del> assert column.serial?
<add> assert_predicate column, :serial?
<ide> end
<ide>
<ide> def test_not_serial_column
<ide> column = PostgresqlSerial.columns_hash["serials_id"]
<ide> assert_equal :integer, column.type
<ide> assert_equal "integer", column.sql_type
<del> assert_not column.serial?
<add> assert_not_predicate column, :serial?
<ide> end
<ide>
<ide> def test_schema_dump_with_shorthand
<ide> def test_bigserial_column
<ide> column = PostgresqlBigSerial.columns_hash["seq"]
<ide> assert_equal :integer, column.type
<ide> assert_equal "bigint", column.sql_type
<del> assert column.serial?
<add> assert_predicate column, :serial?
<ide> end
<ide>
<ide> def test_not_bigserial_column
<ide> column = PostgresqlBigSerial.columns_hash["serials_id"]
<ide> assert_equal :integer, column.type
<ide> assert_equal "bigint", column.sql_type
<del> assert_not column.serial?
<add> assert_not_predicate column, :serial?
<ide> end
<ide>
<ide> def test_schema_dump_with_shorthand
<ide> def test_serial_columns
<ide> columns = @connection.columns(:foo)
<ide> columns.each do |column|
<ide> assert_equal :integer, column.type
<del> assert column.serial?
<add> assert_predicate column, :serial?
<ide> end
<ide> end
<ide>
<ide> def test_serial_columns
<ide> columns = @connection.columns(@table_name)
<ide> columns.each do |column|
<ide> assert_equal :integer, column.type
<del> assert column.serial?
<add> assert_predicate column, :serial?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb
<ide> def test_add_column_with_default_array
<ide> UUIDType.reset_column_information
<ide> column = UUIDType.columns_hash["thingy"]
<ide>
<del> assert column.array?
<add> assert_predicate column, :array?
<ide> assert_equal "{}", column.default
<ide>
<ide> schema = dump_table_schema "uuid_data_type"
<ide> def test_data_type_of_uuid_types
<ide> column = UUIDType.columns_hash["guid"]
<ide> assert_equal :uuid, column.type
<ide> assert_equal "uuid", column.sql_type
<del> assert_not column.array?
<add> assert_not_predicate column, :array?
<ide>
<ide> type = UUIDType.type_for_attribute("guid")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_treat_blank_uuid_as_nil
<ide> def self.name
<ide> duplicate = klass.new(guid: record.guid)
<ide>
<ide> assert record.guid.present? # Ensure we actually are testing a UUID
<del> assert_not duplicate.valid?
<add> assert_not_predicate duplicate, :valid?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb
<ide> def self.name; "Temp"; end
<ide> end
<ide>
<ide> account = model.new
<del> assert account.valid?
<add> assert_predicate account, :valid?
<ide> ensure
<ide> ActiveRecord::Base.belongs_to_required_by_default = original_value
<ide> end
<ide> def self.name; "Temp"; end
<ide> end
<ide>
<ide> account = model.new
<del> assert_not account.valid?
<add> assert_not_predicate account, :valid?
<ide> assert_equal [{ error: :blank }], account.errors.details[:company]
<ide> ensure
<ide> ActiveRecord::Base.belongs_to_required_by_default = original_value
<ide> def self.name; "Temp"; end
<ide> end
<ide>
<ide> account = model.new
<del> assert_not account.valid?
<add> assert_not_predicate account, :valid?
<ide> assert_equal [{ error: :blank }], account.errors.details[:company]
<ide> ensure
<ide> ActiveRecord::Base.belongs_to_required_by_default = original_value
<ide> def test_eager_loading_with_primary_key
<ide> Firm.create("name" => "Apple")
<ide> Client.create("name" => "Citibank", :firm_name => "Apple")
<ide> citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key).first
<del> assert citibank_result.association(:firm_with_primary_key).loaded?
<add> assert_predicate citibank_result.association(:firm_with_primary_key), :loaded?
<ide> end
<ide>
<ide> def test_eager_loading_with_primary_key_as_symbol
<ide> Firm.create("name" => "Apple")
<ide> Client.create("name" => "Citibank", :firm_name => "Apple")
<ide> citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key_symbols).first
<del> assert citibank_result.association(:firm_with_primary_key_symbols).loaded?
<add> assert_predicate citibank_result.association(:firm_with_primary_key_symbols), :loaded?
<ide> end
<ide>
<ide> def test_creating_the_belonging_object
<ide> def test_create!
<ide> client = Client.create!(name: "Jimmy")
<ide> account = client.create_account!(credit_limit: 10)
<ide> assert_equal account, client.account
<del> assert account.persisted?
<add> assert_predicate account, :persisted?
<ide> client.save
<ide> client.reload
<ide> assert_equal account, client.account
<ide> def test_failing_create!
<ide> client = Client.create!(name: "Jimmy")
<ide> assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
<ide> assert_not_nil client.account
<del> assert client.account.new_record?
<add> assert_predicate client.account, :new_record?
<ide> end
<ide>
<ide> def test_reloading_the_belonging_object
<ide> def test_assignment_before_child_saved
<ide> final_cut = Client.new("name" => "Final Cut")
<ide> firm = Firm.find(1)
<ide> final_cut.firm = firm
<del> assert !final_cut.persisted?
<add> assert_not_predicate final_cut, :persisted?
<ide> assert final_cut.save
<del> assert final_cut.persisted?
<del> assert firm.persisted?
<add> assert_predicate final_cut, :persisted?
<add> assert_predicate firm, :persisted?
<ide> assert_equal firm, final_cut.firm
<ide> final_cut.association(:firm).reload
<ide> assert_equal firm, final_cut.firm
<ide> def test_assignment_before_child_saved_with_primary_key
<ide> final_cut = Client.new("name" => "Final Cut")
<ide> firm = Firm.find(1)
<ide> final_cut.firm_with_primary_key = firm
<del> assert !final_cut.persisted?
<add> assert_not_predicate final_cut, :persisted?
<ide> assert final_cut.save
<del> assert final_cut.persisted?
<del> assert firm.persisted?
<add> assert_predicate final_cut, :persisted?
<add> assert_predicate firm, :persisted?
<ide> assert_equal firm, final_cut.firm_with_primary_key
<ide> final_cut.association(:firm_with_primary_key).reload
<ide> assert_equal firm, final_cut.firm_with_primary_key
<ide> def test_association_assignment_sticks
<ide>
<ide> def test_cant_save_readonly_association
<ide> assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! }
<del> assert companies(:first_client).readonly_firm.readonly?
<add> assert_predicate companies(:first_client).readonly_firm, :readonly?
<ide> end
<ide>
<ide> def test_polymorphic_assignment_foreign_key_type_string
<ide> def test_reassigning_the_parent_id_updates_the_object
<ide> firm_proxy = client.send(:association_instance_get, :firm)
<ide> firm_with_condition_proxy = client.send(:association_instance_get, :firm_with_condition)
<ide>
<del> assert !firm_proxy.stale_target?
<del> assert !firm_with_condition_proxy.stale_target?
<add> assert_not_predicate firm_proxy, :stale_target?
<add> assert_not_predicate firm_with_condition_proxy, :stale_target?
<ide> assert_equal companies(:first_firm), client.firm
<ide> assert_equal companies(:first_firm), client.firm_with_condition
<ide>
<ide> client.client_of = companies(:another_firm).id
<ide>
<del> assert firm_proxy.stale_target?
<del> assert firm_with_condition_proxy.stale_target?
<add> assert_predicate firm_proxy, :stale_target?
<add> assert_predicate firm_with_condition_proxy, :stale_target?
<ide> assert_equal companies(:another_firm), client.firm
<ide> assert_equal companies(:another_firm), client.firm_with_condition
<ide> end
<ide> def test_polymorphic_reassignment_of_associated_id_updates_the_object
<ide> sponsor.sponsorable
<ide> proxy = sponsor.send(:association_instance_get, :sponsorable)
<ide>
<del> assert !proxy.stale_target?
<add> assert_not_predicate proxy, :stale_target?
<ide> assert_equal members(:groucho), sponsor.sponsorable
<ide>
<ide> sponsor.sponsorable_id = members(:some_other_guy).id
<ide>
<del> assert proxy.stale_target?
<add> assert_predicate proxy, :stale_target?
<ide> assert_equal members(:some_other_guy), sponsor.sponsorable
<ide> end
<ide>
<ide> def test_polymorphic_reassignment_of_associated_type_updates_the_object
<ide> sponsor.sponsorable
<ide> proxy = sponsor.send(:association_instance_get, :sponsorable)
<ide>
<del> assert !proxy.stale_target?
<add> assert_not_predicate proxy, :stale_target?
<ide> assert_equal members(:groucho), sponsor.sponsorable
<ide>
<ide> sponsor.sponsorable_type = "Firm"
<ide>
<del> assert proxy.stale_target?
<add> assert_predicate proxy, :stale_target?
<ide> assert_equal companies(:first_firm), sponsor.sponsorable
<ide> end
<ide>
<ide> def self.name; "Temp"; end
<ide> comment.post_id = 9223372036854775808 # out of range in the bigint
<ide>
<ide> assert_nil comment.post
<del> assert_not comment.valid?
<add> assert_not_predicate comment, :valid?
<ide> assert_equal [{ error: :blank }], comment.errors.details[:post]
<ide> end
<ide>
<ide> def test_polymorphic_with_custom_primary_key
<ide>
<ide> citibank.firm_id = apple.id.to_s
<ide>
<del> assert !citibank.association(:firm).stale_target?
<add> assert_not_predicate citibank.association(:firm), :stale_target?
<ide> end
<ide>
<ide> def test_reflect_the_most_recent_change
<ide><path>activerecord/test/cases/associations/callbacks_test.rb
<ide> def setup
<ide> @david = authors(:david)
<ide> @thinking = posts(:thinking)
<ide> @authorless = posts(:authorless)
<del> assert @david.post_log.empty?
<add> assert_predicate @david.post_log, :empty?
<ide> end
<ide>
<ide> def test_adding_macro_callbacks
<ide> def test_has_many_callbacks_for_destroy_on_parent
<ide> def test_has_and_belongs_to_many_add_callback
<ide> david = developers(:david)
<ide> ar = projects(:active_record)
<del> assert ar.developers_log.empty?
<add> assert_predicate ar.developers_log, :empty?
<ide> ar.developers_with_callbacks << david
<ide> assert_equal ["before_adding#{david.id}", "after_adding#{david.id}"], ar.developers_log
<ide> ar.developers_with_callbacks << david
<ide> def self.name; Project.name; end
<ide> assert_equal alice, dev
<ide> assert_not_nil new_dev
<ide> assert new_dev, "record should not have been saved"
<del> assert_not alice.new_record?
<add> assert_not_predicate alice, :new_record?
<ide> end
<ide>
<ide> def test_has_and_belongs_to_many_after_add_called_after_save
<ide> ar = projects(:active_record)
<del> assert ar.developers_log.empty?
<add> assert_predicate ar.developers_log, :empty?
<ide> alice = Developer.new(name: "alice")
<ide> ar.developers_with_callbacks << alice
<ide> assert_equal "after_adding#{alice.id}", ar.developers_log.last
<ide> def test_has_and_belongs_to_many_remove_callback
<ide> david = developers(:david)
<ide> jamis = developers(:jamis)
<ide> activerecord = projects(:active_record)
<del> assert activerecord.developers_log.empty?
<add> assert_predicate activerecord.developers_log, :empty?
<ide> activerecord.developers_with_callbacks.delete(david)
<ide> assert_equal ["before_removing#{david.id}", "after_removing#{david.id}"], activerecord.developers_log
<ide>
<ide> def test_has_and_belongs_to_many_remove_callback
<ide>
<ide> def test_has_and_belongs_to_many_does_not_fire_callbacks_on_clear
<ide> activerecord = projects(:active_record)
<del> assert activerecord.developers_log.empty?
<add> assert_predicate activerecord.developers_log, :empty?
<ide> if activerecord.developers_with_callbacks.size == 0
<ide> activerecord.developers << developers(:david)
<ide> activerecord.developers << developers(:jamis)
<ide> def test_dont_add_if_before_callback_raises_exception
<ide> @david.unchangeable_posts << @authorless
<ide> rescue Exception
<ide> end
<del> assert @david.post_log.empty?
<add> assert_predicate @david.post_log, :empty?
<ide> assert_not_includes @david.unchangeable_posts, @authorless
<ide> @david.reload
<ide> assert_not_includes @david.unchangeable_posts, @authorless
<ide><path>activerecord/test/cases/associations/eager_test.rb
<ide> def test_loading_from_an_association
<ide> end
<ide>
<ide> def test_loading_from_an_association_that_has_a_hash_of_conditions
<del> assert !Author.all.merge!(includes: :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts.empty?
<add> assert_not_predicate Author.all.merge!(includes: :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts, :empty?
<ide> end
<ide>
<ide> def test_loading_with_no_associations
<ide> def test_preloading_has_many_through_with_custom_scope
<ide> test "preloading readonly association" do
<ide> # has-one
<ide> firm = Firm.where(id: "1").preload(:readonly_account).first!
<del> assert firm.readonly_account.readonly?
<add> assert_predicate firm.readonly_account, :readonly?
<ide>
<ide> # has_and_belongs_to_many
<ide> project = Project.where(id: "2").preload(:readonly_developers).first!
<del> assert project.readonly_developers.first.readonly?
<add> assert_predicate project.readonly_developers.first, :readonly?
<ide>
<ide> # has-many :through
<ide> david = Author.where(id: "1").preload(:readonly_comments).first!
<del> assert david.readonly_comments.first.readonly?
<add> assert_predicate david.readonly_comments.first, :readonly?
<ide> end
<ide>
<ide> test "eager-loading non-readonly association" do
<ide> # has_one
<ide> firm = Firm.where(id: "1").eager_load(:account).first!
<del> assert_not firm.account.readonly?
<add> assert_not_predicate firm.account, :readonly?
<ide>
<ide> # has_and_belongs_to_many
<ide> project = Project.where(id: "2").eager_load(:developers).first!
<del> assert_not project.developers.first.readonly?
<add> assert_not_predicate project.developers.first, :readonly?
<ide>
<ide> # has_many :through
<ide> david = Author.where(id: "1").eager_load(:comments).first!
<del> assert_not david.comments.first.readonly?
<add> assert_not_predicate david.comments.first, :readonly?
<ide>
<ide> # belongs_to
<ide> post = Post.where(id: "1").eager_load(:author).first!
<del> assert_not post.author.readonly?
<add> assert_not_predicate post.author, :readonly?
<ide> end
<ide>
<ide> test "eager-loading readonly association" do
<ide> # has-one
<ide> firm = Firm.where(id: "1").eager_load(:readonly_account).first!
<del> assert firm.readonly_account.readonly?
<add> assert_predicate firm.readonly_account, :readonly?
<ide>
<ide> # has_and_belongs_to_many
<ide> project = Project.where(id: "2").eager_load(:readonly_developers).first!
<del> assert project.readonly_developers.first.readonly?
<add> assert_predicate project.readonly_developers.first, :readonly?
<ide>
<ide> # has-many :through
<ide> david = Author.where(id: "1").eager_load(:readonly_comments).first!
<del> assert david.readonly_comments.first.readonly?
<add> assert_predicate david.readonly_comments.first, :readonly?
<ide>
<ide> # belongs_to
<ide> post = Post.where(id: "1").eager_load(:readonly_author).first!
<del> assert post.readonly_author.readonly?
<add> assert_predicate post.readonly_author, :readonly?
<ide> end
<ide>
<ide> test "preloading a polymorphic association with references to the associated table" do
<ide><path>activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
<ide> def test_join_table_composite_primary_key_should_not_warn
<ide> def test_has_and_belongs_to_many
<ide> david = Developer.find(1)
<ide>
<del> assert !david.projects.empty?
<add> assert_not_predicate david.projects, :empty?
<ide> assert_equal 2, david.projects.size
<ide>
<ide> active_record = Project.find(1)
<del> assert !active_record.developers.empty?
<add> assert_not_predicate active_record.developers, :empty?
<ide> assert_equal 3, active_record.developers.size
<ide> assert_includes active_record.developers, david
<ide> end
<ide> def test_habtm_adding_before_save
<ide> no_of_projects = Project.count
<ide> aredridel = Developer.new("name" => "Aredridel")
<ide> aredridel.projects.concat([Project.find(1), p = Project.new("name" => "Projekt")])
<del> assert !aredridel.persisted?
<del> assert !p.persisted?
<add> assert_not_predicate aredridel, :persisted?
<add> assert_not_predicate p, :persisted?
<ide> assert aredridel.save
<del> assert aredridel.persisted?
<add> assert_predicate aredridel, :persisted?
<ide> assert_equal no_of_devels + 1, Developer.count
<ide> assert_equal no_of_projects + 1, Project.count
<ide> assert_equal 2, aredridel.projects.size
<ide> def test_habtm_collection_size_from_params
<ide> def test_build
<ide> devel = Developer.find(1)
<ide> proj = assert_no_queries(ignore_none: false) { devel.projects.build("name" => "Projekt") }
<del> assert !devel.projects.loaded?
<add> assert_not_predicate devel.projects, :loaded?
<ide>
<ide> assert_equal devel.projects.last, proj
<del> assert devel.projects.loaded?
<add> assert_predicate devel.projects, :loaded?
<ide>
<del> assert !proj.persisted?
<add> assert_not_predicate proj, :persisted?
<ide> devel.save
<del> assert proj.persisted?
<add> assert_predicate proj, :persisted?
<ide> assert_equal devel.projects.last, proj
<ide> assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
<ide> end
<ide>
<ide> def test_new_aliased_to_build
<ide> devel = Developer.find(1)
<ide> proj = assert_no_queries(ignore_none: false) { devel.projects.new("name" => "Projekt") }
<del> assert !devel.projects.loaded?
<add> assert_not_predicate devel.projects, :loaded?
<ide>
<ide> assert_equal devel.projects.last, proj
<del> assert devel.projects.loaded?
<add> assert_predicate devel.projects, :loaded?
<ide>
<del> assert !proj.persisted?
<add> assert_not_predicate proj, :persisted?
<ide> devel.save
<del> assert proj.persisted?
<add> assert_predicate proj, :persisted?
<ide> assert_equal devel.projects.last, proj
<ide> assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
<ide> end
<ide> def test_build_by_new_record
<ide> devel.projects.build(name: "Make bed")
<ide> proj2 = devel.projects.build(name: "Lie in it")
<ide> assert_equal devel.projects.last, proj2
<del> assert !proj2.persisted?
<add> assert_not_predicate proj2, :persisted?
<ide> devel.save
<del> assert devel.persisted?
<del> assert proj2.persisted?
<add> assert_predicate devel, :persisted?
<add> assert_predicate proj2, :persisted?
<ide> assert_equal devel.projects.last, proj2
<ide> assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated
<ide> end
<ide>
<ide> def test_create
<ide> devel = Developer.find(1)
<ide> proj = devel.projects.create("name" => "Projekt")
<del> assert !devel.projects.loaded?
<add> assert_not_predicate devel.projects, :loaded?
<ide>
<ide> assert_equal devel.projects.last, proj
<del> assert !devel.projects.loaded?
<add> assert_not_predicate devel.projects, :loaded?
<ide>
<del> assert proj.persisted?
<add> assert_predicate proj, :persisted?
<ide> assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
<ide> end
<ide>
<ide> def test_creation_respects_hash_condition
<ide> # in Oracle '' is saved as null therefore need to save ' ' in not null column
<ide> another_post = categories(:general).post_with_conditions.create(body: " ")
<ide>
<del> assert another_post.persisted?
<add> assert_predicate another_post, :persisted?
<ide> assert_equal "Yet Another Testing Title", another_post.title
<ide> end
<ide>
<ide> def test_deleting_all
<ide>
<ide> def test_removing_associations_on_destroy
<ide> david = DeveloperWithBeforeDestroyRaise.find(1)
<del> assert !david.projects.empty?
<add> assert_not_predicate david.projects, :empty?
<ide> david.destroy
<del> assert david.projects.empty?
<del> assert DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1").empty?
<add> assert_predicate david.projects, :empty?
<add> assert_predicate DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1"), :empty?
<ide> end
<ide>
<ide> def test_destroying
<ide> def test_destroying
<ide> end
<ide>
<ide> join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id} AND project_id = #{project.id}")
<del> assert join_records.empty?
<add> assert_predicate join_records, :empty?
<ide>
<ide> assert_equal 1, david.reload.projects.size
<ide> assert_equal 1, david.projects.reload.size
<ide> def test_destroying_many
<ide> end
<ide>
<ide> join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}")
<del> assert join_records.empty?
<add> assert_predicate join_records, :empty?
<ide>
<ide> assert_equal 0, david.reload.projects.size
<ide> assert_equal 0, david.projects.reload.size
<ide> def test_destroying_many
<ide> def test_destroy_all
<ide> david = Developer.find(1)
<ide> david.projects.reload
<del> assert !david.projects.empty?
<add> assert_not_predicate david.projects, :empty?
<ide>
<ide> assert_no_difference "Project.count" do
<ide> david.projects.destroy_all
<ide> end
<ide>
<ide> join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}")
<del> assert join_records.empty?
<add> assert_predicate join_records, :empty?
<ide>
<del> assert david.projects.empty?
<del> assert david.projects.reload.empty?
<add> assert_predicate david.projects, :empty?
<add> assert_predicate david.projects.reload, :empty?
<ide> end
<ide>
<ide> def test_destroy_associations_destroys_multiple_associations
<ide> george = parrots(:george)
<del> assert !george.pirates.empty?
<del> assert !george.treasures.empty?
<add> assert_not_predicate george.pirates, :empty?
<add> assert_not_predicate george.treasures, :empty?
<ide>
<ide> assert_no_difference "Pirate.count" do
<ide> assert_no_difference "Treasure.count" do
<ide> def test_destroy_associations_destroys_multiple_associations
<ide> end
<ide>
<ide> join_records = Parrot.connection.select_all("SELECT * FROM parrots_pirates WHERE parrot_id = #{george.id}")
<del> assert join_records.empty?
<del> assert george.pirates.reload.empty?
<add> assert_predicate join_records, :empty?
<add> assert_predicate george.pirates.reload, :empty?
<ide>
<ide> join_records = Parrot.connection.select_all("SELECT * FROM parrots_treasures WHERE parrot_id = #{george.id}")
<del> assert join_records.empty?
<del> assert george.treasures.reload.empty?
<add> assert_predicate join_records, :empty?
<add> assert_predicate george.treasures.reload, :empty?
<ide> end
<ide>
<ide> def test_associations_with_conditions
<ide> def test_include_uses_array_include_after_loaded
<ide> developer = project.developers.first
<ide>
<ide> assert_no_queries(ignore_none: false) do
<del> assert project.developers.loaded?
<add> assert_predicate project.developers, :loaded?
<ide> assert_includes project.developers, developer
<ide> end
<ide> end
<ide> def test_include_checks_if_record_exists_if_target_not_loaded
<ide> developer = project.developers.first
<ide>
<ide> project.reload
<del> assert ! project.developers.loaded?
<add> assert_not_predicate project.developers, :loaded?
<ide> assert_queries(1) do
<ide> assert_includes project.developers, developer
<ide> end
<del> assert ! project.developers.loaded?
<add> assert_not_predicate project.developers, :loaded?
<ide> end
<ide>
<ide> def test_include_returns_false_for_non_matching_record_to_verify_scoping
<ide> project = projects(:active_record)
<ide> developer = Developer.create name: "Bryan", salary: 50_000
<ide>
<del> assert ! project.developers.loaded?
<add> assert_not_predicate project.developers, :loaded?
<ide> assert ! project.developers.include?(developer)
<ide> end
<ide>
<ide> def test_get_ids_for_loaded_associations
<ide>
<ide> def test_get_ids_for_unloaded_associations_does_not_load_them
<ide> developer = developers(:david)
<del> assert !developer.projects.loaded?
<add> assert_not_predicate developer.projects, :loaded?
<ide> assert_equal projects(:active_record, :action_controller).map(&:id).sort, developer.project_ids.sort
<del> assert !developer.projects.loaded?
<add> assert_not_predicate developer.projects, :loaded?
<ide> end
<ide>
<ide> def test_assign_ids
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> class HasManyAssociationsTestPrimaryKeys < ActiveRecord::TestCase
<ide>
<ide> def test_custom_primary_key_on_new_record_should_fetch_with_query
<ide> subscriber = Subscriber.new(nick: "webster132")
<del> assert !subscriber.subscriptions.loaded?
<add> assert_not_predicate subscriber.subscriptions, :loaded?
<ide>
<ide> assert_queries 1 do
<ide> assert_equal 2, subscriber.subscriptions.size
<ide> def test_custom_primary_key_on_new_record_should_fetch_with_query
<ide>
<ide> def test_association_primary_key_on_new_record_should_fetch_with_query
<ide> author = Author.new(name: "David")
<del> assert !author.essays.loaded?
<add> assert_not_predicate author.essays, :loaded?
<ide>
<ide> assert_queries 1 do
<ide> assert_equal 1, author.essays.size
<ide> def test_has_many_assignment_with_custom_primary_key
<ide>
<ide> def test_blank_custom_primary_key_on_new_record_should_not_run_queries
<ide> author = Author.new
<del> assert !author.essays.loaded?
<add> assert_not_predicate author.essays, :loaded?
<ide>
<ide> assert_queries 0 do
<ide> assert_equal 0, author.essays.size
<ide> def test_clear_collection_should_not_change_updated_at
<ide> part.reload
<ide>
<ide> assert_nil part.ship
<del> assert !part.updated_at_changed?
<add> assert_not_predicate part, :updated_at_changed?
<ide> end
<ide>
<ide> def test_create_from_association_should_respect_default_scope
<ide> def test_finder_method_with_dirty_target
<ide> new_clients << company.clients_of_firm.build(name: "Another Client III")
<ide> end
<ide>
<del> assert_not company.clients_of_firm.loaded?
<add> assert_not_predicate company.clients_of_firm, :loaded?
<ide> assert_queries(1) do
<ide> assert_same new_clients[0], company.clients_of_firm.third
<ide> assert_same new_clients[1], company.clients_of_firm.fourth
<ide> def test_finder_bang_method_with_dirty_target
<ide> new_clients << company.clients_of_firm.build(name: "Another Client III")
<ide> end
<ide>
<del> assert_not company.clients_of_firm.loaded?
<add> assert_not_predicate company.clients_of_firm, :loaded?
<ide> assert_queries(1) do
<ide> assert_same new_clients[0], company.clients_of_firm.third!
<ide> assert_same new_clients[1], company.clients_of_firm.fourth!
<ide> def self.name
<ide> # taking from unloaded Relation
<ide> bob = klass.find(authors(:bob).id)
<ide> new_post = bob.posts.build
<del> assert_not bob.posts.loaded?
<add> assert_not_predicate bob.posts, :loaded?
<ide> assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
<ide> assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
<ide> assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
<ide>
<ide> # taking from loaded Relation
<ide> bob.posts.load
<del> assert bob.posts.loaded?
<add> assert_predicate bob.posts, :loaded?
<ide> assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
<ide> assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
<ide> assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
<ide> def test_find_all
<ide> def test_find_each
<ide> firm = companies(:first_firm)
<ide>
<del> assert ! firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide>
<ide> assert_queries(4) do
<ide> firm.clients.find_each(batch_size: 1) { |c| assert_equal firm.id, c.firm_id }
<ide> end
<ide>
<del> assert ! firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_find_each_with_conditions
<ide> def test_find_each_with_conditions
<ide> end
<ide> end
<ide>
<del> assert ! firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_find_in_batches
<ide> firm = companies(:first_firm)
<ide>
<del> assert ! firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide>
<ide> assert_queries(2) do
<ide> firm.clients.find_in_batches(batch_size: 2) do |clients|
<ide> clients.each { |c| assert_equal firm.id, c.firm_id }
<ide> end
<ide> end
<ide>
<del> assert ! firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_find_all_sanitized
<ide> def test_inverse_on_before_validate
<ide> def test_new_aliased_to_build
<ide> company = companies(:first_firm)
<ide> new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.new("name" => "Another Client") }
<del> assert !company.clients_of_firm.loaded?
<add> assert_not_predicate company.clients_of_firm, :loaded?
<ide>
<ide> assert_equal "Another Client", new_client.name
<del> assert !new_client.persisted?
<add> assert_not_predicate new_client, :persisted?
<ide> assert_equal new_client, company.clients_of_firm.last
<ide> end
<ide>
<ide> def test_build
<ide> company = companies(:first_firm)
<ide> new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build("name" => "Another Client") }
<del> assert !company.clients_of_firm.loaded?
<add> assert_not_predicate company.clients_of_firm, :loaded?
<ide>
<ide> assert_equal "Another Client", new_client.name
<del> assert !new_client.persisted?
<add> assert_not_predicate new_client, :persisted?
<ide> assert_equal new_client, company.clients_of_firm.last
<ide> end
<ide>
<ide> def test_build_many
<ide> def test_build_followed_by_save_does_not_load_target
<ide> companies(:first_firm).clients_of_firm.build("name" => "Another Client")
<ide> assert companies(:first_firm).save
<del> assert !companies(:first_firm).clients_of_firm.loaded?
<add> assert_not_predicate companies(:first_firm).clients_of_firm, :loaded?
<ide> end
<ide>
<ide> def test_build_without_loading_association
<ide> def test_build_without_loading_association
<ide> def test_build_via_block
<ide> company = companies(:first_firm)
<ide> new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build { |client| client.name = "Another Client" } }
<del> assert !company.clients_of_firm.loaded?
<add> assert_not_predicate company.clients_of_firm, :loaded?
<ide>
<ide> assert_equal "Another Client", new_client.name
<del> assert !new_client.persisted?
<add> assert_not_predicate new_client, :persisted?
<ide> assert_equal new_client, company.clients_of_firm.last
<ide> end
<ide>
<ide> def test_create
<ide> assert_predicate companies(:first_firm).clients_of_firm, :loaded?
<ide>
<ide> new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
<del> assert new_client.persisted?
<add> assert_predicate new_client, :persisted?
<ide> assert_equal new_client, companies(:first_firm).clients_of_firm.last
<ide> assert_equal new_client, companies(:first_firm).clients_of_firm.reload.last
<ide> end
<ide> def test_create_many
<ide> def test_create_followed_by_save_does_not_load_target
<ide> companies(:first_firm).clients_of_firm.create("name" => "Another Client")
<ide> assert companies(:first_firm).save
<del> assert !companies(:first_firm).clients_of_firm.loaded?
<add> assert_not_predicate companies(:first_firm).clients_of_firm, :loaded?
<ide> end
<ide>
<ide> def test_deleting
<ide> def test_has_many_without_counter_cache_option
<ide> # option is not given on the association.
<ide> ship = Ship.create(name: "Countless", treasures_count: 10)
<ide>
<del> assert_not Ship.reflect_on_association(:treasures).has_cached_counter?
<add> assert_not_predicate Ship.reflect_on_association(:treasures), :has_cached_counter?
<ide>
<ide> # Count should come from sql count() of treasures rather than treasures_count attribute
<ide> assert_equal ship.treasures.size, 0
<ide> def test_deleting_updates_counter_cache_with_dependent_destroy
<ide> def test_calling_empty_with_counter_cache
<ide> post = posts(:welcome)
<ide> assert_queries(0) do
<del> assert_not post.comments.empty?
<add> assert_not_predicate post.comments, :empty?
<ide> end
<ide> end
<ide>
<ide> def test_creation_respects_hash_condition
<ide>
<ide> another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create
<ide>
<del> assert another_ms_client.persisted?
<add> assert_predicate another_ms_client, :persisted?
<ide> assert_equal "Microsoft", another_ms_client.name
<ide> end
<ide>
<ide> def test_dependence
<ide> firm = companies(:first_firm)
<ide> assert_equal 3, firm.clients.size
<ide> firm.destroy
<del> assert Client.all.merge!(where: "firm_id=#{firm.id}").to_a.empty?
<add> assert_predicate Client.all.merge!(where: "firm_id=#{firm.id}").to_a, :empty?
<ide> end
<ide>
<ide> def test_dependence_for_associations_with_hash_condition
<ide> def test_restrict_with_exception
<ide> firm = RestrictedWithExceptionFirm.create!(name: "restrict")
<ide> firm.companies.create(name: "child")
<ide>
<del> assert !firm.companies.empty?
<add> assert_not_predicate firm.companies, :empty?
<ide> assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
<ide> assert RestrictedWithExceptionFirm.exists?(name: "restrict")
<ide> assert firm.companies.exists?(name: "child")
<ide> def test_restrict_with_error
<ide> firm = RestrictedWithErrorFirm.create!(name: "restrict")
<ide> firm.companies.create(name: "child")
<ide>
<del> assert !firm.companies.empty?
<add> assert_not_predicate firm.companies, :empty?
<ide>
<ide> firm.destroy
<ide>
<del> assert !firm.errors.empty?
<add> assert_not_predicate firm.errors, :empty?
<ide>
<ide> assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
<ide> assert RestrictedWithErrorFirm.exists?(name: "restrict")
<ide> def test_restrict_with_error_with_locale
<ide> firm = RestrictedWithErrorFirm.create!(name: "restrict")
<ide> firm.companies.create(name: "child")
<ide>
<del> assert !firm.companies.empty?
<add> assert_not_predicate firm.companies, :empty?
<ide>
<ide> firm.destroy
<ide>
<del> assert !firm.errors.empty?
<add> assert_not_predicate firm.errors, :empty?
<ide>
<ide> assert_equal "Cannot delete record because dependent client companies exist", firm.errors[:base].first
<ide> assert RestrictedWithErrorFirm.exists?(name: "restrict")
<ide> def test_replace_failure
<ide> account = Account.new
<ide> orig_accounts = firm.accounts.to_a
<ide>
<del> assert !account.valid?
<del> assert !orig_accounts.empty?
<add> assert_not_predicate account, :valid?
<add> assert_not_predicate orig_accounts, :empty?
<ide> error = assert_raise ActiveRecord::RecordNotSaved do
<ide> firm.accounts = [account]
<ide> end
<ide> def test_get_ids_for_loaded_associations
<ide>
<ide> def test_get_ids_for_unloaded_associations_does_not_load_them
<ide> company = companies(:first_firm)
<del> assert !company.clients.loaded?
<add> assert_not_predicate company.clients, :loaded?
<ide> assert_equal [companies(:first_client).id, companies(:second_client).id, companies(:another_first_firm_client).id], company.client_ids
<del> assert !company.clients.loaded?
<add> assert_not_predicate company.clients, :loaded?
<ide> end
<ide>
<ide> def test_counter_cache_on_unloaded_association
<ide> def test_include_uses_array_include_after_loaded
<ide> client = firm.clients.first
<ide>
<ide> assert_no_queries do
<del> assert firm.clients.loaded?
<add> assert_predicate firm.clients, :loaded?
<ide> assert_equal true, firm.clients.include?(client)
<ide> end
<ide> end
<ide> def test_include_checks_if_record_exists_if_target_not_loaded
<ide> client = firm.clients.first
<ide>
<ide> firm.reload
<del> assert ! firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> assert_queries(1) do
<ide> assert_equal true, firm.clients.include?(client)
<ide> end
<del> assert ! firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_include_returns_false_for_non_matching_record_to_verify_scoping
<ide> firm = companies(:first_firm)
<ide> client = Client.create!(name: "Not Associated")
<ide>
<del> assert ! firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> assert_equal false, firm.clients.include?(client)
<ide> end
<ide>
<ide> def test_calling_first_nth_or_last_on_association_should_not_load_association
<ide> firm.clients.first
<ide> firm.clients.second
<ide> firm.clients.last
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query
<ide> firm = companies(:first_firm)
<ide> firm.clients.load_target
<del> assert firm.clients.loaded?
<add> assert_predicate firm.clients, :loaded?
<ide>
<ide> assert_no_queries(ignore_none: false) do
<ide> firm.clients.first
<ide> def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query
<ide> def test_calling_first_or_last_on_existing_record_with_build_should_load_association
<ide> firm = companies(:first_firm)
<ide> firm.clients.build(name: "Foo")
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide>
<ide> assert_queries 1 do
<ide> firm.clients.first
<ide> firm.clients.second
<ide> firm.clients.last
<ide> end
<ide>
<del> assert firm.clients.loaded?
<add> assert_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_first_nth_or_last_on_existing_record_with_create_should_not_load_association
<ide> firm = companies(:first_firm)
<ide> firm.clients.create(name: "Foo")
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide>
<ide> assert_queries 3 do
<ide> firm.clients.first
<ide> firm.clients.second
<ide> firm.clients.last
<ide> end
<ide>
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_first_nth_or_last_on_new_record_should_not_run_queries
<ide> def test_calling_first_nth_or_last_on_new_record_should_not_run_queries
<ide> def test_calling_first_or_last_with_integer_on_association_should_not_load_association
<ide> firm = companies(:first_firm)
<ide> firm.clients.create(name: "Foo")
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide>
<ide> assert_queries 2 do
<ide> firm.clients.first(2)
<ide> firm.clients.last(2)
<ide> end
<ide>
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_many_should_count_instead_of_loading_association
<ide> firm = companies(:first_firm)
<ide> assert_queries(1) do
<ide> firm.clients.many? # use count query
<ide> end
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_many_on_loaded_association_should_not_use_query
<ide> def test_calling_many_should_defer_to_collection_if_using_a_block
<ide> firm.clients.expects(:size).never
<ide> firm.clients.many? { true }
<ide> end
<del> assert firm.clients.loaded?
<add> assert_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_many_should_return_false_if_none_or_one
<ide> firm = companies(:another_firm)
<del> assert !firm.clients_like_ms.many?
<add> assert_not_predicate firm.clients_like_ms, :many?
<ide> assert_equal 0, firm.clients_like_ms.size
<ide>
<ide> firm = companies(:first_firm)
<del> assert !firm.limited_clients.many?
<add> assert_not_predicate firm.limited_clients, :many?
<ide> assert_equal 1, firm.limited_clients.size
<ide> end
<ide>
<ide> def test_calling_many_should_return_true_if_more_than_one
<ide> firm = companies(:first_firm)
<del> assert firm.clients.many?
<add> assert_predicate firm.clients, :many?
<ide> assert_equal 3, firm.clients.size
<ide> end
<ide>
<ide> def test_calling_none_should_count_instead_of_loading_association
<ide> assert_queries(1) do
<ide> firm.clients.none? # use count query
<ide> end
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_none_on_loaded_association_should_not_use_query
<ide> def test_calling_none_should_defer_to_collection_if_using_a_block
<ide> firm.clients.expects(:size).never
<ide> firm.clients.none? { true }
<ide> end
<del> assert firm.clients.loaded?
<add> assert_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_none_should_return_true_if_none
<ide> firm = companies(:another_firm)
<del> assert firm.clients_like_ms.none?
<add> assert_predicate firm.clients_like_ms, :none?
<ide> assert_equal 0, firm.clients_like_ms.size
<ide> end
<ide>
<ide> def test_calling_none_should_return_false_if_any
<ide> firm = companies(:first_firm)
<del> assert !firm.limited_clients.none?
<add> assert_not_predicate firm.limited_clients, :none?
<ide> assert_equal 1, firm.limited_clients.size
<ide> end
<ide>
<ide> def test_calling_one_should_count_instead_of_loading_association
<ide> assert_queries(1) do
<ide> firm.clients.one? # use count query
<ide> end
<del> assert !firm.clients.loaded?
<add> assert_not_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_one_on_loaded_association_should_not_use_query
<ide> def test_calling_one_should_defer_to_collection_if_using_a_block
<ide> firm.clients.expects(:size).never
<ide> firm.clients.one? { true }
<ide> end
<del> assert firm.clients.loaded?
<add> assert_predicate firm.clients, :loaded?
<ide> end
<ide>
<ide> def test_calling_one_should_return_false_if_zero
<ide> firm = companies(:another_firm)
<del> assert ! firm.clients_like_ms.one?
<add> assert_not_predicate firm.clients_like_ms, :one?
<ide> assert_equal 0, firm.clients_like_ms.size
<ide> end
<ide>
<ide> def test_calling_one_should_return_true_if_one
<ide> firm = companies(:first_firm)
<del> assert firm.limited_clients.one?
<add> assert_predicate firm.limited_clients, :one?
<ide> assert_equal 1, firm.limited_clients.size
<ide> end
<ide>
<ide> def test_calling_one_should_return_false_if_more_than_one
<ide> firm = companies(:first_firm)
<del> assert ! firm.clients.one?
<add> assert_not_predicate firm.clients, :one?
<ide> assert_equal 3, firm.clients.size
<ide> end
<ide>
<ide> def test_collection_association_with_private_kernel_method
<ide> post = posts(:welcome)
<ide>
<ide> assert post.taggings_with_delete_all.count > 0
<del> assert !post.taggings_with_delete_all.loaded?
<add> assert_not_predicate post.taggings_with_delete_all, :loaded?
<ide>
<ide> # 2 queries: one DELETE and another to update the counter cache
<ide> assert_queries(2) do
<ide> def test_collection_association_with_private_kernel_method
<ide>
<ide> test "collection proxy respects default scope" do
<ide> author = authors(:mary)
<del> assert !author.first_posts.exists?
<add> assert_not_predicate author.first_posts, :exists?
<ide> end
<ide>
<ide> test "association with extend option" do
<ide> def test_collection_association_with_private_kernel_method
<ide> pirate = FamousPirate.new
<ide> pirate.famous_ships << ship = FamousShip.new
<ide>
<del> assert pirate.valid?
<add> assert_predicate pirate, :valid?
<ide> assert_not pirate.valid?(:conference)
<ide> assert_equal "can't be blank", ship.errors[:name].first
<ide> end
<ide><path>activerecord/test/cases/associations/has_many_through_associations_test.rb
<ide> def test_delete_association
<ide> end
<ide>
<ide> assert_queries(1) do
<del> assert posts(:welcome).people.empty?
<add> assert_predicate posts(:welcome).people, :empty?
<ide> end
<ide>
<del> assert posts(:welcome).reload.people.reload.empty?
<add> assert_predicate posts(:welcome).reload.people.reload, :empty?
<ide> end
<ide>
<ide> def test_destroy_association
<ide> def test_destroy_association
<ide> end
<ide> end
<ide>
<del> assert posts(:welcome).reload.people.empty?
<del> assert posts(:welcome).people.reload.empty?
<add> assert_predicate posts(:welcome).reload.people, :empty?
<add> assert_predicate posts(:welcome).people.reload, :empty?
<ide> end
<ide>
<ide> def test_destroy_all
<ide> def test_destroy_all
<ide> end
<ide> end
<ide>
<del> assert posts(:welcome).reload.people.empty?
<del> assert posts(:welcome).people.reload.empty?
<add> assert_predicate posts(:welcome).reload.people, :empty?
<add> assert_predicate posts(:welcome).people.reload, :empty?
<ide> end
<ide>
<ide> def test_should_raise_exception_for_destroying_mismatching_records
<ide> def test_clear_associations
<ide> end
<ide>
<ide> assert_queries(0) do
<del> assert posts(:welcome).people.empty?
<add> assert_predicate posts(:welcome).people, :empty?
<ide> end
<ide>
<del> assert posts(:welcome).reload.people.reload.empty?
<add> assert_predicate posts(:welcome).reload.people.reload, :empty?
<ide> end
<ide>
<ide> def test_association_callback_ordering
<ide> def test_get_ids_for_loaded_associations
<ide>
<ide> def test_get_ids_for_unloaded_associations_does_not_load_them
<ide> person = people(:michael)
<del> assert !person.posts.loaded?
<add> assert_not_predicate person.posts, :loaded?
<ide> assert_equal [posts(:welcome).id, posts(:authorless).id].sort, person.post_ids.sort
<del> assert !person.posts.loaded?
<add> assert_not_predicate person.posts, :loaded?
<ide> end
<ide>
<ide> def test_association_proxy_transaction_method_starts_transaction_in_association_class
<ide> def test_collection_delete_with_nonstandard_primary_key_on_belongs_to
<ide> category = author.named_categories.create(name: "Primary")
<ide> author.named_categories.delete(category)
<ide> assert !Categorization.exists?(author_id: author.id, named_category_name: category.name)
<del> assert author.named_categories.reload.empty?
<add> assert_predicate author.named_categories.reload, :empty?
<ide> end
<ide>
<ide> def test_collection_singular_ids_getter_with_string_primary_keys
<ide> def test_include_method_in_association_through_should_return_true_for_instance_a
<ide> end
<ide>
<ide> def test_through_association_readonly_should_be_false
<del> assert !people(:michael).posts.first.readonly?
<del> assert !people(:michael).posts.to_a.first.readonly?
<add> assert_not_predicate people(:michael).posts.first, :readonly?
<add> assert_not_predicate people(:michael).posts.to_a.first, :readonly?
<ide> end
<ide>
<ide> def test_can_update_through_association
<ide> def test_has_many_through_belongs_to_should_update_when_the_through_foreign_key_
<ide> post.author_categorizations
<ide> proxy = post.send(:association_instance_get, :author_categorizations)
<ide>
<del> assert !proxy.stale_target?
<add> assert_not_predicate proxy, :stale_target?
<ide> assert_equal authors(:mary).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id)
<ide>
<ide> post.author_id = authors(:david).id
<ide>
<del> assert proxy.stale_target?
<add> assert_predicate proxy, :stale_target?
<ide> assert_equal authors(:david).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id)
<ide> end
<ide>
<ide> def test_deleting_from_has_many_through_a_belongs_to_should_not_try_to_update_co
<ide>
<ide> assert_includes post.author_addresses, address
<ide> post.author_addresses.delete(address)
<del> assert post[:author_count].nil?
<add> assert_predicate post[:author_count], :nil?
<ide> end
<ide>
<ide> def test_primary_key_option_on_source
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb
<ide> def test_nullification_on_destroyed_association
<ide> developer = Developer.create!(name: "Someone")
<ide> ship = Ship.create!(name: "Planet Caravan", developer: developer)
<ide> ship.destroy
<del> assert !ship.persisted?
<del> assert !developer.persisted?
<add> assert_not_predicate ship, :persisted?
<add> assert_not_predicate developer, :persisted?
<ide> end
<ide>
<ide> def test_natural_assignment_to_nil_after_destroy
<ide> def test_restrict_with_exception
<ide>
<ide> assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
<ide> assert RestrictedWithExceptionFirm.exists?(name: "restrict")
<del> assert firm.account.present?
<add> assert_predicate firm.account, :present?
<ide> end
<ide>
<ide> def test_restrict_with_error
<ide> def test_restrict_with_error
<ide>
<ide> firm.destroy
<ide>
<del> assert !firm.errors.empty?
<add> assert_not_predicate firm.errors, :empty?
<ide> assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
<ide> assert RestrictedWithErrorFirm.exists?(name: "restrict")
<del> assert firm.account.present?
<add> assert_predicate firm.account, :present?
<ide> end
<ide>
<ide> def test_restrict_with_error_with_locale
<ide> def test_restrict_with_error_with_locale
<ide>
<ide> firm.destroy
<ide>
<del> assert !firm.errors.empty?
<add> assert_not_predicate firm.errors, :empty?
<ide> assert_equal "Cannot delete record because a dependent firm account exists", firm.errors[:base].first
<ide> assert RestrictedWithErrorFirm.exists?(name: "restrict")
<del> assert firm.account.present?
<add> assert_predicate firm.account, :present?
<ide> ensure
<ide> I18n.backend.reload!
<ide> end
<ide> def test_finding_with_interpolated_condition
<ide> def test_assignment_before_child_saved
<ide> firm = Firm.find(1)
<ide> firm.account = a = Account.new("credit_limit" => 1000)
<del> assert a.persisted?
<add> assert_predicate a, :persisted?
<ide> assert_equal a, firm.account
<ide> assert_equal a, firm.account
<ide> firm.association(:account).reload
<ide> def test_save_still_works_after_accessing_nil_has_one
<ide>
<ide> def test_cant_save_readonly_association
<ide> assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_firm).readonly_account.save! }
<del> assert companies(:first_firm).readonly_account.readonly?
<add> assert_predicate companies(:first_firm).readonly_account, :readonly?
<ide> end
<ide>
<ide> def test_has_one_proxy_should_not_respond_to_private_methods
<ide> def test_build_respects_hash_condition
<ide>
<ide> def test_create_respects_hash_condition
<ide> account = companies(:first_firm).create_account_limit_500_with_hash_conditions
<del> assert account.persisted?
<add> assert_predicate account, :persisted?
<ide> assert_equal 500, account.credit_limit
<ide> end
<ide>
<ide> def test_creation_failure_without_dependent_option
<ide> new_ship = pirate.create_ship
<ide> assert_not_equal ships(:black_pearl), new_ship
<ide> assert_equal new_ship, pirate.ship
<del> assert new_ship.new_record?
<add> assert_predicate new_ship, :new_record?
<ide> assert_nil orig_ship.pirate_id
<ide> assert !orig_ship.changed? # check it was saved
<ide> end
<ide> def test_creation_failure_with_dependent_option
<ide> orig_ship = pirate.dependent_ship
<ide>
<ide> new_ship = pirate.create_dependent_ship
<del> assert new_ship.new_record?
<del> assert orig_ship.destroyed?
<add> assert_predicate new_ship, :new_record?
<add> assert_predicate orig_ship, :destroyed?
<ide> end
<ide>
<ide> def test_creation_failure_due_to_new_record_should_raise_error
<ide> def test_replacement_failure_due_to_existing_record_should_raise_error
<ide> pirate = pirates(:blackbeard)
<ide> pirate.ship.name = nil
<ide>
<del> assert !pirate.ship.valid?
<add> assert_not_predicate pirate.ship, :valid?
<ide> error = assert_raise(ActiveRecord::RecordNotSaved) do
<ide> pirate.ship = ships(:interceptor)
<ide> end
<ide> def test_has_one_assignment_dont_trigger_save_on_change_of_same_object
<ide> ship.save!
<ide>
<ide> ship.name = "new name"
<del> assert ship.changed?
<add> assert_predicate ship, :changed?
<ide> assert_queries(1) do
<ide> # One query for updating name, not triggering query for updating pirate_id
<ide> pirate.ship = ship
<ide><path>activerecord/test/cases/associations/has_one_through_associations_test.rb
<ide> def test_creating_association_builds_through_record
<ide> new_club = new_member.association(:club).build
<ide> assert new_member.current_membership
<ide> assert_equal new_club, new_member.club
<del> assert new_club.new_record?
<del> assert new_member.current_membership.new_record?
<add> assert_predicate new_club, :new_record?
<add> assert_predicate new_member.current_membership, :new_record?
<ide> assert new_member.save
<del> assert new_club.persisted?
<del> assert new_member.current_membership.persisted?
<add> assert_predicate new_club, :persisted?
<add> assert_predicate new_member.current_membership, :persisted?
<ide> end
<ide>
<ide> def test_creating_association_builds_through_record_for_new
<ide> def test_preloading_has_one_through_on_belongs_to
<ide> MemberDetail.all.merge!(includes: :member_type).to_a
<ide> end
<ide> @new_detail = @member_details[0]
<del> assert @new_detail.send(:association, :member_type).loaded?
<add> assert_predicate @new_detail.send(:association, :member_type), :loaded?
<ide> assert_no_queries { @new_detail.member_type }
<ide> end
<ide>
<ide> def test_has_one_through_belongs_to_should_update_when_the_through_foreign_key_c
<ide> minivan.dashboard
<ide> proxy = minivan.send(:association_instance_get, :dashboard)
<ide>
<del> assert !proxy.stale_target?
<add> assert_not_predicate proxy, :stale_target?
<ide> assert_equal dashboards(:cool_first), minivan.dashboard
<ide>
<ide> minivan.speedometer_id = speedometers(:second).id
<ide>
<del> assert proxy.stale_target?
<add> assert_predicate proxy, :stale_target?
<ide> assert_equal dashboards(:second), minivan.dashboard
<ide> end
<ide>
<ide> def test_has_one_through_belongs_to_setting_belongs_to_foreign_key_after_nil_tar
<ide>
<ide> minivan.speedometer_id = speedometers(:second).id
<ide>
<del> assert proxy.stale_target?
<add> assert_predicate proxy, :stale_target?
<ide> assert_equal dashboards(:second), minivan.dashboard
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/inner_join_association_test.rb
<ide> def test_find_with_sti_join
<ide> scope = Post.joins(:special_comments).where(id: posts(:sti_comments).id)
<ide>
<ide> # The join should match SpecialComment and its subclasses only
<del> assert scope.where("comments.type" => "Comment").empty?
<del> assert !scope.where("comments.type" => "SpecialComment").empty?
<del> assert !scope.where("comments.type" => "SubSpecialComment").empty?
<add> assert_predicate scope.where("comments.type" => "Comment"), :empty?
<add> assert_not_predicate scope.where("comments.type" => "SpecialComment"), :empty?
<add> assert_not_predicate scope.where("comments.type" => "SubSpecialComment"), :empty?
<ide> end
<ide>
<ide> def test_find_with_conditions_on_reflection
<del> assert !posts(:welcome).comments.empty?
<add> assert_not_predicate posts(:welcome).comments, :empty?
<ide> assert Post.joins(:nonexistent_comments).where(id: posts(:welcome).id).empty? # [sic!]
<ide> end
<ide>
<ide> def test_find_with_conditions_on_through_reflection
<del> assert !posts(:welcome).tags.empty?
<del> assert Post.joins(:misc_tags).where(id: posts(:welcome).id).empty?
<add> assert_not_predicate posts(:welcome).tags, :empty?
<add> assert_predicate Post.joins(:misc_tags).where(id: posts(:welcome).id), :empty?
<ide> end
<ide>
<ide> test "the default scope of the target is applied when joining associations" do
<ide><path>activerecord/test/cases/associations/inverse_associations_test.rb
<ide> def test_polymorphic_and_has_many_through_relationships_should_not_have_inverses
<ide> def test_polymorphic_has_one_should_find_inverse_automatically
<ide> man_reflection = Man.reflect_on_association(:polymorphic_face_without_inverse)
<ide>
<del> assert man_reflection.has_inverse?
<add> assert_predicate man_reflection, :has_inverse?
<ide> end
<ide> end
<ide>
<ide> def test_should_allow_for_inverse_of_options_in_associations
<ide>
<ide> def test_should_be_able_to_ask_a_reflection_if_it_has_an_inverse
<ide> has_one_with_inverse_ref = Man.reflect_on_association(:face)
<del> assert has_one_with_inverse_ref.has_inverse?
<add> assert_predicate has_one_with_inverse_ref, :has_inverse?
<ide>
<ide> has_many_with_inverse_ref = Man.reflect_on_association(:interests)
<del> assert has_many_with_inverse_ref.has_inverse?
<add> assert_predicate has_many_with_inverse_ref, :has_inverse?
<ide>
<ide> belongs_to_with_inverse_ref = Face.reflect_on_association(:man)
<del> assert belongs_to_with_inverse_ref.has_inverse?
<add> assert_predicate belongs_to_with_inverse_ref, :has_inverse?
<ide>
<ide> has_one_without_inverse_ref = Club.reflect_on_association(:sponsor)
<del> assert !has_one_without_inverse_ref.has_inverse?
<add> assert_not_predicate has_one_without_inverse_ref, :has_inverse?
<ide>
<ide> has_many_without_inverse_ref = Club.reflect_on_association(:memberships)
<del> assert !has_many_without_inverse_ref.has_inverse?
<add> assert_not_predicate has_many_without_inverse_ref, :has_inverse?
<ide>
<ide> belongs_to_without_inverse_ref = Sponsor.reflect_on_association(:sponsor_club)
<del> assert !belongs_to_without_inverse_ref.has_inverse?
<add> assert_not_predicate belongs_to_without_inverse_ref, :has_inverse?
<ide> end
<ide>
<ide> def test_inverse_of_method_should_supply_the_actual_reflection_instance_it_is_the_inverse_of
<ide> def test_find_on_child_instance_with_id_should_not_load_all_child_records
<ide> interest = Interest.create!(man: man)
<ide>
<ide> man.interests.find(interest.id)
<del> assert_not man.interests.loaded?
<add> assert_not_predicate man.interests, :loaded?
<ide> end
<ide>
<ide> def test_raise_record_not_found_error_when_invalid_ids_are_passed
<ide> def test_child_instance_should_point_to_parent_without_saving
<ide> i.man.name = "Charles"
<ide> assert_equal i.man.name, man.name
<ide>
<del> assert !man.persisted?
<add> assert_not_predicate man, :persisted?
<ide> end
<ide>
<ide> def test_inverse_instance_should_be_set_before_find_callbacks_are_run
<ide> reset_callbacks(Interest, :find) do
<ide> Interest.after_find { raise unless association(:man).loaded? && man.present? }
<ide>
<del> assert Man.first.interests.reload.any?
<del> assert Man.includes(:interests).first.interests.any?
<del> assert Man.joins(:interests).includes(:interests).first.interests.any?
<add> assert_predicate Man.first.interests.reload, :any?
<add> assert_predicate Man.includes(:interests).first.interests, :any?
<add> assert_predicate Man.joins(:interests).includes(:interests).first.interests, :any?
<ide> end
<ide> end
<ide>
<ide> def test_inverse_instance_should_be_set_before_initialize_callbacks_are_run
<ide> reset_callbacks(Interest, :initialize) do
<ide> Interest.after_initialize { raise unless association(:man).loaded? && man.present? }
<ide>
<del> assert Man.first.interests.reload.any?
<del> assert Man.includes(:interests).first.interests.any?
<del> assert Man.joins(:interests).includes(:interests).first.interests.any?
<add> assert_predicate Man.first.interests.reload, :any?
<add> assert_predicate Man.includes(:interests).first.interests, :any?
<add> assert_predicate Man.joins(:interests).includes(:interests).first.interests, :any?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/join_model_test.rb
<ide> def test_has_many_distinct_through_join_model
<ide>
<ide> def test_has_many_distinct_through_count
<ide> author = authors(:mary)
<del> assert !authors(:mary).unique_categorized_posts.loaded?
<add> assert_not_predicate authors(:mary).unique_categorized_posts, :loaded?
<ide> assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count }
<ide> assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count(:title) }
<ide> assert_queries(1) { assert_equal 0, author.unique_categorized_posts.where(title: nil).count(:title) }
<del> assert !authors(:mary).unique_categorized_posts.loaded?
<add> assert_not_predicate authors(:mary).unique_categorized_posts, :loaded?
<ide> end
<ide>
<ide> def test_has_many_distinct_through_find
<ide> def test_add_to_self_referential_has_many_through
<ide>
<ide> def test_has_many_through_uses_conditions_specified_on_the_has_many_association
<ide> author = Author.first
<del> assert author.comments.present?
<del> assert author.nonexistent_comments.blank?
<add> assert_predicate author.comments, :present?
<add> assert_predicate author.nonexistent_comments, :blank?
<ide> end
<ide>
<ide> def test_has_many_through_uses_correct_attributes
<ide> def test_associating_unsaved_records_with_has_many_through
<ide>
<ide> saved_post.tags << new_tag
<ide> assert new_tag.persisted? # consistent with habtm!
<del> assert saved_post.persisted?
<add> assert_predicate saved_post, :persisted?
<ide> assert_includes saved_post.tags, new_tag
<ide>
<del> assert new_tag.persisted?
<add> assert_predicate new_tag, :persisted?
<ide> assert_includes saved_post.reload.tags.reload, new_tag
<ide>
<ide> new_post = Post.new(title: "Association replacement works!", body: "You best believe it.")
<ide> saved_tag = tags(:general)
<ide>
<ide> new_post.tags << saved_tag
<del> assert !new_post.persisted?
<del> assert saved_tag.persisted?
<add> assert_not_predicate new_post, :persisted?
<add> assert_predicate saved_tag, :persisted?
<ide> assert_includes new_post.tags, saved_tag
<ide>
<ide> new_post.save!
<del> assert new_post.persisted?
<add> assert_predicate new_post, :persisted?
<ide> assert_includes new_post.reload.tags.reload, saved_tag
<ide>
<del> assert !posts(:thinking).tags.build.persisted?
<del> assert !posts(:thinking).tags.new.persisted?
<add> assert_not_predicate posts(:thinking).tags.build, :persisted?
<add> assert_not_predicate posts(:thinking).tags.new, :persisted?
<ide> end
<ide>
<ide> def test_create_associate_when_adding_to_has_many_through
<ide> def test_add_to_join_table_with_no_id
<ide> def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded
<ide> author = authors(:david)
<ide> assert_equal 10, author.comments.size
<del> assert !author.comments.loaded?
<add> assert_not_predicate author.comments, :loaded?
<ide> end
<ide>
<ide> def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
<ide> c = categories(:general)
<ide> c.categorizations_count = 100
<ide> assert_equal 100, c.categorizations.size
<del> assert !c.categorizations.loaded?
<add> assert_not_predicate c.categorizations, :loaded?
<ide> end
<ide>
<ide> def test_adding_junk_to_has_many_through_should_raise_type_mismatch
<ide> def test_has_many_through_include_uses_array_include_after_loaded
<ide> category = david.categories.first
<ide>
<ide> assert_no_queries do
<del> assert david.categories.loaded?
<add> assert_predicate david.categories, :loaded?
<ide> assert_includes david.categories, category
<ide> end
<ide> end
<ide> def test_has_many_through_include_checks_if_record_exists_if_target_not_loaded
<ide> category = david.categories.first
<ide>
<ide> david.reload
<del> assert ! david.categories.loaded?
<add> assert_not_predicate david.categories, :loaded?
<ide> assert_queries(1) do
<ide> assert_includes david.categories, category
<ide> end
<del> assert ! david.categories.loaded?
<add> assert_not_predicate david.categories, :loaded?
<ide> end
<ide>
<ide> def test_has_many_through_include_returns_false_for_non_matching_record_to_verify_scoping
<ide> david = authors(:david)
<ide> category = Category.create!(name: "Not Associated")
<ide>
<del> assert ! david.categories.loaded?
<add> assert_not_predicate david.categories, :loaded?
<ide> assert ! david.categories.include?(category)
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/left_outer_join_association_test.rb
<ide> def test_find_with_sti_join
<ide> scope = Post.left_outer_joins(:special_comments).where(id: posts(:sti_comments).id)
<ide>
<ide> # The join should match SpecialComment and its subclasses only
<del> assert scope.where("comments.type" => "Comment").empty?
<del> assert !scope.where("comments.type" => "SpecialComment").empty?
<del> assert !scope.where("comments.type" => "SubSpecialComment").empty?
<add> assert_predicate scope.where("comments.type" => "Comment"), :empty?
<add> assert_not_predicate scope.where("comments.type" => "SpecialComment"), :empty?
<add> assert_not_predicate scope.where("comments.type" => "SubSpecialComment"), :empty?
<ide> end
<ide>
<ide> def test_does_not_override_select
<ide> authors = Author.select("authors.name, #{%{(authors.author_address_id || ' ' || authors.author_address_extra_id) as addr_id}}").left_outer_joins(:posts)
<del> assert authors.any?
<add> assert_predicate authors, :any?
<ide> assert_respond_to authors.first, :addr_id
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/nested_through_associations_test.rb
<ide> def test_has_many_through_has_many_with_has_many_through_source_reflection_prelo
<ide>
<ide> # This ensures that the polymorphism of taggings is being observed correctly
<ide> authors = Author.joins(:tags).where("taggings.taggable_type" => "FakeModel")
<del> assert authors.empty?
<add> assert_predicate authors, :empty?
<ide> end
<ide>
<ide> # has_many through
<ide> def test_has_many_through_has_one_with_has_many_through_source_reflection_preloa
<ide>
<ide> members = Member.joins(:organization_member_details).
<ide> where("member_details.id" => 9)
<del> assert members.empty?
<add> assert_predicate members, :empty?
<ide> end
<ide>
<ide> # has_many through
<ide> def test_has_many_through_has_one_through_with_has_many_source_reflection_preloa
<ide>
<ide> members = Member.joins(:organization_member_details_2).
<ide> where("member_details.id" => 9)
<del> assert members.empty?
<add> assert_predicate members, :empty?
<ide> end
<ide>
<ide> # has_many through
<ide> def test_nested_has_many_through_with_a_table_referenced_multiple_times
<ide>
<ide> # Check the polymorphism of taggings is being observed correctly (in both joins)
<ide> authors = Author.joins(:similar_posts).where("taggings.taggable_type" => "FakeModel")
<del> assert authors.empty?
<add> assert_predicate authors, :empty?
<ide> authors = Author.joins(:similar_posts).where("taggings_authors_join.taggable_type" => "FakeModel")
<del> assert authors.empty?
<add> assert_predicate authors, :empty?
<ide> end
<ide>
<ide> def test_nested_has_many_through_with_scope_on_polymorphic_reflection
<ide> def test_has_many_through_with_sti_on_through_reflection
<ide>
<ide> # Ensure STI is respected in the join
<ide> scope = Post.joins(:special_comments_ratings).where(id: posts(:sti_comments).id)
<del> assert scope.where("comments.type" => "Comment").empty?
<del> assert !scope.where("comments.type" => "SpecialComment").empty?
<del> assert !scope.where("comments.type" => "SubSpecialComment").empty?
<add> assert_predicate scope.where("comments.type" => "Comment"), :empty?
<add> assert_not_predicate scope.where("comments.type" => "SpecialComment"), :empty?
<add> assert_not_predicate scope.where("comments.type" => "SubSpecialComment"), :empty?
<ide> end
<ide>
<ide> def test_has_many_through_with_sti_on_nested_through_reflection
<ide> taggings = posts(:sti_comments).special_comments_ratings_taggings
<ide> assert_equal [taggings(:special_comment_rating)], taggings
<ide>
<ide> scope = Post.joins(:special_comments_ratings_taggings).where(id: posts(:sti_comments).id)
<del> assert scope.where("comments.type" => "Comment").empty?
<del> assert !scope.where("comments.type" => "SpecialComment").empty?
<add> assert_predicate scope.where("comments.type" => "Comment"), :empty?
<add> assert_not_predicate scope.where("comments.type" => "SpecialComment"), :empty?
<ide> end
<ide>
<ide> def test_nested_has_many_through_writers_should_raise_error
<ide> def test_nested_has_many_through_with_conditions_on_through_associations
<ide> end
<ide>
<ide> def test_nested_has_many_through_with_conditions_on_through_associations_preload
<del> assert Author.where("tags.id" => 100).joins(:misc_post_first_blue_tags).empty?
<add> assert_predicate Author.where("tags.id" => 100).joins(:misc_post_first_blue_tags), :empty?
<ide>
<ide> authors = assert_queries(3) { Author.includes(:misc_post_first_blue_tags).to_a.sort_by(&:id) }
<ide> blue = tags(:blue)
<ide> def test_nested_has_many_through_should_not_be_autosaved
<ide> c = Categorization.new
<ide> c.author = authors(:david)
<ide> c.post_taggings.to_a
<del> assert !c.post_taggings.empty?
<add> assert_not_predicate c.post_taggings, :empty?
<ide> c.save
<del> assert !c.post_taggings.empty?
<add> assert_not_predicate c.post_taggings, :empty?
<ide> end
<ide>
<ide> def test_polymorphic_has_many_through_when_through_association_has_not_loaded
<ide><path>activerecord/test/cases/associations_test.rb
<ide> def test_loading_the_association_target_should_keep_child_records_marked_for_des
<ide> ship = Ship.create!(name: "The good ship Dollypop")
<ide> part = ship.parts.create!(name: "Mast")
<ide> part.mark_for_destruction
<del> assert ship.parts[0].marked_for_destruction?
<add> assert_predicate ship.parts[0], :marked_for_destruction?
<ide> end
<ide>
<ide> def test_loading_the_association_target_should_load_most_recent_attributes_for_child_records_marked_for_destruction
<ide> def test_push_does_not_load_target
<ide> david = authors(:david)
<ide>
<ide> david.posts << (post = Post.new(title: "New on Edge", body: "More cool stuff!"))
<del> assert !david.posts.loaded?
<add> assert_not_predicate david.posts, :loaded?
<ide> assert_includes david.posts, post
<ide> end
<ide>
<ide> def test_push_has_many_through_does_not_load_target
<ide> david = authors(:david)
<ide>
<ide> david.categories << categories(:technology)
<del> assert !david.categories.loaded?
<add> assert_not_predicate david.categories, :loaded?
<ide> assert_includes david.categories, categories(:technology)
<ide> end
<ide>
<ide> def test_push_followed_by_save_does_not_load_target
<ide> david = authors(:david)
<ide>
<ide> david.posts << (post = Post.new(title: "New on Edge", body: "More cool stuff!"))
<del> assert !david.posts.loaded?
<add> assert_not_predicate david.posts, :loaded?
<ide> david.save
<del> assert !david.posts.loaded?
<add> assert_not_predicate david.posts, :loaded?
<ide> assert_includes david.posts, post
<ide> end
<ide>
<ide> def test_push_does_not_lose_additions_to_new_record
<ide> josh = Author.new(name: "Josh")
<ide> josh.posts << Post.new(title: "New on Edge", body: "More cool stuff!")
<del> assert josh.posts.loaded?
<add> assert_predicate josh.posts, :loaded?
<ide> assert_equal 1, josh.posts.size
<ide> end
<ide>
<ide> def test_append_behaves_like_push
<ide> josh = Author.new(name: "Josh")
<ide> josh.posts.append Post.new(title: "New on Edge", body: "More cool stuff!")
<del> assert josh.posts.loaded?
<add> assert_predicate josh.posts, :loaded?
<ide> assert_equal 1, josh.posts.size
<ide> end
<ide>
<ide> def test_prepend_is_not_defined
<ide> def test_save_on_parent_does_not_load_target
<ide> david = developers(:david)
<ide>
<del> assert !david.projects.loaded?
<add> assert_not_predicate david.projects, :loaded?
<ide> david.update_columns(created_at: Time.now)
<del> assert !david.projects.loaded?
<add> assert_not_predicate david.projects, :loaded?
<ide> end
<ide>
<ide> def test_load_does_load_target
<ide> david = developers(:david)
<ide>
<del> assert !david.projects.loaded?
<add> assert_not_predicate david.projects, :loaded?
<ide> david.projects.load
<del> assert david.projects.loaded?
<add> assert_predicate david.projects, :loaded?
<ide> end
<ide>
<ide> def test_inspect_does_not_reload_a_not_yet_loaded_target
<ide> andreas = Developer.new name: "Andreas", log: "new developer added"
<del> assert !andreas.audit_logs.loaded?
<add> assert_not_predicate andreas.audit_logs, :loaded?
<ide> assert_match(/message: "new developer added"/, andreas.audit_logs.inspect)
<ide> end
<ide>
<ide> def test_scoped_allows_conditions
<ide> test "first! works on loaded associations" do
<ide> david = authors(:david)
<ide> assert_equal david.first_posts.first, david.first_posts.reload.first!
<del> assert david.first_posts.loaded?
<add> assert_predicate david.first_posts, :loaded?
<ide> assert_no_queries { david.first_posts.first! }
<ide> end
<ide>
<ide> def test_pluck_uses_loaded_target
<ide> david = authors(:david)
<ide> assert_equal david.first_posts.pluck(:title), david.first_posts.load.pluck(:title)
<del> assert david.first_posts.loaded?
<add> assert_predicate david.first_posts, :loaded?
<ide> assert_no_queries { david.first_posts.pluck(:title) }
<ide> end
<ide>
<ide> def test_reset_unloads_target
<ide> david = authors(:david)
<ide> david.posts.reload
<ide>
<del> assert david.posts.loaded?
<add> assert_predicate david.posts, :loaded?
<ide> david.posts.reset
<del> assert !david.posts.loaded?
<add> assert_not_predicate david.posts, :loaded?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/attribute_methods_test.rb
<ide> def setup
<ide> end
<ide>
<ide> test "boolean attributes" do
<del> assert !Topic.find(1).approved?
<del> assert Topic.find(2).approved?
<add> assert_not_predicate Topic.find(1), :approved?
<add> assert_predicate Topic.find(2), :approved?
<ide> end
<ide>
<ide> test "set attributes" do
<ide> def topic.title() "b" end
<ide> SQL
<ide>
<ide> assert_equal "Firm", object.string_value
<del> assert object.string_value?
<add> assert_predicate object, :string_value?
<ide>
<ide> object.string_value = " "
<del> assert !object.string_value?
<add> assert_not_predicate object, :string_value?
<ide>
<ide> assert_equal 1, object.int_value.to_i
<del> assert object.int_value?
<add> assert_predicate object, :int_value?
<ide>
<ide> object.int_value = "0"
<del> assert !object.int_value?
<add> assert_not_predicate object, :int_value?
<ide> end
<ide>
<ide> test "non-attribute read and write" do
<ide> def topic.title() "b" end
<ide> else
<ide> topic = Topic.all.merge!(select: "topics.*, 1=2 as is_test").first
<ide> end
<del> assert !topic.is_test?
<add> assert_not_predicate topic, :is_test?
<ide> end
<ide>
<ide> test "typecast attribute from select to true" do
<ide> def topic.title() "b" end
<ide> else
<ide> topic = Topic.all.merge!(select: "topics.*, 2=2 as is_test").first
<ide> end
<del> assert topic.is_test?
<add> assert_predicate topic, :is_test?
<ide> end
<ide>
<ide> test "raises ActiveRecord::DangerousAttributeError when defining an AR method in a model" do
<ide> def topic.title() "b" end
<ide> expected_time = Time.utc(2000, 01, 01, 10)
<ide>
<ide> assert_equal expected_time, record.bonus_time
<del> assert record.bonus_time.utc?
<add> assert_predicate record.bonus_time, :utc?
<ide> end
<ide> end
<ide> end
<ide> def some_method_that_is_not_on_super
<ide> test "came_from_user?" do
<ide> model = @target.first
<ide>
<del> assert_not model.id_came_from_user?
<add> assert_not_predicate model, :id_came_from_user?
<ide> model.id = "omg"
<del> assert model.id_came_from_user?
<add> assert_predicate model, :id_came_from_user?
<ide> end
<ide>
<ide> test "accessed_fields" do
<ide><path>activerecord/test/cases/attributes_test.rb
<ide> def deserialize(*)
<ide> end
<ide>
<ide> test "attributes not backed by database columns are not dirty when unchanged" do
<del> assert_not OverloadedType.new.non_existent_decimal_changed?
<add> assert_not_predicate OverloadedType.new, :non_existent_decimal_changed?
<ide> end
<ide>
<ide> test "attributes not backed by database columns are always initialized" do
<ide> def deserialize(*)
<ide>
<ide> model.foo << "asdf"
<ide> assert_equal "lolasdf", model.foo
<del> assert model.foo_changed?
<add> assert_predicate model, :foo_changed?
<ide>
<ide> model.reload
<ide> assert_equal "lol", model.foo
<ide>
<ide> model.foo = "lol"
<del> assert_not model.changed?
<add> assert_not_predicate model, :changed?
<ide> end
<ide>
<ide> test "attributes not backed by database columns appear in inspect" do
<ide><path>activerecord/test/cases/autosave_association_test.rb
<ide> def self.name; "Reference"; end
<ide>
<ide> u = person.create!(first_name: "cool")
<ide> u.update_attributes!(first_name: "nah") # still valid because validation only applies on 'create'
<del> assert reference.create!(person: u).persisted?
<add> assert_predicate reference.create!(person: u), :persisted?
<ide> end
<ide>
<ide> def test_should_not_add_the_same_callbacks_multiple_times_for_has_one
<ide> def test_cyclic_autosaves_do_not_add_multiple_validations
<ide> ship = ShipWithoutNestedAttributes.new
<ide> ship.prisoners.build
<ide>
<del> assert_not ship.valid?
<add> assert_not_predicate ship, :valid?
<ide> assert_equal 1, ship.errors[:name].length
<ide> end
<ide>
<ide> class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
<ide>
<ide> def test_should_save_parent_but_not_invalid_child
<ide> firm = Firm.new(name: "GlobalMegaCorp")
<del> assert firm.valid?
<add> assert_predicate firm, :valid?
<ide>
<ide> firm.build_account_using_primary_key
<del> assert !firm.build_account_using_primary_key.valid?
<add> assert_not_predicate firm.build_account_using_primary_key, :valid?
<ide>
<ide> assert firm.save
<del> assert !firm.account_using_primary_key.persisted?
<add> assert_not_predicate firm.account_using_primary_key, :persisted?
<ide> end
<ide>
<ide> def test_save_fails_for_invalid_has_one
<ide> firm = Firm.first
<del> assert firm.valid?
<add> assert_predicate firm, :valid?
<ide>
<ide> firm.build_account
<ide>
<del> assert !firm.account.valid?
<del> assert !firm.valid?
<add> assert_not_predicate firm.account, :valid?
<add> assert_not_predicate firm, :valid?
<ide> assert !firm.save
<ide> assert_equal ["is invalid"], firm.errors["account"]
<ide> end
<ide>
<ide> def test_save_succeeds_for_invalid_has_one_with_validate_false
<ide> firm = Firm.first
<del> assert firm.valid?
<add> assert_predicate firm, :valid?
<ide>
<ide> firm.build_unvalidated_account
<ide>
<del> assert !firm.unvalidated_account.valid?
<del> assert firm.valid?
<add> assert_not_predicate firm.unvalidated_account, :valid?
<add> assert_predicate firm, :valid?
<ide> assert firm.save
<ide> end
<ide>
<ide> def test_build_before_child_saved
<ide>
<ide> account = firm.build_account("credit_limit" => 1000)
<ide> assert_equal account, firm.account
<del> assert !account.persisted?
<add> assert_not_predicate account, :persisted?
<ide> assert firm.save
<ide> assert_equal account, firm.account
<del> assert account.persisted?
<add> assert_predicate account, :persisted?
<ide> end
<ide>
<ide> def test_build_before_either_saved
<ide> firm = Firm.new("name" => "GlobalMegaCorp")
<ide>
<ide> firm.account = account = Account.new("credit_limit" => 1000)
<ide> assert_equal account, firm.account
<del> assert !account.persisted?
<add> assert_not_predicate account, :persisted?
<ide> assert firm.save
<ide> assert_equal account, firm.account
<del> assert account.persisted?
<add> assert_predicate account, :persisted?
<ide> end
<ide>
<ide> def test_assignment_before_parent_saved
<ide> firm = Firm.new("name" => "GlobalMegaCorp")
<ide> firm.account = a = Account.find(1)
<del> assert !firm.persisted?
<add> assert_not_predicate firm, :persisted?
<ide> assert_equal a, firm.account
<ide> assert firm.save
<ide> assert_equal a, firm.account
<ide> def test_assignment_before_parent_saved
<ide> def test_assignment_before_either_saved
<ide> firm = Firm.new("name" => "GlobalMegaCorp")
<ide> firm.account = a = Account.new("credit_limit" => 1000)
<del> assert !firm.persisted?
<del> assert !a.persisted?
<add> assert_not_predicate firm, :persisted?
<add> assert_not_predicate a, :persisted?
<ide> assert_equal a, firm.account
<ide> assert firm.save
<del> assert firm.persisted?
<del> assert a.persisted?
<add> assert_predicate firm, :persisted?
<add> assert_predicate a, :persisted?
<ide> assert_equal a, firm.account
<ide> firm.association(:account).reload
<ide> assert_equal a, firm.account
<ide> class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
<ide>
<ide> def test_should_save_parent_but_not_invalid_child
<ide> client = Client.new(name: "Joe (the Plumber)")
<del> assert client.valid?
<add> assert_predicate client, :valid?
<ide>
<ide> client.build_firm
<del> assert !client.firm.valid?
<add> assert_not_predicate client.firm, :valid?
<ide>
<ide> assert client.save
<del> assert !client.firm.persisted?
<add> assert_not_predicate client.firm, :persisted?
<ide> end
<ide>
<ide> def test_save_fails_for_invalid_belongs_to
<ide> # Oracle saves empty string as NULL therefore :message changed to one space
<ide> assert log = AuditLog.create(developer_id: 0, message: " ")
<ide>
<ide> log.developer = Developer.new
<del> assert !log.developer.valid?
<del> assert !log.valid?
<add> assert_not_predicate log.developer, :valid?
<add> assert_not_predicate log, :valid?
<ide> assert !log.save
<ide> assert_equal ["is invalid"], log.errors["developer"]
<ide> end
<ide> def test_save_succeeds_for_invalid_belongs_to_with_validate_false
<ide> assert log = AuditLog.create(developer_id: 0, message: " ")
<ide>
<ide> log.unvalidated_developer = Developer.new
<del> assert !log.unvalidated_developer.valid?
<del> assert log.valid?
<add> assert_not_predicate log.unvalidated_developer, :valid?
<add> assert_predicate log, :valid?
<ide> assert log.save
<ide> end
<ide>
<ide> def test_assignment_before_parent_saved
<ide> apple = Firm.new("name" => "Apple")
<ide> client.firm = apple
<ide> assert_equal apple, client.firm
<del> assert !apple.persisted?
<add> assert_not_predicate apple, :persisted?
<ide> assert client.save
<ide> assert apple.save
<del> assert apple.persisted?
<add> assert_predicate apple, :persisted?
<ide> assert_equal apple, client.firm
<ide> client.association(:firm).reload
<ide> assert_equal apple, client.firm
<ide> def test_assignment_before_either_saved
<ide> final_cut = Client.new("name" => "Final Cut")
<ide> apple = Firm.new("name" => "Apple")
<ide> final_cut.firm = apple
<del> assert !final_cut.persisted?
<del> assert !apple.persisted?
<add> assert_not_predicate final_cut, :persisted?
<add> assert_not_predicate apple, :persisted?
<ide> assert final_cut.save
<del> assert final_cut.persisted?
<del> assert apple.persisted?
<add> assert_predicate final_cut, :persisted?
<add> assert_predicate apple, :persisted?
<ide> assert_equal apple, final_cut.firm
<ide> final_cut.association(:firm).reload
<ide> assert_equal apple, final_cut.firm
<ide> def test_validation_does_not_validate_stale_association_target
<ide> auditlog.developer = invalid_developer
<ide> auditlog.developer_id = valid_developer.id
<ide>
<del> assert auditlog.valid?
<add> assert_predicate auditlog, :valid?
<ide> end
<ide> end
<ide>
<ide> def test_invalid_adding_with_nested_attributes
<ide> molecule.electrons = [valid_electron, invalid_electron]
<ide> molecule.save
<ide>
<del> assert_not invalid_electron.valid?
<del> assert valid_electron.valid?
<add> assert_not_predicate invalid_electron, :valid?
<add> assert_predicate valid_electron, :valid?
<ide> assert_not molecule.persisted?, "Molecule should not be persisted when its electrons are invalid"
<ide> end
<ide>
<ide> def test_errors_should_be_indexed_when_passed_as_array
<ide>
<ide> guitar.tuning_pegs = [tuning_peg_valid, tuning_peg_invalid]
<ide>
<del> assert_not tuning_peg_invalid.valid?
<del> assert tuning_peg_valid.valid?
<del> assert_not guitar.valid?
<add> assert_not_predicate tuning_peg_invalid, :valid?
<add> assert_predicate tuning_peg_valid, :valid?
<add> assert_not_predicate guitar, :valid?
<ide> assert_equal ["is not a number"], guitar.errors["tuning_pegs[1].pitch"]
<ide> assert_not_equal ["is not a number"], guitar.errors["tuning_pegs.pitch"]
<ide> end
<ide> def test_errors_should_be_indexed_when_global_flag_is_set
<ide>
<ide> molecule.electrons = [valid_electron, invalid_electron]
<ide>
<del> assert_not invalid_electron.valid?
<del> assert valid_electron.valid?
<del> assert_not molecule.valid?
<add> assert_not_predicate invalid_electron, :valid?
<add> assert_predicate valid_electron, :valid?
<add> assert_not_predicate molecule, :valid?
<ide> assert_equal ["can't be blank"], molecule.errors["electrons[1].name"]
<ide> assert_not_equal ["can't be blank"], molecule.errors["electrons.name"]
<ide> ensure
<ide> def test_errors_details_should_be_set
<ide>
<ide> molecule.electrons = [valid_electron, invalid_electron]
<ide>
<del> assert_not invalid_electron.valid?
<del> assert valid_electron.valid?
<del> assert_not molecule.valid?
<add> assert_not_predicate invalid_electron, :valid?
<add> assert_predicate valid_electron, :valid?
<add> assert_not_predicate molecule, :valid?
<ide> assert_equal [{ error: :blank }], molecule.errors.details[:"electrons.name"]
<ide> end
<ide>
<ide> def test_errors_details_should_be_indexed_when_passed_as_array
<ide>
<ide> guitar.tuning_pegs = [tuning_peg_valid, tuning_peg_invalid]
<ide>
<del> assert_not tuning_peg_invalid.valid?
<del> assert tuning_peg_valid.valid?
<del> assert_not guitar.valid?
<add> assert_not_predicate tuning_peg_invalid, :valid?
<add> assert_predicate tuning_peg_valid, :valid?
<add> assert_not_predicate guitar, :valid?
<ide> assert_equal [{ error: :not_a_number, value: nil }], guitar.errors.details[:"tuning_pegs[1].pitch"]
<ide> assert_equal [], guitar.errors.details[:"tuning_pegs.pitch"]
<ide> end
<ide> def test_errors_details_should_be_indexed_when_global_flag_is_set
<ide>
<ide> molecule.electrons = [valid_electron, invalid_electron]
<ide>
<del> assert_not invalid_electron.valid?
<del> assert valid_electron.valid?
<del> assert_not molecule.valid?
<add> assert_not_predicate invalid_electron, :valid?
<add> assert_predicate valid_electron, :valid?
<add> assert_not_predicate molecule, :valid?
<ide> assert_equal [{ error: :blank }], molecule.errors.details[:"electrons[1].name"]
<ide> assert_equal [], molecule.errors.details[:"electrons.name"]
<ide> ensure
<ide> def test_valid_adding_with_nested_attributes
<ide> molecule.electrons = [valid_electron]
<ide> molecule.save
<ide>
<del> assert valid_electron.valid?
<del> assert molecule.persisted?
<add> assert_predicate valid_electron, :valid?
<add> assert_predicate molecule, :persisted?
<ide> assert_equal 1, molecule.electrons.count
<ide> end
<ide> end
<ide> class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
<ide> def test_invalid_adding
<ide> firm = Firm.find(1)
<ide> assert !(firm.clients_of_firm << c = Client.new)
<del> assert !c.persisted?
<del> assert !firm.valid?
<add> assert_not_predicate c, :persisted?
<add> assert_not_predicate firm, :valid?
<ide> assert !firm.save
<del> assert !c.persisted?
<add> assert_not_predicate c, :persisted?
<ide> end
<ide>
<ide> def test_invalid_adding_before_save
<ide> new_firm = Firm.new("name" => "A New Firm, Inc")
<ide> new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")])
<del> assert !c.persisted?
<del> assert !c.valid?
<del> assert !new_firm.valid?
<add> assert_not_predicate c, :persisted?
<add> assert_not_predicate c, :valid?
<add> assert_not_predicate new_firm, :valid?
<ide> assert !new_firm.save
<del> assert !c.persisted?
<del> assert !new_firm.persisted?
<add> assert_not_predicate c, :persisted?
<add> assert_not_predicate new_firm, :persisted?
<ide> end
<ide>
<ide> def test_invalid_adding_with_validate_false
<ide> firm = Firm.first
<ide> client = Client.new
<ide> firm.unvalidated_clients_of_firm << client
<ide>
<del> assert firm.valid?
<del> assert !client.valid?
<add> assert_predicate firm, :valid?
<add> assert_not_predicate client, :valid?
<ide> assert firm.save
<del> assert !client.persisted?
<add> assert_not_predicate client, :persisted?
<ide> end
<ide>
<ide> def test_valid_adding_with_validate_false
<ide> def test_valid_adding_with_validate_false
<ide> firm = Firm.first
<ide> client = Client.new("name" => "Apple")
<ide>
<del> assert firm.valid?
<del> assert client.valid?
<del> assert !client.persisted?
<add> assert_predicate firm, :valid?
<add> assert_predicate client, :valid?
<add> assert_not_predicate client, :persisted?
<ide>
<ide> firm.unvalidated_clients_of_firm << client
<ide>
<ide> assert firm.save
<del> assert client.persisted?
<add> assert_predicate client, :persisted?
<ide> assert_equal no_of_clients + 1, Client.count
<ide> end
<ide>
<ide> def test_invalid_build
<ide> new_client = companies(:first_firm).clients_of_firm.build
<del> assert !new_client.persisted?
<del> assert !new_client.valid?
<add> assert_not_predicate new_client, :persisted?
<add> assert_not_predicate new_client, :valid?
<ide> assert_equal new_client, companies(:first_firm).clients_of_firm.last
<ide> assert !companies(:first_firm).save
<del> assert !new_client.persisted?
<add> assert_not_predicate new_client, :persisted?
<ide> assert_equal 2, companies(:first_firm).clients_of_firm.reload.size
<ide> end
<ide>
<ide> def test_adding_before_save
<ide> assert_equal no_of_firms, Firm.count # Firm was not saved to database.
<ide> assert_equal no_of_clients, Client.count # Clients were not saved to database.
<ide> assert new_firm.save
<del> assert new_firm.persisted?
<del> assert c.persisted?
<add> assert_predicate new_firm, :persisted?
<add> assert_predicate c, :persisted?
<ide> assert_equal new_firm, c.firm
<ide> assert_equal no_of_firms + 1, Firm.count # Firm was saved to database.
<ide> assert_equal no_of_clients + 2, Client.count # Clients were saved to database.
<ide> def test_assign_ids_for_through_a_belongs_to
<ide> def test_build_before_save
<ide> company = companies(:first_firm)
<ide> new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build("name" => "Another Client") }
<del> assert !company.clients_of_firm.loaded?
<add> assert_not_predicate company.clients_of_firm, :loaded?
<ide>
<ide> company.name += "-changed"
<ide> assert_queries(2) { assert company.save }
<del> assert new_client.persisted?
<add> assert_predicate new_client, :persisted?
<ide> assert_equal 3, company.clients_of_firm.reload.size
<ide> end
<ide>
<ide> def test_build_many_before_save
<ide> def test_build_via_block_before_save
<ide> company = companies(:first_firm)
<ide> new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build { |client| client.name = "Another Client" } }
<del> assert !company.clients_of_firm.loaded?
<add> assert_not_predicate company.clients_of_firm, :loaded?
<ide>
<ide> company.name += "-changed"
<ide> assert_queries(2) { assert company.save }
<del> assert new_client.persisted?
<add> assert_predicate new_client, :persisted?
<ide> assert_equal 3, company.clients_of_firm.reload.size
<ide> end
<ide>
<ide> def test_autosave_new_record_on_belongs_to_can_be_disabled_per_relationship
<ide> new_account = Account.new("credit_limit" => 1000)
<ide> new_firm = Firm.new("name" => "some firm")
<ide>
<del> assert !new_firm.persisted?
<add> assert_not_predicate new_firm, :persisted?
<ide> new_account.firm = new_firm
<ide> new_account.save!
<ide>
<del> assert new_firm.persisted?
<add> assert_predicate new_firm, :persisted?
<ide>
<ide> new_account = Account.new("credit_limit" => 1000)
<ide> new_autosaved_firm = Firm.new("name" => "some firm")
<ide>
<del> assert !new_autosaved_firm.persisted?
<add> assert_not_predicate new_autosaved_firm, :persisted?
<ide> new_account.unautosaved_firm = new_autosaved_firm
<ide> new_account.save!
<ide>
<del> assert !new_autosaved_firm.persisted?
<add> assert_not_predicate new_autosaved_firm, :persisted?
<ide> end
<ide>
<ide> def test_autosave_new_record_on_has_one_can_be_disabled_per_relationship
<ide> firm = Firm.new("name" => "some firm")
<ide> account = Account.new("credit_limit" => 1000)
<ide>
<del> assert !account.persisted?
<add> assert_not_predicate account, :persisted?
<ide> firm.account = account
<ide> firm.save!
<ide>
<del> assert account.persisted?
<add> assert_predicate account, :persisted?
<ide>
<ide> firm = Firm.new("name" => "some firm")
<ide> account = Account.new("credit_limit" => 1000)
<ide>
<ide> firm.unautosaved_account = account
<ide>
<del> assert !account.persisted?
<add> assert_not_predicate account, :persisted?
<ide> firm.unautosaved_account = account
<ide> firm.save!
<ide>
<del> assert !account.persisted?
<add> assert_not_predicate account, :persisted?
<ide> end
<ide>
<ide> def test_autosave_new_record_on_has_many_can_be_disabled_per_relationship
<ide> firm = Firm.new("name" => "some firm")
<ide> account = Account.new("credit_limit" => 1000)
<ide>
<del> assert !account.persisted?
<add> assert_not_predicate account, :persisted?
<ide> firm.accounts << account
<ide>
<ide> firm.save!
<del> assert account.persisted?
<add> assert_predicate account, :persisted?
<ide>
<ide> firm = Firm.new("name" => "some firm")
<ide> account = Account.new("credit_limit" => 1000)
<ide>
<del> assert !account.persisted?
<add> assert_not_predicate account, :persisted?
<ide> firm.unautosaved_accounts << account
<ide>
<ide> firm.save!
<del> assert !account.persisted?
<add> assert_not_predicate account, :persisted?
<ide> end
<ide>
<ide> def test_autosave_new_record_with_after_create_callback
<ide> def test_a_marked_for_destruction_record_should_not_be_be_marked_after_reload
<ide> @pirate.mark_for_destruction
<ide> @pirate.ship.mark_for_destruction
<ide>
<del> assert !@pirate.reload.marked_for_destruction?
<del> assert !@pirate.ship.reload.marked_for_destruction?
<add> assert_not_predicate @pirate.reload, :marked_for_destruction?
<add> assert_not_predicate @pirate.ship.reload, :marked_for_destruction?
<ide> end
<ide>
<ide> # has_one
<ide> def test_should_destroy_a_child_association_as_part_of_the_save_transaction_if_it_was_marked_for_destruction
<del> assert !@pirate.ship.marked_for_destruction?
<add> assert_not_predicate @pirate.ship, :marked_for_destruction?
<ide>
<ide> @pirate.ship.mark_for_destruction
<ide> id = @pirate.ship.id
<ide>
<del> assert @pirate.ship.marked_for_destruction?
<add> assert_predicate @pirate.ship, :marked_for_destruction?
<ide> assert Ship.find_by_id(id)
<ide>
<ide> @pirate.save
<ide> def test_should_destroy_a_child_association_as_part_of_the_save_transaction_if_i
<ide>
<ide> def test_should_skip_validation_on_a_child_association_if_marked_for_destruction
<ide> @pirate.ship.name = ""
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide>
<ide> @pirate.ship.mark_for_destruction
<ide> @pirate.ship.expects(:valid?).never
<ide> def test_should_not_save_changed_has_one_unchanged_object_if_child_is_saved
<ide>
<ide> # belongs_to
<ide> def test_should_destroy_a_parent_association_as_part_of_the_save_transaction_if_it_was_marked_for_destruction
<del> assert !@ship.pirate.marked_for_destruction?
<add> assert_not_predicate @ship.pirate, :marked_for_destruction?
<ide>
<ide> @ship.pirate.mark_for_destruction
<ide> id = @ship.pirate.id
<ide>
<del> assert @ship.pirate.marked_for_destruction?
<add> assert_predicate @ship.pirate, :marked_for_destruction?
<ide> assert Pirate.find_by_id(id)
<ide>
<ide> @ship.save
<ide> def test_should_destroy_a_parent_association_as_part_of_the_save_transaction_if_
<ide>
<ide> def test_should_skip_validation_on_a_parent_association_if_marked_for_destruction
<ide> @ship.pirate.catchphrase = ""
<del> assert !@ship.valid?
<add> assert_not_predicate @ship, :valid?
<ide>
<ide> @ship.pirate.mark_for_destruction
<ide> @ship.pirate.expects(:valid?).never
<ide> def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_ma
<ide> ids.each { |id| assert klass.find_by_id(id) }
<ide>
<ide> @pirate.save
<del> assert @pirate.reload.birds.empty?
<add> assert_predicate @pirate.reload.birds, :empty?
<ide> ids.each { |id| assert_nil klass.find_by_id(id) }
<ide> end
<ide>
<ide> def test_should_not_resave_destroyed_association
<ide> @pirate.birds.create!(name: :parrot)
<ide> @pirate.birds.first.destroy
<ide> @pirate.save!
<del> assert @pirate.reload.birds.empty?
<add> assert_predicate @pirate.reload.birds, :empty?
<ide> end
<ide>
<ide> def test_should_skip_validation_on_has_many_if_marked_for_destruction
<ide> 2.times { |i| @pirate.birds.create!(name: "birds_#{i}") }
<ide>
<ide> @pirate.birds.each { |bird| bird.name = "" }
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide>
<ide> @pirate.birds.each do |bird|
<ide> bird.mark_for_destruction
<ide> def test_should_skip_validation_on_has_many_if_destroyed
<ide> @pirate.birds.create!(name: "birds_1")
<ide>
<ide> @pirate.birds.each { |bird| bird.name = "" }
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide>
<ide> @pirate.birds.each(&:destroy)
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> end
<ide>
<ide> def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many
<ide> def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marke
<ide> @pirate.save
<ide> end
<ide>
<del> assert @pirate.reload.parrots.empty?
<add> assert_predicate @pirate.reload.parrots, :empty?
<ide>
<ide> join_records = Pirate.connection.select_all("SELECT * FROM parrots_pirates WHERE pirate_id = #{@pirate.id}")
<del> assert join_records.empty?
<add> assert_predicate join_records, :empty?
<ide> end
<ide>
<ide> def test_should_skip_validation_on_habtm_if_marked_for_destruction
<ide> 2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") }
<ide>
<ide> @pirate.parrots.each { |parrot| parrot.name = "" }
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide>
<ide> @pirate.parrots.each do |parrot|
<ide> parrot.mark_for_destruction
<ide> parrot.expects(:valid?).never
<ide> end
<ide>
<ide> @pirate.save!
<del> assert @pirate.reload.parrots.empty?
<add> assert_predicate @pirate.reload.parrots, :empty?
<ide> end
<ide>
<ide> def test_should_skip_validation_on_habtm_if_destroyed
<ide> @pirate.parrots.create!(name: "parrots_1")
<ide>
<ide> @pirate.parrots.each { |parrot| parrot.name = "" }
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide>
<ide> @pirate.parrots.each(&:destroy)
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> end
<ide>
<ide> def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm
<ide> def test_should_automatically_save_bang_the_associated_model
<ide>
<ide> def test_should_automatically_validate_the_associated_model
<ide> @pirate.ship.name = ""
<del> assert @pirate.invalid?
<del> assert @pirate.errors[:"ship.name"].any?
<add> assert_predicate @pirate, :invalid?
<add> assert_predicate @pirate.errors[:"ship.name"], :any?
<ide> end
<ide>
<ide> def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
<ide> @pirate.ship.name = nil
<ide> @pirate.catchphrase = nil
<del> assert @pirate.invalid?
<del> assert @pirate.errors[:"ship.name"].any?
<del> assert @pirate.errors[:catchphrase].any?
<add> assert_predicate @pirate, :invalid?
<add> assert_predicate @pirate.errors[:"ship.name"], :any?
<add> assert_predicate @pirate.errors[:catchphrase], :any?
<ide> end
<ide>
<ide> def test_should_not_ignore_different_error_messages_on_the_same_attribute
<ide> def test_should_not_ignore_different_error_messages_on_the_same_attribute
<ide> Ship.validates_format_of :name, with: /\w/
<ide> @pirate.ship.name = ""
<ide> @pirate.catchphrase = nil
<del> assert @pirate.invalid?
<add> assert_predicate @pirate, :invalid?
<ide> assert_equal ["can't be blank", "is invalid"], @pirate.errors[:"ship.name"]
<ide> ensure
<ide> Ship._validators = old_validators if old_validators
<ide> def test_mark_for_destruction_is_ignored_without_autosave_true
<ide> ship = ShipWithoutNestedAttributes.new(name: "The Black Flag")
<ide> ship.parts.build.mark_for_destruction
<ide>
<del> assert_not ship.valid?
<add> assert_not_predicate ship, :valid?
<ide> end
<ide> end
<ide>
<ide> def test_should_automatically_save_bang_the_associated_model
<ide>
<ide> def test_should_automatically_validate_the_associated_model
<ide> @ship.pirate.catchphrase = ""
<del> assert @ship.invalid?
<del> assert @ship.errors[:"pirate.catchphrase"].any?
<add> assert_predicate @ship, :invalid?
<add> assert_predicate @ship.errors[:"pirate.catchphrase"], :any?
<ide> end
<ide>
<ide> def test_should_merge_errors_on_the_associated_model_onto_the_parent_even_if_it_is_not_valid
<ide> @ship.name = nil
<ide> @ship.pirate.catchphrase = nil
<del> assert @ship.invalid?
<del> assert @ship.errors[:name].any?
<del> assert @ship.errors[:"pirate.catchphrase"].any?
<add> assert_predicate @ship, :invalid?
<add> assert_predicate @ship.errors[:name], :any?
<add> assert_predicate @ship.errors[:"pirate.catchphrase"], :any?
<ide> end
<ide>
<ide> def test_should_still_allow_to_bypass_validations_on_the_associated_model
<ide> def test_should_not_update_children_when_parent_creation_with_no_reason
<ide> def test_should_automatically_validate_the_associated_models
<ide> @pirate.send(@association_name).each { |child| child.name = "" }
<ide>
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide> assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
<del> assert @pirate.errors[@association_name].empty?
<add> assert_predicate @pirate.errors[@association_name], :empty?
<ide> end
<ide>
<ide> def test_should_not_use_default_invalid_error_on_associated_models
<ide> @pirate.send(@association_name).build(name: "")
<ide>
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide> assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
<del> assert @pirate.errors[@association_name].empty?
<add> assert_predicate @pirate.errors[@association_name], :empty?
<ide> end
<ide>
<ide> def test_should_default_invalid_error_from_i18n
<ide> def test_should_default_invalid_error_from_i18n
<ide>
<ide> @pirate.send(@association_name).build(name: "")
<ide>
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide> assert_equal ["cannot be blank"], @pirate.errors["#{@association_name}.name"]
<ide> assert_equal ["#{@association_name.to_s.humanize} name cannot be blank"], @pirate.errors.full_messages
<del> assert @pirate.errors[@association_name].empty?
<add> assert_predicate @pirate.errors[@association_name], :empty?
<ide> ensure
<ide> I18n.backend = I18n::Backend::Simple.new
<ide> end
<ide> def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it
<ide> @pirate.send(@association_name).each { |child| child.name = "" }
<ide> @pirate.catchphrase = nil
<ide>
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide> assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
<del> assert @pirate.errors[:catchphrase].any?
<add> assert_predicate @pirate.errors[:catchphrase], :any?
<ide> end
<ide>
<ide> def test_should_allow_to_bypass_validations_on_the_associated_models_on_update
<ide> def setup
<ide> end
<ide>
<ide> test "should automatically validate associations" do
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> @pirate.birds.each { |bird| bird.name = "" }
<ide>
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide> end
<ide> end
<ide>
<ide> def setup
<ide> end
<ide>
<ide> test "should automatically validate associations with :validate => true" do
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> @pirate.ship.name = ""
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide> end
<ide>
<ide> test "should not automatically add validate associations without :validate => true" do
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> @pirate.non_validated_ship.name = ""
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> end
<ide> end
<ide>
<ide> def setup
<ide> end
<ide>
<ide> test "should automatically validate associations with :validate => true" do
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> @pirate.parrot = Parrot.new(name: "")
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide> end
<ide>
<ide> test "should not automatically validate associations without :validate => true" do
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> @pirate.non_validated_parrot = Parrot.new(name: "")
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> end
<ide> end
<ide>
<ide> def setup
<ide> end
<ide>
<ide> test "should automatically validate associations with :validate => true" do
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> @pirate.parrots = [ Parrot.new(name: "popuga") ]
<ide> @pirate.parrots.each { |parrot| parrot.name = "" }
<del> assert !@pirate.valid?
<add> assert_not_predicate @pirate, :valid?
<ide> end
<ide>
<ide> test "should not automatically validate associations without :validate => true" do
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> @pirate.non_validated_parrots = [ Parrot.new(name: "popuga") ]
<ide> @pirate.non_validated_parrots.each { |parrot| parrot.name = "" }
<del> assert @pirate.valid?
<add> assert_predicate @pirate, :valid?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_select_symbol
<ide> end
<ide>
<ide> def test_table_exists
<del> assert !NonExistentTable.table_exists?
<del> assert Topic.table_exists?
<add> assert_not_predicate NonExistentTable, :table_exists?
<add> assert_predicate Topic, :table_exists?
<ide> end
<ide>
<ide> def test_preserving_date_objects
<ide> def test_null_fields
<ide>
<ide> def test_default_values
<ide> topic = Topic.new
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide> assert_nil topic.written_on
<ide> assert_nil topic.bonus_time
<ide> assert_nil topic.last_read
<ide>
<ide> topic.save
<ide>
<ide> topic = Topic.find(topic.id)
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide> assert_nil topic.last_read
<ide>
<ide> # Oracle has some funky default handling, so it requires a bit of
<ide> def test_boolean
<ide> b_nil = Boolean.find(nil_id)
<ide> assert_nil b_nil.value
<ide> b_false = Boolean.find(false_id)
<del> assert !b_false.value?
<add> assert_not_predicate b_false, :value?
<ide> b_true = Boolean.find(true_id)
<del> assert b_true.value?
<add> assert_predicate b_true, :value?
<ide> end
<ide>
<ide> def test_boolean_without_questionmark
<ide> def test_boolean_cast_from_string
<ide> b_blank = Boolean.find(blank_id)
<ide> assert_nil b_blank.value
<ide> b_false = Boolean.find(false_id)
<del> assert !b_false.value?
<add> assert_not_predicate b_false, :value?
<ide> b_true = Boolean.find(true_id)
<del> assert b_true.value?
<add> assert_predicate b_true, :value?
<ide> end
<ide>
<ide> def test_new_record_returns_boolean
<ide> def test_dup
<ide> duped_topic = nil
<ide> assert_nothing_raised { duped_topic = topic.dup }
<ide> assert_equal topic.title, duped_topic.title
<del> assert !duped_topic.persisted?
<add> assert_not_predicate duped_topic, :persisted?
<ide>
<ide> # test if the attributes have been duped
<ide> topic.title = "a"
<ide> def test_dup
<ide>
<ide> # test if saved clone object differs from original
<ide> duped_topic.save
<del> assert duped_topic.persisted?
<add> assert_predicate duped_topic, :persisted?
<ide> assert_not_equal duped_topic.id, topic.id
<ide>
<ide> duped_topic.reload
<ide> def test_dup_with_aggregate_of_same_name_as_attribute
<ide> assert_nothing_raised { dup = dev.dup }
<ide> assert_kind_of DeveloperSalary, dup.salary
<ide> assert_equal dev.salary.amount, dup.salary.amount
<del> assert !dup.persisted?
<add> assert_not_predicate dup, :persisted?
<ide>
<ide> # test if the attributes have been duped
<ide> original_amount = dup.salary.amount
<ide> dev.salary.amount = 1
<ide> assert_equal original_amount, dup.salary.amount
<ide>
<ide> assert dup.save
<del> assert dup.persisted?
<add> assert_predicate dup, :persisted?
<ide> assert_not_equal dup.id, dev.id
<ide> end
<ide>
<ide> def test_clone_preserves_subtype
<ide>
<ide> def test_clone_of_new_object_with_defaults
<ide> developer = Developer.new
<del> assert !developer.name_changed?
<del> assert !developer.salary_changed?
<add> assert_not_predicate developer, :name_changed?
<add> assert_not_predicate developer, :salary_changed?
<ide>
<ide> cloned_developer = developer.clone
<del> assert !cloned_developer.name_changed?
<del> assert !cloned_developer.salary_changed?
<add> assert_not_predicate cloned_developer, :name_changed?
<add> assert_not_predicate cloned_developer, :salary_changed?
<ide> end
<ide>
<ide> def test_clone_of_new_object_marks_attributes_as_dirty
<ide> developer = Developer.new name: "Bjorn", salary: 100000
<del> assert developer.name_changed?
<del> assert developer.salary_changed?
<add> assert_predicate developer, :name_changed?
<add> assert_predicate developer, :salary_changed?
<ide>
<ide> cloned_developer = developer.clone
<del> assert cloned_developer.name_changed?
<del> assert cloned_developer.salary_changed?
<add> assert_predicate cloned_developer, :name_changed?
<add> assert_predicate cloned_developer, :salary_changed?
<ide> end
<ide>
<ide> def test_clone_of_new_object_marks_as_dirty_only_changed_attributes
<ide> def test_clone_of_new_object_marks_as_dirty_only_changed_attributes
<ide> assert !developer.salary_changed? # attribute has non-nil default value, so treated as not changed
<ide>
<ide> cloned_developer = developer.clone
<del> assert cloned_developer.name_changed?
<add> assert_predicate cloned_developer, :name_changed?
<ide> assert !cloned_developer.salary_changed? # ... and cloned instance should behave same
<ide> end
<ide>
<ide> def test_dup_of_saved_object_marks_attributes_as_dirty
<ide> developer = Developer.create! name: "Bjorn", salary: 100000
<del> assert !developer.name_changed?
<del> assert !developer.salary_changed?
<add> assert_not_predicate developer, :name_changed?
<add> assert_not_predicate developer, :salary_changed?
<ide>
<ide> cloned_developer = developer.dup
<ide> assert cloned_developer.name_changed? # both attributes differ from defaults
<del> assert cloned_developer.salary_changed?
<add> assert_predicate cloned_developer, :salary_changed?
<ide> end
<ide>
<ide> def test_dup_of_saved_object_marks_as_dirty_only_changed_attributes
<ide> developer = Developer.create! name: "Bjorn"
<ide> assert !developer.name_changed? # both attributes of saved object should be treated as not changed
<del> assert !developer.salary_changed?
<add> assert_not_predicate developer, :salary_changed?
<ide>
<ide> cloned_developer = developer.dup
<ide> assert cloned_developer.name_changed? # ... but on cloned object should be
<ide> def test_quote
<ide> end
<ide>
<ide> def test_toggle_attribute
<del> assert !topics(:first).approved?
<add> assert_not_predicate topics(:first), :approved?
<ide> topics(:first).toggle!(:approved)
<del> assert topics(:first).approved?
<add> assert_predicate topics(:first), :approved?
<ide> topic = topics(:first)
<ide> topic.toggle(:approved)
<del> assert !topic.approved?
<add> assert_not_predicate topic, :approved?
<ide> topic.reload
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide> end
<ide>
<ide> def test_reload
<ide> def test_default_values_are_deeply_dupped
<ide> test "resetting column information doesn't remove attribute methods" do
<ide> topic = topics(:first)
<ide>
<del> assert_not topic.id_changed?
<add> assert_not_predicate topic, :id_changed?
<ide>
<ide> Topic.reset_column_information
<ide>
<del> assert_not topic.id_changed?
<add> assert_not_predicate topic, :id_changed?
<ide> end
<ide>
<ide> test "ignored columns are not present in columns_hash" do
<ide><path>activerecord/test/cases/batches_test.rb
<ide> def test_in_batches_should_be_enumerable_if_no_block_given
<ide> def test_in_batches_each_record_should_yield_record_if_block_is_given
<ide> assert_queries(6) do
<ide> Post.in_batches(of: 2).each_record do |post|
<del> assert post.title.present?
<add> assert_predicate post.title, :present?
<ide> assert_kind_of Post, post
<ide> end
<ide> end
<ide> def test_in_batches_each_record_should_yield_record_if_block_is_given
<ide> def test_in_batches_each_record_should_return_enumerator_if_no_block_given
<ide> assert_queries(6) do
<ide> Post.in_batches(of: 2).each_record.with_index do |post, i|
<del> assert post.title.present?
<add> assert_predicate post.title, :present?
<ide> assert_kind_of Post, post
<ide> end
<ide> end
<ide> def test_in_batches_delete_all_should_not_delete_records_in_other_batches
<ide>
<ide> def test_in_batches_should_not_be_loaded
<ide> Post.in_batches(of: 1) do |relation|
<del> assert_not relation.loaded?
<add> assert_not_predicate relation, :loaded?
<ide> end
<ide>
<ide> Post.in_batches(of: 1, load: false) do |relation|
<del> assert_not relation.loaded?
<add> assert_not_predicate relation, :loaded?
<ide> end
<ide> end
<ide>
<ide> def test_in_batches_should_be_loaded
<ide> Post.in_batches(of: 1, load: true) do |relation|
<del> assert relation.loaded?
<add> assert_predicate relation, :loaded?
<ide> end
<ide> end
<ide>
<ide> def test_in_batches_if_not_loaded_executes_more_queries
<ide> assert_queries(@total + 1) do
<ide> Post.in_batches(of: 1, load: false) do |relation|
<del> assert_not relation.loaded?
<add> assert_not_predicate relation, :loaded?
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/cache_key_test.rb
<ide> class CacheMeWithVersion < ActiveRecord::Base
<ide> end
<ide>
<ide> test "cache_version is only there when versioning is on" do
<del> assert CacheMeWithVersion.create.cache_version.present?
<del> assert_not CacheMe.create.cache_version.present?
<add> assert_predicate CacheMeWithVersion.create.cache_version, :present?
<add> assert_not_predicate CacheMe.create.cache_version, :present?
<ide> end
<ide>
<ide> test "cache_key_with_version always has both key and version" do
<ide><path>activerecord/test/cases/callbacks_test.rb
<ide> def assert_save_callbacks_not_called(someone)
<ide> def test_before_create_throwing_abort
<ide> someone = CallbackHaltedDeveloper.new
<ide> someone.cancel_before_create = true
<del> assert someone.valid?
<add> assert_predicate someone, :valid?
<ide> assert !someone.save
<ide> assert_save_callbacks_not_called(someone)
<ide> end
<ide>
<ide> def test_before_save_throwing_abort
<ide> david = DeveloperWithCanceledCallbacks.find(1)
<del> assert david.valid?
<add> assert_predicate david, :valid?
<ide> assert !david.save
<ide> exc = assert_raise(ActiveRecord::RecordNotSaved) { david.save! }
<ide> assert_equal david, exc.record
<ide>
<ide> david = DeveloperWithCanceledCallbacks.find(1)
<ide> david.salary = 10_000_000
<del> assert !david.valid?
<add> assert_not_predicate david, :valid?
<ide> assert !david.save
<ide> assert_raise(ActiveRecord::RecordInvalid) { david.save! }
<ide>
<ide> someone = CallbackHaltedDeveloper.find(1)
<ide> someone.cancel_before_save = true
<del> assert someone.valid?
<add> assert_predicate someone, :valid?
<ide> assert !someone.save
<ide> assert_save_callbacks_not_called(someone)
<ide> end
<ide>
<ide> def test_before_update_throwing_abort
<ide> someone = CallbackHaltedDeveloper.find(1)
<ide> someone.cancel_before_update = true
<del> assert someone.valid?
<add> assert_predicate someone, :valid?
<ide> assert !someone.save
<ide> assert_save_callbacks_not_called(someone)
<ide> end
<ide><path>activerecord/test/cases/clone_test.rb
<ide> def test_freezing_a_cloned_model_does_not_freeze_clone
<ide> cloned = Topic.new
<ide> clone = cloned.clone
<ide> cloned.freeze
<del> assert_not clone.frozen?
<add> assert_not_predicate clone, :frozen?
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/connection_adapters/adapter_leasing_test.rb
<ide> def test_close
<ide>
<ide> # Make sure the pool marks the connection in use
<ide> assert_equal @adapter, pool.connection
<del> assert @adapter.in_use?
<add> assert_predicate @adapter, :in_use?
<ide>
<ide> # Close should put the adapter back in the pool
<ide> @adapter.close
<del> assert_not @adapter.in_use?
<add> assert_not_predicate @adapter, :in_use?
<ide>
<ide> assert_equal @adapter, pool.connection
<ide> end
<ide><path>activerecord/test/cases/connection_adapters/connection_handler_test.rb
<ide> def test_retrieve_connection
<ide> end
<ide>
<ide> def test_active_connections?
<del> assert !@handler.active_connections?
<add> assert_not_predicate @handler, :active_connections?
<ide> assert @handler.retrieve_connection(@spec_name)
<del> assert @handler.active_connections?
<add> assert_predicate @handler, :active_connections?
<ide> @handler.clear_active_connections!
<del> assert !@handler.active_connections?
<add> assert_not_predicate @handler, :active_connections?
<ide> end
<ide>
<ide> def test_retrieve_connection_pool
<ide> def test_connection_pool_per_pid
<ide>
<ide> def test_forked_child_doesnt_mangle_parent_connection
<ide> object_id = ActiveRecord::Base.connection.object_id
<del> assert ActiveRecord::Base.connection.active?
<add> assert_predicate ActiveRecord::Base.connection, :active?
<ide>
<ide> rd, wr = IO.pipe
<ide> rd.binmode
<ide> def test_forked_child_doesnt_mangle_parent_connection
<ide> unless in_memory_db?
<ide> def test_forked_child_recovers_from_disconnected_parent
<ide> object_id = ActiveRecord::Base.connection.object_id
<del> assert ActiveRecord::Base.connection.active?
<add> assert_predicate ActiveRecord::Base.connection, :active?
<ide>
<ide> rd, wr = IO.pipe
<ide> rd.binmode
<ide><path>activerecord/test/cases/connection_management_test.rb
<ide> def setup
<ide>
<ide> # make sure we have an active connection
<ide> assert ActiveRecord::Base.connection
<del> assert ActiveRecord::Base.connection_handler.active_connections?
<add> assert_predicate ActiveRecord::Base.connection_handler, :active_connections?
<ide> end
<ide>
<ide> def test_app_delegation
<ide> def test_body_responds_to_each
<ide> def test_connections_are_cleared_after_body_close
<ide> _, _, body = @management.call(@env)
<ide> body.close
<del> assert !ActiveRecord::Base.connection_handler.active_connections?
<add> assert_not_predicate ActiveRecord::Base.connection_handler, :active_connections?
<ide> end
<ide>
<ide> def test_active_connections_are_not_cleared_on_body_close_during_transaction
<ide> ActiveRecord::Base.transaction do
<ide> _, _, body = @management.call(@env)
<ide> body.close
<del> assert ActiveRecord::Base.connection_handler.active_connections?
<add> assert_predicate ActiveRecord::Base.connection_handler, :active_connections?
<ide> end
<ide> end
<ide>
<ide> def test_connections_closed_if_exception
<ide> app = Class.new(App) { def call(env); raise NotImplementedError; end }.new
<ide> explosive = middleware(app)
<ide> assert_raises(NotImplementedError) { explosive.call(@env) }
<del> assert !ActiveRecord::Base.connection_handler.active_connections?
<add> assert_not_predicate ActiveRecord::Base.connection_handler, :active_connections?
<ide> end
<ide>
<ide> def test_connections_not_closed_if_exception_inside_transaction
<ide> ActiveRecord::Base.transaction do
<ide> app = Class.new(App) { def call(env); raise RuntimeError; end }.new
<ide> explosive = middleware(app)
<ide> assert_raises(RuntimeError) { explosive.call(@env) }
<del> assert ActiveRecord::Base.connection_handler.active_connections?
<add> assert_predicate ActiveRecord::Base.connection_handler, :active_connections?
<ide> end
<ide> end
<ide>
<ide> test "doesn't clear active connections when running in a test case" do
<ide> executor.wrap do
<ide> @management.call(@env)
<del> assert ActiveRecord::Base.connection_handler.active_connections?
<add> assert_predicate ActiveRecord::Base.connection_handler, :active_connections?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/connection_pool_test.rb
<ide> def active_connections(pool)
<ide>
<ide> def test_checkout_after_close
<ide> connection = pool.connection
<del> assert connection.in_use?
<add> assert_predicate connection, :in_use?
<ide>
<ide> connection.close
<del> assert !connection.in_use?
<add> assert_not_predicate connection, :in_use?
<ide>
<del> assert pool.connection.in_use?
<add> assert_predicate pool.connection, :in_use?
<ide> end
<ide>
<ide> def test_released_connection_moves_between_threads
<ide> def test_with_connection
<ide> end
<ide>
<ide> def test_active_connection_in_use
<del> assert !pool.active_connection?
<add> assert_not_predicate pool, :active_connection?
<ide> main_thread = pool.connection
<ide>
<del> assert pool.active_connection?
<add> assert_predicate pool, :active_connection?
<ide>
<ide> main_thread.close
<ide>
<del> assert !pool.active_connection?
<add> assert_not_predicate pool, :active_connection?
<ide> end
<ide>
<ide> def test_full_pool_exception
<ide> def idle_conn.seconds_idle
<ide>
<ide> def test_remove_connection
<ide> conn = @pool.checkout
<del> assert conn.in_use?
<add> assert_predicate conn, :in_use?
<ide>
<ide> length = @pool.connections.length
<ide> @pool.remove conn
<del> assert conn.in_use?
<add> assert_predicate conn, :in_use?
<ide> assert_equal(length - 1, @pool.connections.length)
<ide> ensure
<ide> conn.close
<ide> def test_remove_connection_for_thread
<ide> end
<ide>
<ide> def test_active_connection?
<del> assert !@pool.active_connection?
<add> assert_not_predicate @pool, :active_connection?
<ide> assert @pool.connection
<del> assert @pool.active_connection?
<add> assert_predicate @pool, :active_connection?
<ide> @pool.release_connection
<del> assert !@pool.active_connection?
<add> assert_not_predicate @pool, :active_connection?
<ide> end
<ide>
<ide> def test_checkout_behaviour
<ide> def test_disconnect_and_clear_reloadable_connections_attempt_to_wait_for_threads
<ide> assert_nil timed_join_result
<ide>
<ide> # assert that since this is within default timeout our connection hasn't been forcefully taken away from us
<del> assert @pool.active_connection?
<add> assert_predicate @pool, :active_connection?
<ide> end
<ide> ensure
<ide> thread.join if thread && !timed_join_result # clean up the other thread
<ide> def test_bang_versions_of_disconnect_and_clear_reloadable_connections_if_unable_
<ide> @pool.with_connection do |connection|
<ide> Thread.new { @pool.send(group_action_method) }.join
<ide> # assert connection has been forcefully taken away from us
<del> assert_not @pool.active_connection?
<add> assert_not_predicate @pool, :active_connection?
<ide>
<ide> # make a new connection for with_connection to clean up
<ide> @pool.connection
<ide><path>activerecord/test/cases/dirty_test.rb
<ide> def test_attribute_changes
<ide>
<ide> # Change catchphrase.
<ide> pirate.catchphrase = "arrr"
<del> assert pirate.catchphrase_changed?
<add> assert_predicate pirate, :catchphrase_changed?
<ide> assert_nil pirate.catchphrase_was
<ide> assert_equal [nil, "arrr"], pirate.catchphrase_change
<ide>
<ide> # Saved - no changes.
<ide> pirate.save!
<del> assert !pirate.catchphrase_changed?
<add> assert_not_predicate pirate, :catchphrase_changed?
<ide> assert_nil pirate.catchphrase_change
<ide>
<ide> # Same value - no changes.
<ide> pirate.catchphrase = "arrr"
<del> assert !pirate.catchphrase_changed?
<add> assert_not_predicate pirate, :catchphrase_changed?
<ide> assert_nil pirate.catchphrase_change
<ide> end
<ide>
<ide> def test_time_attributes_changes_with_time_zone
<ide>
<ide> # New record - no changes.
<ide> pirate = target.new
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> assert_nil pirate.created_on_change
<ide>
<ide> # Saved - no changes.
<ide> pirate.catchphrase = "arrrr, time zone!!"
<ide> pirate.save!
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> assert_nil pirate.created_on_change
<ide>
<ide> # Change created_on.
<ide> old_created_on = pirate.created_on
<ide> pirate.created_on = Time.now - 1.day
<del> assert pirate.created_on_changed?
<add> assert_predicate pirate, :created_on_changed?
<ide> assert_kind_of ActiveSupport::TimeWithZone, pirate.created_on_was
<ide> assert_equal old_created_on, pirate.created_on_was
<ide> pirate.created_on = old_created_on
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> end
<ide> end
<ide>
<ide> def test_setting_time_attributes_with_time_zone_field_to_itself_should_not_be_ma
<ide>
<ide> pirate = target.create!
<ide> pirate.created_on = pirate.created_on
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> end
<ide> end
<ide>
<ide> def test_time_attributes_changes_without_time_zone_by_skip
<ide>
<ide> # New record - no changes.
<ide> pirate = target.new
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> assert_nil pirate.created_on_change
<ide>
<ide> # Saved - no changes.
<ide> pirate.catchphrase = "arrrr, time zone!!"
<ide> pirate.save!
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> assert_nil pirate.created_on_change
<ide>
<ide> # Change created_on.
<ide> old_created_on = pirate.created_on
<ide> pirate.created_on = Time.now + 1.day
<del> assert pirate.created_on_changed?
<add> assert_predicate pirate, :created_on_changed?
<ide> # kind_of does not work because
<ide> # ActiveSupport::TimeWithZone.name == 'Time'
<ide> assert_instance_of Time, pirate.created_on_was
<ide> def test_time_attributes_changes_without_time_zone
<ide>
<ide> # New record - no changes.
<ide> pirate = target.new
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> assert_nil pirate.created_on_change
<ide>
<ide> # Saved - no changes.
<ide> pirate.catchphrase = "arrrr, time zone!!"
<ide> pirate.save!
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> assert_nil pirate.created_on_change
<ide>
<ide> # Change created_on.
<ide> old_created_on = pirate.created_on
<ide> pirate.created_on = Time.now + 1.day
<del> assert pirate.created_on_changed?
<add> assert_predicate pirate, :created_on_changed?
<ide> # kind_of does not work because
<ide> # ActiveSupport::TimeWithZone.name == 'Time'
<ide> assert_instance_of Time, pirate.created_on_was
<ide> def test_aliased_attribute_changes
<ide> # the actual attribute here is name, title is an
<ide> # alias setup via alias_attribute
<ide> parrot = Parrot.new
<del> assert !parrot.title_changed?
<add> assert_not_predicate parrot, :title_changed?
<ide> assert_nil parrot.title_change
<ide>
<ide> parrot.name = "Sam"
<del> assert parrot.title_changed?
<add> assert_predicate parrot, :title_changed?
<ide> assert_nil parrot.title_was
<ide> assert_equal parrot.name_change, parrot.title_change
<ide> end
<ide> def test_restore_attribute!
<ide> pirate.restore_catchphrase!
<ide> assert_equal "Yar!", pirate.catchphrase
<ide> assert_equal Hash.new, pirate.changes
<del> assert !pirate.catchphrase_changed?
<add> assert_not_predicate pirate, :catchphrase_changed?
<ide> end
<ide>
<ide> def test_nullable_number_not_marked_as_changed_if_new_value_is_blank
<ide> pirate = Pirate.new
<ide>
<ide> ["", nil].each do |value|
<ide> pirate.parrot_id = value
<del> assert !pirate.parrot_id_changed?
<add> assert_not_predicate pirate, :parrot_id_changed?
<ide> assert_nil pirate.parrot_id_change
<ide> end
<ide> end
<ide> def test_nullable_decimal_not_marked_as_changed_if_new_value_is_blank
<ide>
<ide> ["", nil].each do |value|
<ide> numeric_data.bank_balance = value
<del> assert !numeric_data.bank_balance_changed?
<add> assert_not_predicate numeric_data, :bank_balance_changed?
<ide> assert_nil numeric_data.bank_balance_change
<ide> end
<ide> end
<ide> def test_nullable_float_not_marked_as_changed_if_new_value_is_blank
<ide>
<ide> ["", nil].each do |value|
<ide> numeric_data.temperature = value
<del> assert !numeric_data.temperature_changed?
<add> assert_not_predicate numeric_data, :temperature_changed?
<ide> assert_nil numeric_data.temperature_change
<ide> end
<ide> end
<ide> def test_nullable_datetime_not_marked_as_changed_if_new_value_is_blank
<ide> ["", nil].each do |value|
<ide> topic.written_on = value
<ide> assert_nil topic.written_on
<del> assert !topic.written_on_changed?
<add> assert_not_predicate topic, :written_on_changed?
<ide> end
<ide> end
<ide> end
<ide> def test_integer_zero_to_string_zero_not_marked_as_changed
<ide> pirate.catchphrase = "arrr"
<ide> assert pirate.save!
<ide>
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide>
<ide> pirate.parrot_id = "0"
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide> end
<ide>
<ide> def test_integer_zero_to_integer_zero_not_marked_as_changed
<ide> def test_integer_zero_to_integer_zero_not_marked_as_changed
<ide> pirate.catchphrase = "arrr"
<ide> assert pirate.save!
<ide>
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide>
<ide> pirate.parrot_id = 0
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide> end
<ide>
<ide> def test_float_zero_to_string_zero_not_marked_as_changed
<ide> data = NumericData.new temperature: 0.0
<ide> data.save!
<ide>
<del> assert_not data.changed?
<add> assert_not_predicate data, :changed?
<ide>
<ide> data.temperature = "0"
<ide> assert_empty data.changes
<ide> def test_zero_to_blank_marked_as_changed
<ide> # check the change from 1 to ''
<ide> pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
<ide> pirate.parrot_id = ""
<del> assert pirate.parrot_id_changed?
<add> assert_predicate pirate, :parrot_id_changed?
<ide> assert_equal([1, nil], pirate.parrot_id_change)
<ide> pirate.save
<ide>
<ide> # check the change from nil to 0
<ide> pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
<ide> pirate.parrot_id = 0
<del> assert pirate.parrot_id_changed?
<add> assert_predicate pirate, :parrot_id_changed?
<ide> assert_equal([nil, 0], pirate.parrot_id_change)
<ide> pirate.save
<ide>
<ide> # check the change from 0 to ''
<ide> pirate = Pirate.find_by_catchphrase("Yarrrr, me hearties")
<ide> pirate.parrot_id = ""
<del> assert pirate.parrot_id_changed?
<add> assert_predicate pirate, :parrot_id_changed?
<ide> assert_equal([0, nil], pirate.parrot_id_change)
<ide> end
<ide>
<ide> def test_object_should_be_changed_if_any_attribute_is_changed
<ide> pirate = Pirate.new
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide> assert_equal [], pirate.changed
<ide> assert_equal Hash.new, pirate.changes
<ide>
<ide> pirate.catchphrase = "arrr"
<del> assert pirate.changed?
<add> assert_predicate pirate, :changed?
<ide> assert_nil pirate.catchphrase_was
<ide> assert_equal %w(catchphrase), pirate.changed
<ide> assert_equal({ "catchphrase" => [nil, "arrr"] }, pirate.changes)
<ide>
<ide> pirate.save
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide> assert_equal [], pirate.changed
<ide> assert_equal Hash.new, pirate.changes
<ide> end
<ide>
<ide> def test_attribute_will_change!
<ide> pirate = Pirate.create!(catchphrase: "arr")
<ide>
<del> assert !pirate.catchphrase_changed?
<add> assert_not_predicate pirate, :catchphrase_changed?
<ide> assert pirate.catchphrase_will_change!
<del> assert pirate.catchphrase_changed?
<add> assert_predicate pirate, :catchphrase_changed?
<ide> assert_equal ["arr", "arr"], pirate.catchphrase_change
<ide>
<ide> pirate.catchphrase << " matey!"
<del> assert pirate.catchphrase_changed?
<add> assert_predicate pirate, :catchphrase_changed?
<ide> assert_equal ["arr", "arr matey!"], pirate.catchphrase_change
<ide> end
<ide>
<ide> def test_virtual_attribute_will_change
<ide> parrot = Parrot.create!(name: "Ruby")
<ide> parrot.send(:attribute_will_change!, :cancel_save_from_callback)
<del> assert parrot.has_changes_to_save?
<add> assert_predicate parrot, :has_changes_to_save?
<ide> end
<ide>
<ide> def test_association_assignment_changes_foreign_key
<ide> pirate = Pirate.create!(catchphrase: "jarl")
<ide> pirate.parrot = Parrot.create!(name: "Lorre")
<del> assert pirate.changed?
<add> assert_predicate pirate, :changed?
<ide> assert_equal %w(parrot_id), pirate.changed
<ide> end
<ide>
<ide> def test_attribute_should_be_compared_with_type_cast
<ide> topic = Topic.new
<del> assert topic.approved?
<del> assert !topic.approved_changed?
<add> assert_predicate topic, :approved?
<add> assert_not_predicate topic, :approved_changed?
<ide>
<ide> # Coming from web form.
<ide> params = { topic: { approved: 1 } }
<ide> # In the controller.
<ide> topic.attributes = params[:topic]
<del> assert topic.approved?
<del> assert !topic.approved_changed?
<add> assert_predicate topic, :approved?
<add> assert_not_predicate topic, :approved_changed?
<ide> end
<ide>
<ide> def test_partial_update
<ide> def test_changed_attributes_should_be_preserved_if_save_failure
<ide> def test_reload_should_clear_changed_attributes
<ide> pirate = Pirate.create!(catchphrase: "shiver me timbers")
<ide> pirate.catchphrase = "*hic*"
<del> assert pirate.changed?
<add> assert_predicate pirate, :changed?
<ide> pirate.reload
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide> end
<ide>
<ide> def test_dup_objects_should_not_copy_dirty_flag_from_creator
<ide> pirate = Pirate.create!(catchphrase: "shiver me timbers")
<ide> pirate_dup = pirate.dup
<ide> pirate_dup.restore_catchphrase!
<ide> pirate.catchphrase = "I love Rum"
<del> assert pirate.catchphrase_changed?
<del> assert !pirate_dup.catchphrase_changed?
<add> assert_predicate pirate, :catchphrase_changed?
<add> assert_not_predicate pirate_dup, :catchphrase_changed?
<ide> end
<ide>
<ide> def test_reverted_changes_are_not_dirty
<ide> phrase = "shiver me timbers"
<ide> pirate = Pirate.create!(catchphrase: phrase)
<ide> pirate.catchphrase = "*hic*"
<del> assert pirate.changed?
<add> assert_predicate pirate, :changed?
<ide> pirate.catchphrase = phrase
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide> end
<ide>
<ide> def test_reverted_changes_are_not_dirty_after_multiple_changes
<ide> phrase = "shiver me timbers"
<ide> pirate = Pirate.create!(catchphrase: phrase)
<ide> 10.times do |i|
<ide> pirate.catchphrase = "*hic*" * i
<del> assert pirate.changed?
<add> assert_predicate pirate, :changed?
<ide> end
<del> assert pirate.changed?
<add> assert_predicate pirate, :changed?
<ide> pirate.catchphrase = phrase
<del> assert !pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide> end
<ide>
<ide> def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back
<ide> pirate = Pirate.create!(catchphrase: "Yar!")
<ide>
<ide> pirate.parrot_id = 1
<del> assert pirate.changed?
<del> assert pirate.parrot_id_changed?
<del> assert !pirate.catchphrase_changed?
<add> assert_predicate pirate, :changed?
<add> assert_predicate pirate, :parrot_id_changed?
<add> assert_not_predicate pirate, :catchphrase_changed?
<ide>
<ide> pirate.parrot_id = nil
<del> assert !pirate.changed?
<del> assert !pirate.parrot_id_changed?
<del> assert !pirate.catchphrase_changed?
<add> assert_not_predicate pirate, :changed?
<add> assert_not_predicate pirate, :parrot_id_changed?
<add> assert_not_predicate pirate, :catchphrase_changed?
<ide> end
<ide>
<ide> def test_save_should_store_serialized_attributes_even_with_partial_writes
<ide> with_partial_writes(Topic) do
<ide> topic = Topic.create!(content: { a: "a" })
<ide>
<del> assert_not topic.changed?
<add> assert_not_predicate topic, :changed?
<ide>
<ide> topic.content[:b] = "b"
<ide>
<del> assert topic.changed?
<add> assert_predicate topic, :changed?
<ide>
<ide> topic.save!
<ide>
<del> assert_not topic.changed?
<add> assert_not_predicate topic, :changed?
<ide> assert_equal "b", topic.content[:b]
<ide>
<ide> topic.reload
<ide> def test_datetime_attribute_doesnt_change_if_zone_is_modified_in_string
<ide> pirate = Pirate.create!(catchphrase: "rrrr", created_on: time_in_paris)
<ide>
<ide> pirate.created_on = pirate.created_on.in_time_zone("Tokyo").to_s
<del> assert !pirate.created_on_changed?
<add> assert_not_predicate pirate, :created_on_changed?
<ide> end
<ide>
<ide> test "partial insert" do
<ide> def test_datetime_attribute_doesnt_change_if_zone_is_modified_in_string
<ide> pirate = Pirate.create!(catchphrase: "arrrr")
<ide> pirate.catchphrase << " matey!"
<ide>
<del> assert pirate.catchphrase_changed?
<add> assert_predicate pirate, :catchphrase_changed?
<ide> expected_changes = {
<ide> "catchphrase" => ["arrrr", "arrrr matey!"]
<ide> }
<ide> def test_datetime_attribute_doesnt_change_if_zone_is_modified_in_string
<ide> pirate.reload
<ide>
<ide> assert_equal "arrrr matey!", pirate.catchphrase
<del> assert_not pirate.changed?
<add> assert_not_predicate pirate, :changed?
<ide> end
<ide>
<ide> test "in place mutation for binary" do
<ide> def test_datetime_attribute_doesnt_change_if_zone_is_modified_in_string
<ide>
<ide> binary = klass.create!(data: "\\\\foo")
<ide>
<del> assert_not binary.changed?
<add> assert_not_predicate binary, :changed?
<ide>
<ide> binary.data = binary.data.dup
<ide>
<del> assert_not binary.changed?
<add> assert_not_predicate binary, :changed?
<ide>
<ide> binary = klass.last
<ide>
<del> assert_not binary.changed?
<add> assert_not_predicate binary, :changed?
<ide>
<ide> binary.data << "bar"
<ide>
<del> assert binary.changed?
<add> assert_predicate binary, :changed?
<ide> end
<ide>
<ide> test "changes is correct for subclass" do
<ide> def catchphrase
<ide> new_catchphrase = "arrrr matey!"
<ide>
<ide> pirate.catchphrase = new_catchphrase
<del> assert pirate.catchphrase_changed?
<add> assert_predicate pirate, :catchphrase_changed?
<ide>
<ide> expected_changes = {
<ide> "catchphrase" => ["arrrr", new_catchphrase]
<ide> def pirate.catchphrase
<ide> new_catchphrase = "arrrr matey!"
<ide>
<ide> pirate.catchphrase = new_catchphrase
<del> assert pirate.catchphrase_changed?
<add> assert_predicate pirate, :catchphrase_changed?
<ide>
<ide> expected_changes = {
<ide> "catchphrase" => ["arrrr", new_catchphrase]
<ide> def pirate.catchphrase
<ide> end
<ide>
<ide> model = klass.new(first_name: "Jim")
<del> assert model.first_name_changed?
<add> assert_predicate model, :first_name_changed?
<ide> end
<ide>
<ide> test "attribute_will_change! doesn't try to save non-persistable attributes" do
<ide> def pirate.catchphrase
<ide> record = klass.new(first_name: "Sean")
<ide> record.non_persisted_attribute_will_change!
<ide>
<del> assert record.non_persisted_attribute_changed?
<add> assert_predicate record, :non_persisted_attribute_changed?
<ide> assert record.save
<ide> end
<ide>
<ide> def catchphrase
<ide>
<ide> test "attributes assigned but not selected are dirty" do
<ide> person = Person.select(:id).first
<del> assert_not person.changed?
<add> assert_not_predicate person, :changed?
<ide>
<ide> person.first_name = "Sean"
<del> assert person.changed?
<add> assert_predicate person, :changed?
<ide>
<ide> person.first_name = nil
<del> assert person.changed?
<add> assert_predicate person, :changed?
<ide> end
<ide>
<ide> test "attributes not selected are still missing after save" do
<ide> def catchphrase
<ide> test "saved_change_to_attribute? returns whether a change occurred in the last save" do
<ide> person = Person.create!(first_name: "Sean")
<ide>
<del> assert person.saved_change_to_first_name?
<del> assert_not person.saved_change_to_gender?
<add> assert_predicate person, :saved_change_to_first_name?
<add> assert_not_predicate person, :saved_change_to_gender?
<ide> assert person.saved_change_to_first_name?(from: nil, to: "Sean")
<ide> assert person.saved_change_to_first_name?(from: nil)
<ide> assert person.saved_change_to_first_name?(to: "Sean")
<ide> def catchphrase
<ide> test "saved_changes? returns whether the last call to save changed anything" do
<ide> person = Person.create!(first_name: "Sean")
<ide>
<del> assert person.saved_changes?
<add> assert_predicate person, :saved_changes?
<ide>
<ide> person.save
<ide>
<del> assert_not person.saved_changes?
<add> assert_not_predicate person, :saved_changes?
<ide> end
<ide>
<ide> test "saved_changes returns a hash of all the changes that occurred" do
<ide> def catchphrase
<ide> end
<ide>
<ide> person = klass.create!(first_name: "Sean")
<del> assert_not person.changed?
<add> assert_not_predicate person, :changed?
<ide> end
<ide>
<ide> private
<ide> def with_partial_writes(klass, on = true)
<ide> end
<ide>
<ide> def check_pirate_after_save_failure(pirate)
<del> assert pirate.changed?
<del> assert pirate.parrot_id_changed?
<add> assert_predicate pirate, :changed?
<add> assert_predicate pirate, :parrot_id_changed?
<ide> assert_equal %w(parrot_id), pirate.changed
<ide> assert_nil pirate.parrot_id_was
<ide> end
<ide><path>activerecord/test/cases/dup_test.rb
<ide> class DupTest < ActiveRecord::TestCase
<ide> fixtures :topics
<ide>
<ide> def test_dup
<del> assert !Topic.new.freeze.dup.frozen?
<add> assert_not_predicate Topic.new.freeze.dup, :frozen?
<ide> end
<ide>
<ide> def test_not_readonly
<ide> def test_dup_not_destroyed
<ide> topic.destroy
<ide>
<ide> duped = topic.dup
<del> assert_not duped.destroyed?
<add> assert_not_predicate duped, :destroyed?
<ide> end
<ide>
<ide> def test_dup_has_no_id
<ide> def test_dup_validity_is_independent
<ide>
<ide> duped = topic.dup
<ide> duped.title = nil
<del> assert duped.invalid?
<add> assert_predicate duped, :invalid?
<ide>
<ide> topic.title = nil
<ide> duped.title = "Mathematics"
<del> assert topic.invalid?
<del> assert duped.valid?
<add> assert_predicate topic, :invalid?
<add> assert_predicate duped, :valid?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/enum_test.rb
<ide> class EnumTest < ActiveRecord::TestCase
<ide> end
<ide>
<ide> test "query state by predicate" do
<del> assert @book.published?
<del> assert_not @book.written?
<del> assert_not @book.proposed?
<add> assert_predicate @book, :published?
<add> assert_not_predicate @book, :written?
<add> assert_not_predicate @book, :proposed?
<ide>
<del> assert @book.read?
<del> assert @book.in_english?
<del> assert @book.author_visibility_visible?
<del> assert @book.illustrator_visibility_visible?
<del> assert @book.with_medium_font_size?
<del> assert @book.medium_to_read?
<add> assert_predicate @book, :read?
<add> assert_predicate @book, :in_english?
<add> assert_predicate @book, :author_visibility_visible?
<add> assert_predicate @book, :illustrator_visibility_visible?
<add> assert_predicate @book, :with_medium_font_size?
<add> assert_predicate @book, :medium_to_read?
<ide> end
<ide>
<ide> test "query state with strings" do
<ide> class EnumTest < ActiveRecord::TestCase
<ide> end
<ide>
<ide> test "build from scope" do
<del> assert Book.written.build.written?
<del> assert_not Book.written.build.proposed?
<add> assert_predicate Book.written.build, :written?
<add> assert_not_predicate Book.written.build, :proposed?
<ide> end
<ide>
<ide> test "build from where" do
<del> assert Book.where(status: Book.statuses[:written]).build.written?
<del> assert_not Book.where(status: Book.statuses[:written]).build.proposed?
<del> assert Book.where(status: :written).build.written?
<del> assert_not Book.where(status: :written).build.proposed?
<del> assert Book.where(status: "written").build.written?
<del> assert_not Book.where(status: "written").build.proposed?
<add> assert_predicate Book.where(status: Book.statuses[:written]).build, :written?
<add> assert_not_predicate Book.where(status: Book.statuses[:written]).build, :proposed?
<add> assert_predicate Book.where(status: :written).build, :written?
<add> assert_not_predicate Book.where(status: :written).build, :proposed?
<add> assert_predicate Book.where(status: "written").build, :written?
<add> assert_not_predicate Book.where(status: "written").build, :proposed?
<ide> end
<ide>
<ide> test "update by declaration" do
<ide> @book.written!
<del> assert @book.written?
<add> assert_predicate @book, :written?
<ide> @book.in_english!
<del> assert @book.in_english?
<add> assert_predicate @book, :in_english?
<ide> @book.author_visibility_visible!
<del> assert @book.author_visibility_visible?
<add> assert_predicate @book, :author_visibility_visible?
<ide> end
<ide>
<ide> test "update by setter" do
<ide> @book.update! status: :written
<del> assert @book.written?
<add> assert_predicate @book, :written?
<ide> end
<ide>
<ide> test "enum methods are overwritable" do
<ide> assert_equal "do publish work...", @book.published!
<del> assert @book.published?
<add> assert_predicate @book, :published?
<ide> end
<ide>
<ide> test "direct assignment" do
<ide> @book.status = :written
<del> assert @book.written?
<add> assert_predicate @book, :written?
<ide> end
<ide>
<ide> test "assign string value" do
<ide> @book.status = "written"
<del> assert @book.written?
<add> assert_predicate @book, :written?
<ide> end
<ide>
<ide> test "enum changed attributes" do
<ide> class EnumTest < ActiveRecord::TestCase
<ide> end
<ide>
<ide> test "building new objects with enum scopes" do
<del> assert Book.written.build.written?
<del> assert Book.read.build.read?
<del> assert Book.in_spanish.build.in_spanish?
<del> assert Book.illustrator_visibility_invisible.build.illustrator_visibility_invisible?
<add> assert_predicate Book.written.build, :written?
<add> assert_predicate Book.read.build, :read?
<add> assert_predicate Book.in_spanish.build, :in_spanish?
<add> assert_predicate Book.illustrator_visibility_invisible.build, :illustrator_visibility_invisible?
<ide> end
<ide>
<ide> test "creating new objects with enum scopes" do
<del> assert Book.written.create.written?
<del> assert Book.read.create.read?
<del> assert Book.in_spanish.create.in_spanish?
<del> assert Book.illustrator_visibility_invisible.create.illustrator_visibility_invisible?
<add> assert_predicate Book.written.create, :written?
<add> assert_predicate Book.read.create, :read?
<add> assert_predicate Book.in_spanish.create, :in_spanish?
<add> assert_predicate Book.illustrator_visibility_invisible.create, :illustrator_visibility_invisible?
<ide> end
<ide>
<ide> test "_before_type_cast" do
<ide> def self.name; "Book"; end
<ide> klass.delete_all
<ide> klass.create!(status: "proposed")
<ide> book = klass.new(status: "written")
<del> assert book.valid?
<add> assert_predicate book, :valid?
<ide> book.status = "proposed"
<del> assert_not book.valid?
<add> assert_not_predicate book, :valid?
<ide> end
<ide>
<ide> test "validate inclusion of value in array" do
<ide> def self.name; "Book"; end
<ide> end
<ide> klass.delete_all
<ide> invalid_book = klass.new(status: "proposed")
<del> assert_not invalid_book.valid?
<add> assert_not_predicate invalid_book, :valid?
<ide> valid_book = klass.new(status: "written")
<del> assert valid_book.valid?
<add> assert_predicate valid_book, :valid?
<ide> end
<ide>
<ide> test "enums are distinct per class" do
<ide> def self.name; "Book"; end
<ide> end
<ide>
<ide> book1 = klass.proposed.create!
<del> assert book1.proposed?
<add> assert_predicate book1, :proposed?
<ide>
<ide> book2 = klass.single.create!
<del> assert book2.single?
<add> assert_predicate book2, :single?
<ide> end
<ide>
<ide> test "enum with alias_attribute" do
<ide> def self.name; "Book"; end
<ide> end
<ide>
<ide> book = klass.proposed.create!
<del> assert book.proposed?
<add> assert_predicate book, :proposed?
<ide> assert_equal "proposed", book.aliased_status
<ide>
<ide> book = klass.find(book.id)
<del> assert book.proposed?
<add> assert_predicate book, :proposed?
<ide> assert_equal "proposed", book.aliased_status
<ide> end
<ide>
<ide> test "query state by predicate with prefix" do
<del> assert @book.author_visibility_visible?
<del> assert_not @book.author_visibility_invisible?
<del> assert @book.illustrator_visibility_visible?
<del> assert_not @book.illustrator_visibility_invisible?
<add> assert_predicate @book, :author_visibility_visible?
<add> assert_not_predicate @book, :author_visibility_invisible?
<add> assert_predicate @book, :illustrator_visibility_visible?
<add> assert_not_predicate @book, :illustrator_visibility_invisible?
<ide> end
<ide>
<ide> test "query state by predicate with custom prefix" do
<del> assert @book.in_english?
<del> assert_not @book.in_spanish?
<del> assert_not @book.in_french?
<add> assert_predicate @book, :in_english?
<add> assert_not_predicate @book, :in_spanish?
<add> assert_not_predicate @book, :in_french?
<ide> end
<ide>
<ide> test "query state by predicate with custom suffix" do
<del> assert @book.medium_to_read?
<del> assert_not @book.easy_to_read?
<del> assert_not @book.hard_to_read?
<add> assert_predicate @book, :medium_to_read?
<add> assert_not_predicate @book, :easy_to_read?
<add> assert_not_predicate @book, :hard_to_read?
<ide> end
<ide>
<ide> test "enum methods with custom suffix defined" do
<ide> def self.name; "Book"; end
<ide>
<ide> test "update enum attributes with custom suffix" do
<ide> @book.medium_to_read!
<del> assert_not @book.easy_to_read?
<del> assert @book.medium_to_read?
<del> assert_not @book.hard_to_read?
<add> assert_not_predicate @book, :easy_to_read?
<add> assert_predicate @book, :medium_to_read?
<add> assert_not_predicate @book, :hard_to_read?
<ide>
<ide> @book.easy_to_read!
<del> assert @book.easy_to_read?
<del> assert_not @book.medium_to_read?
<del> assert_not @book.hard_to_read?
<add> assert_predicate @book, :easy_to_read?
<add> assert_not_predicate @book, :medium_to_read?
<add> assert_not_predicate @book, :hard_to_read?
<ide>
<ide> @book.hard_to_read!
<del> assert_not @book.easy_to_read?
<del> assert_not @book.medium_to_read?
<del> assert @book.hard_to_read?
<add> assert_not_predicate @book, :easy_to_read?
<add> assert_not_predicate @book, :medium_to_read?
<add> assert_predicate @book, :hard_to_read?
<ide> end
<ide>
<ide> test "uses default status when no status is provided in fixtures" do
<ide> def self.name; "Book"; end
<ide>
<ide> test "uses default value from database on initialization" do
<ide> book = Book.new
<del> assert book.proposed?
<add> assert_predicate book, :proposed?
<ide> end
<ide>
<ide> test "uses default value from database on initialization when using custom mapping" do
<ide> book = Book.new
<del> assert book.hard?
<add> assert_predicate book, :hard?
<ide> end
<ide>
<ide> test "data type of Enum type" do
<ide><path>activerecord/test/cases/explain_subscriber_test.rb
<ide> def setup
<ide>
<ide> def test_collects_nothing_if_the_payload_has_an_exception
<ide> SUBSCRIBER.finish(nil, nil, exception: Exception.new)
<del> assert queries.empty?
<add> assert_predicate queries, :empty?
<ide> end
<ide>
<ide> def test_collects_nothing_for_ignored_payloads
<ide> ActiveRecord::ExplainSubscriber::IGNORED_PAYLOADS.each do |ip|
<ide> SUBSCRIBER.finish(nil, nil, name: ip)
<ide> end
<del> assert queries.empty?
<add> assert_predicate queries, :empty?
<ide> end
<ide>
<ide> def test_collects_nothing_if_collect_is_false
<ide> ActiveRecord::ExplainRegistry.collect = false
<ide> SUBSCRIBER.finish(nil, nil, name: "SQL", sql: "select 1 from users", binds: [1, 2])
<del> assert queries.empty?
<add> assert_predicate queries, :empty?
<ide> end
<ide>
<ide> def test_collects_pairs_of_queries_and_binds
<ide> def test_collects_pairs_of_queries_and_binds
<ide>
<ide> def test_collects_nothing_if_the_statement_is_not_whitelisted
<ide> SUBSCRIBER.finish(nil, nil, name: "SQL", sql: "SHOW max_identifier_length")
<del> assert queries.empty?
<add> assert_predicate queries, :empty?
<ide> end
<ide>
<ide> def test_collects_nothing_if_the_statement_is_only_partially_matched
<ide> SUBSCRIBER.finish(nil, nil, name: "SQL", sql: "select_db yo_mama")
<del> assert queries.empty?
<add> assert_predicate queries, :empty?
<ide> end
<ide>
<ide> def test_collects_cte_queries
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_last_with_integer_and_order_should_keep_the_order
<ide> def test_last_with_integer_and_order_should_use_sql_limit
<ide> relation = Topic.order("title")
<ide> assert_queries(1) { relation.last(5) }
<del> assert !relation.loaded?
<add> assert_not_predicate relation, :loaded?
<ide> end
<ide>
<ide> def test_last_with_integer_and_reorder_should_use_sql_limit
<ide> relation = Topic.reorder("title")
<ide> assert_queries(1) { relation.last(5) }
<del> assert !relation.loaded?
<add> assert_not_predicate relation, :loaded?
<ide> end
<ide>
<ide> def test_last_on_loaded_relation_should_not_use_sql
<ide><path>activerecord/test/cases/fixtures_test.rb
<ide> def test_nonexistent_fixture_file
<ide> nonexistent_fixture_path = FIXTURES_ROOT + "/imnothere"
<ide>
<ide> # sanity check to make sure that this file never exists
<del> assert Dir[nonexistent_fixture_path + "*"].empty?
<add> assert_predicate Dir[nonexistent_fixture_path + "*"], :empty?
<ide>
<ide> assert_raise(Errno::ENOENT) do
<ide> ActiveRecord::FixtureSet.new(Account.connection, "companies", Company, nonexistent_fixture_path)
<ide> def test_namespaced_models
<ide> end
<ide>
<ide> def test_resolves_enums
<del> assert books(:awdr).published?
<del> assert books(:awdr).read?
<del> assert books(:rfr).proposed?
<del> assert books(:ddd).published?
<add> assert_predicate books(:awdr), :published?
<add> assert_predicate books(:awdr), :read?
<add> assert_predicate books(:rfr), :proposed?
<add> assert_predicate books(:ddd), :published?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/habtm_destroy_order_test.rb
<ide> class HabtmDestroyOrderTest < ActiveRecord::TestCase
<ide> sicp.destroy
<ide> end
<ide> end
<del> assert !sicp.destroyed?
<add> assert_not_predicate sicp, :destroyed?
<ide> end
<ide>
<ide> test "should not raise error if have foreign key in the join table" do
<ide> class HabtmDestroyOrderTest < ActiveRecord::TestCase
<ide> ben.lessons << sicp
<ide> ben.save!
<ide> ben.destroy
<del> assert !ben.reload.lessons.empty?
<add> assert_not_predicate ben.reload.lessons, :empty?
<ide> ensure
<ide> # get rid of it so Student is still like it was
<ide> Student.reset_callbacks(:destroy)
<ide> class HabtmDestroyOrderTest < ActiveRecord::TestCase
<ide> assert_raises LessonError do
<ide> sicp.destroy
<ide> end
<del> assert !sicp.reload.students.empty?
<add> assert_not_predicate sicp.reload.students, :empty?
<ide> end
<ide> end
<ide><path>activerecord/test/cases/inheritance_test.rb
<ide> def test_different_namespace_subclass_should_load_correctly_with_store_full_sti_
<ide> end
<ide>
<ide> def test_descends_from_active_record
<del> assert !ActiveRecord::Base.descends_from_active_record?
<add> assert_not_predicate ActiveRecord::Base, :descends_from_active_record?
<ide>
<ide> # Abstract subclass of AR::Base.
<del> assert LoosePerson.descends_from_active_record?
<add> assert_predicate LoosePerson, :descends_from_active_record?
<ide>
<ide> # Concrete subclass of an abstract class.
<del> assert LooseDescendant.descends_from_active_record?
<add> assert_predicate LooseDescendant, :descends_from_active_record?
<ide>
<ide> # Concrete subclass of AR::Base.
<del> assert TightPerson.descends_from_active_record?
<add> assert_predicate TightPerson, :descends_from_active_record?
<ide>
<ide> # Concrete subclass of a concrete class but has no type column.
<del> assert TightDescendant.descends_from_active_record?
<add> assert_predicate TightDescendant, :descends_from_active_record?
<ide>
<ide> # Concrete subclass of AR::Base.
<del> assert Post.descends_from_active_record?
<add> assert_predicate Post, :descends_from_active_record?
<ide>
<ide> # Concrete subclasses of a concrete class which has a type column.
<del> assert !StiPost.descends_from_active_record?
<del> assert !SubStiPost.descends_from_active_record?
<add> assert_not_predicate StiPost, :descends_from_active_record?
<add> assert_not_predicate SubStiPost, :descends_from_active_record?
<ide>
<ide> # Abstract subclass of a concrete class which has a type column.
<ide> # This is pathological, as you'll never have Sub < Abstract < Concrete.
<del> assert !AbstractStiPost.descends_from_active_record?
<add> assert_not_predicate AbstractStiPost, :descends_from_active_record?
<ide>
<ide> # Concrete subclass of an abstract class which has a type column.
<del> assert !SubAbstractStiPost.descends_from_active_record?
<add> assert_not_predicate SubAbstractStiPost, :descends_from_active_record?
<ide> end
<ide>
<ide> def test_company_descends_from_active_record
<del> assert !ActiveRecord::Base.descends_from_active_record?
<add> assert_not_predicate ActiveRecord::Base, :descends_from_active_record?
<ide> assert AbstractCompany.descends_from_active_record?, "AbstractCompany should descend from ActiveRecord::Base"
<ide> assert Company.descends_from_active_record?, "Company should descend from ActiveRecord::Base"
<ide> assert !Class.new(Company).descends_from_active_record?, "Company subclass should not descend from ActiveRecord::Base"
<ide> end
<ide>
<ide> def test_abstract_class
<del> assert !ActiveRecord::Base.abstract_class?
<del> assert LoosePerson.abstract_class?
<del> assert !LooseDescendant.abstract_class?
<add> assert_not_predicate ActiveRecord::Base, :abstract_class?
<add> assert_predicate LoosePerson, :abstract_class?
<add> assert_not_predicate LooseDescendant, :abstract_class?
<ide> end
<ide>
<ide> def test_inheritance_base_class
<ide><path>activerecord/test/cases/json_shared_test_cases.rb
<ide> def test_column
<ide> assert_type_match column_type, column.sql_type
<ide>
<ide> type = klass.type_for_attribute("payload")
<del> assert_not type.binary?
<add> assert_not_predicate type, :binary?
<ide> end
<ide>
<ide> def test_change_table_supports_json
<ide> def test_yaml_round_trip_with_store_accessors
<ide>
<ide> def test_changes_in_place
<ide> json = klass.new
<del> assert_not json.changed?
<add> assert_not_predicate json, :changed?
<ide>
<ide> json.payload = { "one" => "two" }
<del> assert json.changed?
<del> assert json.payload_changed?
<add> assert_predicate json, :changed?
<add> assert_predicate json, :payload_changed?
<ide>
<ide> json.save!
<del> assert_not json.changed?
<add> assert_not_predicate json, :changed?
<ide>
<ide> json.payload["three"] = "four"
<del> assert json.payload_changed?
<add> assert_predicate json, :payload_changed?
<ide>
<ide> json.save!
<ide> json.reload
<ide>
<ide> assert_equal({ "one" => "two", "three" => "four" }, json.payload)
<del> assert_not json.changed?
<add> assert_not_predicate json, :changed?
<ide> end
<ide>
<ide> def test_changes_in_place_ignores_key_order
<ide> json = klass.new
<del> assert_not json.changed?
<add> assert_not_predicate json, :changed?
<ide>
<ide> json.payload = { "three" => "four", "one" => "two" }
<ide> json.save!
<ide> json.reload
<ide>
<ide> json.payload = { "three" => "four", "one" => "two" }
<del> assert_not json.changed?
<add> assert_not_predicate json, :changed?
<ide>
<ide> json.payload = [{ "three" => "four", "one" => "two" }, { "seven" => "eight", "five" => "six" }]
<ide> json.save!
<ide> json.reload
<ide>
<ide> json.payload = [{ "three" => "four", "one" => "two" }, { "seven" => "eight", "five" => "six" }]
<del> assert_not json.changed?
<add> assert_not_predicate json, :changed?
<ide> end
<ide>
<ide> def test_changes_in_place_with_ruby_object
<ide> time = Time.now.utc
<ide> json = klass.create!(payload: time)
<ide>
<ide> json.reload
<del> assert_not json.changed?
<add> assert_not_predicate json, :changed?
<ide>
<ide> json.payload = time
<del> assert_not json.changed?
<add> assert_not_predicate json, :changed?
<ide> end
<ide>
<ide> def test_assigning_string_literal
<ide><path>activerecord/test/cases/locking_test.rb
<ide> def test_non_integer_lock_destroy
<ide> assert_raise(ActiveRecord::StaleObjectError) { s2.destroy }
<ide>
<ide> assert s1.destroy
<del> assert s1.frozen?
<del> assert s1.destroyed?
<add> assert_predicate s1, :frozen?
<add> assert_predicate s1, :destroyed?
<ide> assert_raises(ActiveRecord::RecordNotFound) { StringKeyObject.find("record1") }
<ide> end
<ide>
<ide> def test_lock_destroy
<ide> assert_raises(ActiveRecord::StaleObjectError) { p2.destroy }
<ide>
<ide> assert p1.destroy
<del> assert p1.frozen?
<del> assert p1.destroyed?
<add> assert_predicate p1, :frozen?
<add> assert_predicate p1, :destroyed?
<ide> assert_raises(ActiveRecord::RecordNotFound) { Person.find(1) }
<ide> end
<ide>
<ide> def test_explicit_update_lock_column_raise_error
<ide> person.first_name = "Douglas Adams"
<ide> person.lock_version = 42
<ide>
<del> assert person.lock_version_changed?
<add> assert_predicate person, :lock_version_changed?
<ide>
<ide> person.save
<ide> end
<ide> def test_polymorphic_destroy_with_dependencies_and_lock_version
<ide> assert_difference "car.wheels.count", -1 do
<ide> car.reload.destroy
<ide> end
<del> assert car.destroyed?
<add> assert_predicate car, :destroyed?
<ide> end
<ide>
<ide> def test_removing_has_and_belongs_to_many_associations_upon_destroy
<ide> p = RichPerson.create! first_name: "Jon"
<ide> p.treasures.create!
<del> assert !p.treasures.empty?
<add> assert_not_predicate p.treasures, :empty?
<ide> p.destroy
<del> assert p.treasures.empty?
<del> assert RichPerson.connection.select_all("SELECT * FROM peoples_treasures WHERE rich_person_id = 1").empty?
<add> assert_predicate p.treasures, :empty?
<add> assert_predicate RichPerson.connection.select_all("SELECT * FROM peoples_treasures WHERE rich_person_id = 1"), :empty?
<ide> end
<ide>
<ide> def test_yaml_dumping_with_lock_column
<ide> def test_destroy_existing_object_with_locking_column_value_null_in_the_database
<ide>
<ide> t1.destroy
<ide>
<del> assert t1.destroyed?
<add> assert_predicate t1, :destroyed?
<ide> end
<ide>
<ide> def test_destroy_stale_object
<ide> def test_destroy_stale_object
<ide> stale_object.destroy!
<ide> end
<ide>
<del> assert_not stale_object.destroyed?
<add> assert_not_predicate stale_object, :destroyed?
<ide> end
<ide>
<ide> private
<ide><path>activerecord/test/cases/migration/change_schema_test.rb
<ide> def test_add_column_with_array
<ide> columns = connection.columns(:testings)
<ide> array_column = columns.detect { |c| c.name == "foo" }
<ide>
<del> assert array_column.array?
<add> assert_predicate array_column, :array?
<ide> end
<ide>
<ide> def test_create_table_with_array_column
<ide> def test_create_table_with_array_column
<ide> columns = connection.columns(:testings)
<ide> array_column = columns.detect { |c| c.name == "foo" }
<ide>
<del> assert array_column.array?
<add> assert_predicate array_column, :array?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/migration/columns_test.rb
<ide> def test_rename_column_preserves_default_value_not_null
<ide> if current_adapter?(:Mysql2Adapter)
<ide> def test_mysql_rename_column_preserves_auto_increment
<ide> rename_column "test_models", "id", "id_test"
<del> assert connection.columns("test_models").find { |c| c.name == "id_test" }.auto_increment?
<add> assert_predicate connection.columns("test_models").find { |c| c.name == "id_test" }, :auto_increment?
<ide> TestModel.reset_column_information
<ide> ensure
<ide> rename_column "test_models", "id_test", "id"
<ide> def test_change_column
<ide>
<ide> def test_change_column_with_nil_default
<ide> add_column "test_models", "contributor", :boolean, default: true
<del> assert TestModel.new.contributor?
<add> assert_predicate TestModel.new, :contributor?
<ide>
<ide> change_column "test_models", "contributor", :boolean, default: nil
<ide> TestModel.reset_column_information
<del> assert_not TestModel.new.contributor?
<add> assert_not_predicate TestModel.new, :contributor?
<ide> assert_nil TestModel.new.contributor
<ide> end
<ide>
<ide> def test_change_column_to_drop_default_with_null_false
<ide> add_column "test_models", "contributor", :boolean, default: true, null: false
<del> assert TestModel.new.contributor?
<add> assert_predicate TestModel.new, :contributor?
<ide>
<ide> change_column "test_models", "contributor", :boolean, default: nil, null: false
<ide> TestModel.reset_column_information
<del> assert_not TestModel.new.contributor?
<add> assert_not_predicate TestModel.new, :contributor?
<ide> assert_nil TestModel.new.contributor
<ide> end
<ide>
<ide> def test_change_column_with_new_default
<ide> add_column "test_models", "administrator", :boolean, default: true
<del> assert TestModel.new.administrator?
<add> assert_predicate TestModel.new, :administrator?
<ide>
<ide> change_column "test_models", "administrator", :boolean, default: false
<ide> TestModel.reset_column_information
<del> assert_not TestModel.new.administrator?
<add> assert_not_predicate TestModel.new, :administrator?
<ide> end
<ide>
<ide> def test_change_column_with_custom_index_name
<ide><path>activerecord/test/cases/migration/compatibility_test.rb
<ide> def change
<ide> assert_legacy_primary_key
<ide>
<ide> legacy_ref = LegacyPrimaryKey.columns_hash["legacy_ref_id"]
<del> assert_not legacy_ref.bigint?
<add> assert_not_predicate legacy_ref, :bigint?
<ide>
<ide> record1 = LegacyPrimaryKey.create!
<ide> assert_not_nil record1.id
<ide> def change
<ide> @migration.migrate(:up)
<ide>
<ide> legacy_pk = LegacyPrimaryKey.columns_hash["id"]
<del> assert legacy_pk.bigint?
<del> assert legacy_pk.auto_increment?
<add> assert_predicate legacy_pk, :bigint?
<add> assert_predicate legacy_pk, :auto_increment?
<ide>
<ide> schema = dump_table_schema "legacy_primary_keys"
<ide> assert_match %r{create_table "legacy_primary_keys", (?!id: :bigint, default: nil)}, schema
<ide> def assert_legacy_primary_key
<ide> legacy_pk = LegacyPrimaryKey.columns_hash["id"]
<ide>
<ide> assert_equal :integer, legacy_pk.type
<del> assert_not legacy_pk.bigint?
<add> assert_not_predicate legacy_pk, :bigint?
<ide> assert_not legacy_pk.null
<ide>
<ide> if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
<ide><path>activerecord/test/cases/migration/create_join_table_test.rb
<ide> def test_create_join_table_with_column_options
<ide> def test_create_join_table_without_indexes
<ide> connection.create_join_table :artists, :musics
<ide>
<del> assert connection.indexes(:artists_musics).blank?
<add> assert_predicate connection.indexes(:artists_musics), :blank?
<ide> end
<ide>
<ide> def test_create_join_table_with_index
<ide><path>activerecord/test/cases/migration/foreign_key_test.rb
<ide> def test_add_invalid_foreign_key
<ide> assert_equal 1, foreign_keys.size
<ide>
<ide> fk = foreign_keys.first
<del> assert_not fk.validated?
<add> assert_not_predicate fk, :validated?
<ide> end
<ide>
<ide> def test_validate_foreign_key_infers_column
<ide> @connection.add_foreign_key :astronauts, :rockets, validate: false
<del> assert_not @connection.foreign_keys("astronauts").first.validated?
<add> assert_not_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide>
<ide> @connection.validate_foreign_key :astronauts, :rockets
<del> assert @connection.foreign_keys("astronauts").first.validated?
<add> assert_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide> end
<ide>
<ide> def test_validate_foreign_key_by_column
<ide> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false
<del> assert_not @connection.foreign_keys("astronauts").first.validated?
<add> assert_not_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide>
<ide> @connection.validate_foreign_key :astronauts, column: "rocket_id"
<del> assert @connection.foreign_keys("astronauts").first.validated?
<add> assert_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide> end
<ide>
<ide> def test_validate_foreign_key_by_symbol_column
<ide> @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id, validate: false
<del> assert_not @connection.foreign_keys("astronauts").first.validated?
<add> assert_not_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide>
<ide> @connection.validate_foreign_key :astronauts, column: :rocket_id
<del> assert @connection.foreign_keys("astronauts").first.validated?
<add> assert_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide> end
<ide>
<ide> def test_validate_foreign_key_by_name
<ide> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk", validate: false
<del> assert_not @connection.foreign_keys("astronauts").first.validated?
<add> assert_not_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide>
<ide> @connection.validate_foreign_key :astronauts, name: "fancy_named_fk"
<del> assert @connection.foreign_keys("astronauts").first.validated?
<add> assert_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide> end
<ide>
<ide> def test_validate_foreign_non_existing_foreign_key_raises
<ide> def test_validate_constraint_by_name
<ide> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk", validate: false
<ide>
<ide> @connection.validate_constraint :astronauts, "fancy_named_fk"
<del> assert @connection.foreign_keys("astronauts").first.validated?
<add> assert_predicate @connection.foreign_keys("astronauts").first, :validated?
<ide> end
<ide> else
<ide> # Foreign key should still be created, but should not be invalid
<ide> def test_add_invalid_foreign_key
<ide> assert_equal 1, foreign_keys.size
<ide>
<ide> fk = foreign_keys.first
<del> assert fk.validated?
<add> assert_predicate fk, :validated?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/migration_test.rb
<ide> def test_any_migrations
<ide> old_path = ActiveRecord::Migrator.migrations_paths
<ide> migrator = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid")
<ide>
<del> assert migrator.any_migrations?
<add> assert_predicate migrator, :any_migrations?
<ide>
<ide> migrator_empty = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/empty")
<ide>
<del> assert_not migrator_empty.any_migrations?
<add> assert_not_predicate migrator_empty, :any_migrations?
<ide> ensure
<ide> ActiveRecord::MigrationContext.new(old_path)
<ide> end
<ide> def create_table; "hi mom!"; end
<ide> def test_add_table_with_decimals
<ide> Person.connection.drop_table :big_numbers rescue nil
<ide>
<del> assert !BigNumber.table_exists?
<add> assert_not_predicate BigNumber, :table_exists?
<ide> GiveMeBigNumbers.up
<ide> BigNumber.reset_column_information
<ide>
<ide> def test_add_table_with_decimals
<ide>
<ide> def test_filtering_migrations
<ide> assert_no_column Person, :last_name
<del> assert !Reminder.table_exists?
<add> assert_not_predicate Reminder, :table_exists?
<ide>
<ide> name_filter = lambda { |migration| migration.name == "ValidPeopleHaveLastNames" }
<ide> migrator = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid")
<ide> def test_proper_table_name_on_migration
<ide> end
<ide>
<ide> def test_rename_table_with_prefix_and_suffix
<del> assert !Thing.table_exists?
<add> assert_not_predicate Thing, :table_exists?
<ide> ActiveRecord::Base.table_name_prefix = "p_"
<ide> ActiveRecord::Base.table_name_suffix = "_s"
<ide> Thing.reset_table_name
<ide> def test_rename_table_with_prefix_and_suffix
<ide> end
<ide>
<ide> def test_add_drop_table_with_prefix_and_suffix
<del> assert !Reminder.table_exists?
<add> assert_not_predicate Reminder, :table_exists?
<ide> ActiveRecord::Base.table_name_prefix = "prefix_"
<ide> ActiveRecord::Base.table_name_suffix = "_suffix"
<ide> Reminder.reset_table_name
<ide> def test_copying_migrations_without_timestamps
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy")
<ide> assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
<del> assert copied.empty?
<add> assert_predicate copied, :empty?
<ide> ensure
<ide> clear
<ide> end
<ide> def test_copying_migrations_with_timestamps
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps")
<ide> assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
<del> assert copied.empty?
<add> assert_predicate copied, :empty?
<ide> end
<ide> ensure
<ide> clear
<ide> def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_fu
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps")
<ide> assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
<del> assert copied.empty?
<add> assert_predicate copied, :empty?
<ide> end
<ide> ensure
<ide> clear
<ide> def test_copying_migrations_preserving_magic_comments
<ide> files_count = Dir[@migrations_path + "/*.rb"].length
<ide> copied = ActiveRecord::Migration.copy(@migrations_path, bukkits: MIGRATIONS_ROOT + "/magic")
<ide> assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
<del> assert copied.empty?
<add> assert_predicate copied, :empty?
<ide> ensure
<ide> clear
<ide> end
<ide><path>activerecord/test/cases/multiparameter_attributes_test.rb
<ide> def test_multiparameter_attributes_on_time_only_column_with_time_zone_aware_attr
<ide> topic = Topic.find(1)
<ide> topic.attributes = attributes
<ide> assert_equal Time.zone.local(2000, 1, 1, 16, 24, 0), topic.bonus_time
<del> assert_not topic.bonus_time.utc?
<add> assert_not_predicate topic.bonus_time, :utc?
<ide>
<ide> attributes = {
<ide> "written_on(1i)" => "2000", "written_on(2i)" => "", "written_on(3i)" => "",
<ide><path>activerecord/test/cases/nested_attributes_test.rb
<ide> def test_should_not_build_a_new_record_using_reject_all_even_if_destroy_is_given
<ide> pirate.birds_with_reject_all_blank_attributes = [{ name: "", color: "", _destroy: "0" }]
<ide> pirate.save!
<ide>
<del> assert pirate.birds_with_reject_all_blank.empty?
<add> assert_predicate pirate.birds_with_reject_all_blank, :empty?
<ide> end
<ide>
<ide> def test_should_not_build_a_new_record_if_reject_all_blank_returns_false
<ide> pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
<ide> pirate.birds_with_reject_all_blank_attributes = [{ name: "", color: "" }]
<ide> pirate.save!
<ide>
<del> assert pirate.birds_with_reject_all_blank.empty?
<add> assert_predicate pirate.birds_with_reject_all_blank, :empty?
<ide> end
<ide>
<ide> def test_should_build_a_new_record_if_reject_all_blank_does_not_return_false
<ide> def test_destroy_works_independent_of_reject_if
<ide> man = Man.create(name: "Jon")
<ide> interest = man.interests.create(topic: "the ladies")
<ide> man.update(interests_attributes: { _destroy: "1", id: interest.id })
<del> assert man.reload.interests.empty?
<add> assert_predicate man.reload.interests, :empty?
<ide> end
<ide>
<ide> def test_reject_if_is_not_short_circuited_if_allow_destroy_is_false
<ide> def test_should_build_a_new_record_if_there_is_no_id
<ide> @ship.destroy
<ide> @pirate.reload.ship_attributes = { name: "Davy Jones Gold Dagger" }
<ide>
<del> assert !@pirate.ship.persisted?
<add> assert_not_predicate @pirate.ship, :persisted?
<ide> assert_equal "Davy Jones Gold Dagger", @pirate.ship.name
<ide> end
<ide>
<ide> def test_should_not_build_a_new_record_if_a_reject_if_proc_returns_false
<ide> def test_should_replace_an_existing_record_if_there_is_no_id
<ide> @pirate.reload.ship_attributes = { name: "Davy Jones Gold Dagger" }
<ide>
<del> assert !@pirate.ship.persisted?
<add> assert_not_predicate @pirate.ship, :persisted?
<ide> assert_equal "Davy Jones Gold Dagger", @pirate.ship.name
<ide> assert_equal "Nights Dirty Lightning", @ship.name
<ide> end
<ide> def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false
<ide> def test_should_also_work_with_a_HashWithIndifferentAccess
<ide> @pirate.ship_attributes = ActiveSupport::HashWithIndifferentAccess.new(id: @ship.id, name: "Davy Jones Gold Dagger")
<ide>
<del> assert @pirate.ship.persisted?
<add> assert_predicate @pirate.ship, :persisted?
<ide> assert_equal "Davy Jones Gold Dagger", @pirate.ship.name
<ide> end
<ide>
<ide> def test_should_work_with_update_as_well
<ide> def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
<ide> @pirate.attributes = { ship_attributes: { id: @ship.id, _destroy: "1" } }
<ide>
<del> assert !@pirate.ship.destroyed?
<del> assert @pirate.ship.marked_for_destruction?
<add> assert_not_predicate @pirate.ship, :destroyed?
<add> assert_predicate @pirate.ship, :marked_for_destruction?
<ide>
<ide> @pirate.save
<ide>
<del> assert @pirate.ship.destroyed?
<add> assert_predicate @pirate.ship, :destroyed?
<ide> assert_nil @pirate.reload.ship
<ide> end
<ide>
<ide> def test_should_build_a_new_record_if_there_is_no_id
<ide> @pirate.destroy
<ide> @ship.reload.pirate_attributes = { catchphrase: "Arr" }
<ide>
<del> assert !@ship.pirate.persisted?
<add> assert_not_predicate @ship.pirate, :persisted?
<ide> assert_equal "Arr", @ship.pirate.catchphrase
<ide> end
<ide>
<ide> def test_should_not_build_a_new_record_if_a_reject_if_proc_returns_false
<ide> def test_should_replace_an_existing_record_if_there_is_no_id
<ide> @ship.reload.pirate_attributes = { catchphrase: "Arr" }
<ide>
<del> assert !@ship.pirate.persisted?
<add> assert_not_predicate @ship.pirate, :persisted?
<ide> assert_equal "Arr", @ship.pirate.catchphrase
<ide> assert_equal "Aye", @pirate.catchphrase
<ide> end
<ide> def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true
<ide> @pirate.delete
<ide> @ship.reload.attributes = { update_only_pirate_attributes: { catchphrase: "Arr" } }
<ide>
<del> assert !@ship.update_only_pirate.persisted?
<add> assert_not_predicate @ship.update_only_pirate, :persisted?
<ide> end
<ide>
<ide> def test_should_update_existing_when_update_only_is_true_and_no_id_is_given
<ide> def test_should_take_a_hash_and_assign_the_attributes_to_the_associated_models
<ide> def test_should_not_load_association_when_updating_existing_records
<ide> @pirate.reload
<ide> @pirate.send(association_setter, [{ id: @child_1.id, name: "Grace OMalley" }])
<del> assert ! @pirate.send(@association_name).loaded?
<add> assert_not_predicate @pirate.send(@association_name), :loaded?
<ide>
<ide> @pirate.save
<del> assert ! @pirate.send(@association_name).loaded?
<add> assert_not_predicate @pirate.send(@association_name), :loaded?
<ide> assert_equal "Grace OMalley", @child_1.reload.name
<ide> end
<ide>
<ide> def test_should_refresh_saved_records_when_not_overwriting_unsaved_updates
<ide> def test_should_not_remove_scheduled_destroys_when_loading_association
<ide> @pirate.reload
<ide> @pirate.send(association_setter, [{ id: @child_1.id, _destroy: "1" }])
<del> assert @pirate.send(@association_name).load_target.find { |r| r.id == @child_1.id }.marked_for_destruction?
<add> assert_predicate @pirate.send(@association_name).load_target.find { |r| r.id == @child_1.id }, :marked_for_destruction?
<ide> end
<ide>
<ide> def test_should_take_a_hash_with_composite_id_keys_and_assign_the_attributes_to_the_associated_models
<ide> def test_should_automatically_build_new_associated_models_for_each_entry_in_a_ha
<ide> association_getter => { "foo" => { name: "Grace OMalley" }, "bar" => { name: "Privateers Greed" } }
<ide> }
<ide>
<del> assert !@pirate.send(@association_name).first.persisted?
<add> assert_not_predicate @pirate.send(@association_name).first, :persisted?
<ide> assert_equal "Grace OMalley", @pirate.send(@association_name).first.name
<ide>
<del> assert !@pirate.send(@association_name).last.persisted?
<add> assert_not_predicate @pirate.send(@association_name).last, :persisted?
<ide> assert_equal "Privateers Greed", @pirate.send(@association_name).last.name
<ide> end
<ide>
<ide> def setup
<ide> test "nested singular associations are validated" do
<ide> part = ShipPart.new(name: "Stern", ship_attributes: { name: nil })
<ide>
<del> assert_not part.valid?
<add> assert_not_predicate part, :valid?
<ide> assert_equal ["Ship name can't be blank"], part.errors.full_messages
<ide> end
<ide> end
<ide><path>activerecord/test/cases/nested_attributes_with_callbacks_test.rb
<ide> def update_new_and_destroy_bird_attributes
<ide>
<ide> # Characterizing when :before_add callback is called
<ide> test ":before_add called for new bird when not loaded" do
<del> assert_not @pirate.birds_with_add.loaded?
<add> assert_not_predicate @pirate.birds_with_add, :loaded?
<ide> @pirate.birds_with_add_attributes = new_bird_attributes
<ide> assert_new_bird_with_callback_called
<ide> end
<ide> def assert_new_bird_with_callback_called
<ide> end
<ide>
<ide> test ":before_add not called for identical assignment when not loaded" do
<del> assert_not @pirate.birds_with_add.loaded?
<add> assert_not_predicate @pirate.birds_with_add, :loaded?
<ide> @pirate.birds_with_add_attributes = existing_birds_attributes
<ide> assert_callbacks_not_called
<ide> end
<ide> def assert_new_bird_with_callback_called
<ide> end
<ide>
<ide> test ":before_add not called for destroy assignment when not loaded" do
<del> assert_not @pirate.birds_with_add.loaded?
<add> assert_not_predicate @pirate.birds_with_add, :loaded?
<ide> @pirate.birds_with_add_attributes = destroy_bird_attributes
<ide> assert_callbacks_not_called
<ide> end
<ide> def assert_callbacks_not_called
<ide> # Ensuring that the records in the association target are updated,
<ide> # whether the association is loaded before or not
<ide> test "Assignment updates records in target when not loaded" do
<del> assert_not @pirate.birds_with_add.loaded?
<add> assert_not_predicate @pirate.birds_with_add, :loaded?
<ide> @pirate.birds_with_add_attributes = update_new_and_destroy_bird_attributes
<ide> assert_assignment_affects_records_in_target(:birds_with_add)
<ide> end
<ide> def assert_callbacks_not_called
<ide>
<ide> test("Assignment updates records in target when not loaded" \
<ide> " and callback loads target") do
<del> assert_not @pirate.birds_with_add_load.loaded?
<add> assert_not_predicate @pirate.birds_with_add_load, :loaded?
<ide> @pirate.birds_with_add_load_attributes = update_new_and_destroy_bird_attributes
<ide> assert_assignment_affects_records_in_target(:birds_with_add_load)
<ide> end
<ide><path>activerecord/test/cases/persistence_test.rb
<ide> def test_increment_updates_timestamps
<ide> def test_destroy_all
<ide> conditions = "author_name = 'Mary'"
<ide> topics_by_mary = Topic.all.merge!(where: conditions, order: "id").to_a
<del> assert ! topics_by_mary.empty?
<add> assert_not_predicate topics_by_mary, :empty?
<ide>
<ide> assert_difference("Topic.count", -topics_by_mary.size) do
<ide> destroyed = Topic.where(conditions).destroy_all.sort_by(&:id)
<ide> def test_becomes
<ide>
<ide> def test_becomes_includes_errors
<ide> company = Company.new(name: nil)
<del> assert !company.valid?
<add> assert_not_predicate company, :valid?
<ide> original_errors = company.errors
<ide> client = company.becomes(Client)
<ide> assert_equal original_errors.keys, client.errors.keys
<ide> def test_save_with_duping_of_destroyed_object
<ide> developer.destroy
<ide> new_developer = developer.dup
<ide> new_developer.save
<del> assert new_developer.persisted?
<del> assert_not new_developer.destroyed?
<add> assert_predicate new_developer, :persisted?
<add> assert_not_predicate new_developer, :destroyed?
<ide> end
<ide>
<ide> def test_create_many
<ide> def test_create_columns_not_equal_attributes
<ide> )
<ide> topic = topic.dup # reset @new_record
<ide> assert_nothing_raised { topic.save }
<del> assert topic.persisted?
<add> assert_predicate topic, :persisted?
<ide> assert_equal "Another New Topic", topic.reload.title
<ide> end
<ide>
<ide> def test_update_columns_not_equal_attributes
<ide> topic_reloaded = Topic.instantiate(topic.attributes.merge("does_not_exist" => "test"))
<ide> topic_reloaded.title = "A New Topic"
<ide> assert_nothing_raised { topic_reloaded.save }
<del> assert topic_reloaded.persisted?
<add> assert_predicate topic_reloaded, :persisted?
<ide> assert_equal "A New Topic", topic_reloaded.reload.title
<ide> end
<ide>
<ide> def test_update_all_with_non_standard_table_name
<ide> def test_delete_new_record
<ide> client = Client.new(name: "37signals")
<ide> client.delete
<del> assert client.frozen?
<add> assert_predicate client, :frozen?
<ide>
<ide> assert_not client.save
<ide> assert_raise(ActiveRecord::RecordNotSaved) { client.save! }
<ide>
<del> assert client.frozen?
<add> assert_predicate client, :frozen?
<ide> assert_raise(RuntimeError) { client.name = "something else" }
<ide> end
<ide>
<ide> def test_delete_record_with_associations
<ide> client = Client.find(3)
<ide> client.delete
<del> assert client.frozen?
<add> assert_predicate client, :frozen?
<ide> assert_kind_of Firm, client.firm
<ide>
<ide> assert_not client.save
<ide> assert_raise(ActiveRecord::RecordNotSaved) { client.save! }
<ide>
<del> assert client.frozen?
<add> assert_predicate client, :frozen?
<ide> assert_raise(RuntimeError) { client.name = "something else" }
<ide> end
<ide>
<ide> def test_destroy_new_record
<ide> client = Client.new(name: "37signals")
<ide> client.destroy
<del> assert client.frozen?
<add> assert_predicate client, :frozen?
<ide>
<ide> assert_not client.save
<ide> assert_raise(ActiveRecord::RecordNotSaved) { client.save! }
<ide>
<del> assert client.frozen?
<add> assert_predicate client, :frozen?
<ide> assert_raise(RuntimeError) { client.name = "something else" }
<ide> end
<ide>
<ide> def test_destroy_record_with_associations
<ide> client = Client.find(3)
<ide> client.destroy
<del> assert client.frozen?
<add> assert_predicate client, :frozen?
<ide> assert_kind_of Firm, client.firm
<ide>
<ide> assert_not client.save
<ide> assert_raise(ActiveRecord::RecordNotSaved) { client.save! }
<ide>
<del> assert client.frozen?
<add> assert_predicate client, :frozen?
<ide> assert_raise(RuntimeError) { client.name = "something else" }
<ide> end
<ide>
<ide> def test_update_attribute
<del> assert !Topic.find(1).approved?
<add> assert_not_predicate Topic.find(1), :approved?
<ide> Topic.find(1).update_attribute("approved", true)
<del> assert Topic.find(1).approved?
<add> assert_predicate Topic.find(1), :approved?
<ide>
<ide> Topic.find(1).update_attribute(:approved, false)
<del> assert !Topic.find(1).approved?
<add> assert_not_predicate Topic.find(1), :approved?
<ide>
<ide> Topic.find(1).update_attribute(:change_approved_before_save, true)
<del> assert Topic.find(1).approved?
<add> assert_predicate Topic.find(1), :approved?
<ide> end
<ide>
<ide> def test_update_attribute_for_readonly_attribute
<ide> def test_update_attribute_for_updated_at_on
<ide> def test_update_column
<ide> topic = Topic.find(1)
<ide> topic.update_column("approved", true)
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide> topic.reload
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide>
<ide> topic.update_column(:approved, false)
<del> assert !topic.approved?
<add> assert_not_predicate topic, :approved?
<ide> topic.reload
<del> assert !topic.approved?
<add> assert_not_predicate topic, :approved?
<ide> end
<ide>
<ide> def test_update_column_should_not_use_setter_method
<ide> def test_update_column_with_default_scope
<ide> def test_update_columns
<ide> topic = Topic.find(1)
<ide> topic.update_columns("approved" => true, title: "Sebastian Topic")
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide> assert_equal "Sebastian Topic", topic.title
<ide> topic.reload
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide> assert_equal "Sebastian Topic", topic.title
<ide> end
<ide>
<ide> def test_update_columns_with_default_scope
<ide>
<ide> def test_update
<ide> topic = Topic.find(1)
<del> assert !topic.approved?
<add> assert_not_predicate topic, :approved?
<ide> assert_equal "The First Topic", topic.title
<ide>
<ide> topic.update("approved" => true, "title" => "The First Topic Updated")
<ide> topic.reload
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide> assert_equal "The First Topic Updated", topic.title
<ide>
<ide> topic.update(approved: false, title: "The First Topic")
<ide> topic.reload
<del> assert !topic.approved?
<add> assert_not_predicate topic, :approved?
<ide> assert_equal "The First Topic", topic.title
<ide> end
<ide>
<ide> def test_update_attributes
<ide> topic = Topic.find(1)
<del> assert !topic.approved?
<add> assert_not_predicate topic, :approved?
<ide> assert_equal "The First Topic", topic.title
<ide>
<ide> topic.update_attributes("approved" => true, "title" => "The First Topic Updated")
<ide> topic.reload
<del> assert topic.approved?
<add> assert_predicate topic, :approved?
<ide> assert_equal "The First Topic Updated", topic.title
<ide>
<ide> topic.update_attributes(approved: false, title: "The First Topic")
<ide> topic.reload
<del> assert !topic.approved?
<add> assert_not_predicate topic, :approved?
<ide> assert_equal "The First Topic", topic.title
<ide>
<ide> error = assert_raise(ActiveRecord::RecordNotUnique, ActiveRecord::StatementInvalid) do
<ide> def test_class_level_destroy
<ide> Topic.find(1).replies << should_be_destroyed_reply
<ide>
<ide> topic = Topic.destroy(1)
<del> assert topic.destroyed?
<add> assert_predicate topic, :destroyed?
<ide>
<ide> assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
<ide> assert_raise(ActiveRecord::RecordNotFound) { Reply.find(should_be_destroyed_reply.id) }
<ide> def test_reload_removes_custom_selects
<ide> def test_find_via_reload
<ide> post = Post.new
<ide>
<del> assert post.new_record?
<add> assert_predicate post, :new_record?
<ide>
<ide> post.id = 1
<ide> post.reload
<ide>
<ide> assert_equal "Welcome to the weblog", post.title
<del> assert_not post.new_record?
<add> assert_not_predicate post, :new_record?
<ide> end
<ide>
<ide> def test_reload_via_querycache
<ide><path>activerecord/test/cases/primary_keys_test.rb
<ide> def test_create_without_primary_key_no_extra_query
<ide> def test_serial_with_quoted_sequence_name
<ide> column = MixedCaseMonkey.columns_hash[MixedCaseMonkey.primary_key]
<ide> assert_equal "nextval('\"mixed_case_monkeys_monkeyID_seq\"'::regclass)", column.default_function
<del> assert column.serial?
<add> assert_predicate column, :serial?
<ide> end
<ide>
<ide> def test_serial_with_unquoted_sequence_name
<ide> column = Topic.columns_hash[Topic.primary_key]
<ide> assert_equal "nextval('topics_id_seq'::regclass)", column.default_function
<del> assert column.serial?
<add> assert_predicate column, :serial?
<ide> end
<ide> end
<ide> end
<ide> class Widget < ActiveRecord::Base
<ide> @connection.create_table(:widgets, id: @pk_type, force: true)
<ide> column = @connection.columns(:widgets).find { |c| c.name == "id" }
<ide> assert_equal :integer, column.type
<del> assert_not column.bigint?
<add> assert_not_predicate column, :bigint?
<ide> end
<ide>
<ide> test "primary key with serial/integer are automatically numbered" do
<ide> class Widget < ActiveRecord::Base
<ide> test "primary key column type with options" do
<ide> @connection.create_table(:widgets, id: :primary_key, limit: 4, unsigned: true, force: true)
<ide> column = @connection.columns(:widgets).find { |c| c.name == "id" }
<del> assert column.auto_increment?
<add> assert_predicate column, :auto_increment?
<ide> assert_equal :integer, column.type
<del> assert_not column.bigint?
<del> assert column.unsigned?
<add> assert_not_predicate column, :bigint?
<add> assert_predicate column, :unsigned?
<ide>
<ide> schema = dump_table_schema "widgets"
<ide> assert_match %r{create_table "widgets", id: :integer, unsigned: true, }, schema
<ide> class Widget < ActiveRecord::Base
<ide> test "bigint primary key with unsigned" do
<ide> @connection.create_table(:widgets, id: :bigint, unsigned: true, force: true)
<ide> column = @connection.columns(:widgets).find { |c| c.name == "id" }
<del> assert column.auto_increment?
<add> assert_predicate column, :auto_increment?
<ide> assert_equal :integer, column.type
<del> assert column.bigint?
<del> assert column.unsigned?
<add> assert_predicate column, :bigint?
<add> assert_predicate column, :unsigned?
<ide>
<ide> schema = dump_table_schema "widgets"
<ide> assert_match %r{create_table "widgets", id: :bigint, unsigned: true, }, schema
<ide><path>activerecord/test/cases/query_cache_test.rb
<ide> def test_query_cache_across_threads
<ide> assert_cache :off, conn
<ide> end
<ide>
<del> assert !ActiveRecord::Base.connection.nil?
<add> assert_not_predicate ActiveRecord::Base.connection, :nil?
<ide> assert_cache :off
<ide>
<ide> middleware {
<ide> def test_cache_is_available_when_using_a_not_connected_connection
<ide> conf = ActiveRecord::Base.configurations["arunit"].merge("name" => "test2")
<ide> ActiveRecord::Base.connection_handler.establish_connection(conf)
<ide> Task.connection_specification_name = "test2"
<del> assert_not Task.connected?
<add> assert_not_predicate Task, :connected?
<ide>
<ide> Task.cache do
<ide> begin
<ide> def test_cache_is_expired_by_habtm_delete
<ide> assert_called(ActiveRecord::Base.connection, :clear_query_cache, times: 2) do
<ide> ActiveRecord::Base.cache do
<ide> p = Post.find(1)
<del> assert p.categories.any?
<add> assert_predicate p.categories, :any?
<ide> p.categories.delete_all
<ide> end
<ide> end
<ide><path>activerecord/test/cases/readonly_test.rb
<ide> class ReadOnlyTest < ActiveRecord::TestCase
<ide>
<ide> def test_cant_save_readonly_record
<ide> dev = Developer.find(1)
<del> assert !dev.readonly?
<add> assert_not_predicate dev, :readonly?
<ide>
<ide> dev.readonly!
<del> assert dev.readonly?
<add> assert_predicate dev, :readonly?
<ide>
<ide> assert_nothing_raised do
<ide> dev.name = "Luscious forbidden fruit."
<ide> def test_find_with_joins_option_does_not_imply_readonly
<ide>
<ide> def test_has_many_find_readonly
<ide> post = Post.find(1)
<del> assert !post.comments.empty?
<add> assert_not_predicate post.comments, :empty?
<ide> assert !post.comments.any?(&:readonly?)
<ide> assert !post.comments.to_a.any?(&:readonly?)
<ide> assert post.comments.readonly(true).all?(&:readonly?)
<ide> def test_has_many_with_through_is_not_implicitly_marked_readonly
<ide> end
<ide>
<ide> def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_by_id
<del> assert !posts(:welcome).people.find(1).readonly?
<add> assert_not_predicate posts(:welcome).people.find(1), :readonly?
<ide> end
<ide>
<ide> def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_first
<del> assert !posts(:welcome).people.first.readonly?
<add> assert_not_predicate posts(:welcome).people.first, :readonly?
<ide> end
<ide>
<ide> def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_last
<del> assert !posts(:welcome).people.last.readonly?
<add> assert_not_predicate posts(:welcome).people.last, :readonly?
<ide> end
<ide>
<ide> def test_readonly_scoping
<ide> Post.where("1=1").scoping do
<del> assert !Post.find(1).readonly?
<del> assert Post.readonly(true).find(1).readonly?
<del> assert !Post.readonly(false).find(1).readonly?
<add> assert_not_predicate Post.find(1), :readonly?
<add> assert_predicate Post.readonly(true).find(1), :readonly?
<add> assert_not_predicate Post.readonly(false).find(1), :readonly?
<ide> end
<ide>
<ide> Post.joins(" ").scoping do
<del> assert !Post.find(1).readonly?
<del> assert Post.readonly.find(1).readonly?
<del> assert !Post.readonly(false).find(1).readonly?
<add> assert_not_predicate Post.find(1), :readonly?
<add> assert_predicate Post.readonly.find(1), :readonly?
<add> assert_not_predicate Post.readonly(false).find(1), :readonly?
<ide> end
<ide>
<ide> # Oracle barfs on this because the join includes unqualified and
<ide> # conflicting column names
<ide> unless current_adapter?(:OracleAdapter)
<ide> Post.joins(", developers").scoping do
<del> assert_not Post.find(1).readonly?
<del> assert Post.readonly.find(1).readonly?
<del> assert !Post.readonly(false).find(1).readonly?
<add> assert_not_predicate Post.find(1), :readonly?
<add> assert_predicate Post.readonly.find(1), :readonly?
<add> assert_not_predicate Post.readonly(false).find(1), :readonly?
<ide> end
<ide> end
<ide>
<ide> Post.readonly(true).scoping do
<del> assert Post.find(1).readonly?
<del> assert Post.readonly.find(1).readonly?
<del> assert !Post.readonly(false).find(1).readonly?
<add> assert_predicate Post.find(1), :readonly?
<add> assert_predicate Post.readonly.find(1), :readonly?
<add> assert_not_predicate Post.readonly(false).find(1), :readonly?
<ide> end
<ide> end
<ide>
<ide> def test_association_collection_method_missing_scoping_not_readonly
<ide> developer = Developer.find(1)
<ide> project = Post.find(1)
<ide>
<del> assert !developer.projects.all_as_method.first.readonly?
<del> assert !developer.projects.all_as_scope.first.readonly?
<add> assert_not_predicate developer.projects.all_as_method.first, :readonly?
<add> assert_not_predicate developer.projects.all_as_scope.first, :readonly?
<ide>
<del> assert !project.comments.all_as_method.first.readonly?
<del> assert !project.comments.all_as_scope.first.readonly?
<add> assert_not_predicate project.comments.all_as_method.first, :readonly?
<add> assert_not_predicate project.comments.all_as_scope.first, :readonly?
<ide> end
<ide> end
<ide><path>activerecord/test/cases/reaper_test.rb
<ide> def test_connection_pool_starts_reaper
<ide> end
<ide> Thread.pass while conn.nil?
<ide>
<del> assert conn.in_use?
<add> assert_predicate conn, :in_use?
<ide>
<ide> child.terminate
<ide>
<ide> while conn.in_use?
<ide> Thread.pass
<ide> end
<del> assert !conn.in_use?
<add> assert_not_predicate conn, :in_use?
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/reflection_test.rb
<ide> def test_reflect_on_all_autosave_associations
<ide> expected = Pirate.reflect_on_all_associations.select { |r| r.options[:autosave] }
<ide> received = Pirate.reflect_on_all_autosave_associations
<ide>
<del> assert !received.empty?
<add> assert_not_predicate received, :empty?
<ide> assert_not_equal Pirate.reflect_on_all_associations.length, received.length
<ide> assert_equal expected, received
<ide> end
<ide> def test_scope_chain_of_polymorphic_association_does_not_leak_into_other_hmt_ass
<ide> end
<ide>
<ide> def test_nested?
<del> assert !Author.reflect_on_association(:comments).nested?
<del> assert Author.reflect_on_association(:tags).nested?
<add> assert_not_predicate Author.reflect_on_association(:comments), :nested?
<add> assert_predicate Author.reflect_on_association(:tags), :nested?
<ide>
<ide> # Only goes :through once, but the through_reflection is a has_and_belongs_to_many, so this is
<ide> # a nested through association
<del> assert Category.reflect_on_association(:post_comments).nested?
<add> assert_predicate Category.reflect_on_association(:post_comments), :nested?
<ide> end
<ide>
<ide> def test_association_primary_key
<ide> def test_foreign_type
<ide> end
<ide>
<ide> def test_collection_association
<del> assert Pirate.reflect_on_association(:birds).collection?
<del> assert Pirate.reflect_on_association(:parrots).collection?
<add> assert_predicate Pirate.reflect_on_association(:birds), :collection?
<add> assert_predicate Pirate.reflect_on_association(:parrots), :collection?
<ide>
<del> assert !Pirate.reflect_on_association(:ship).collection?
<del> assert !Ship.reflect_on_association(:pirate).collection?
<add> assert_not_predicate Pirate.reflect_on_association(:ship), :collection?
<add> assert_not_predicate Ship.reflect_on_association(:pirate), :collection?
<ide> end
<ide>
<ide> def test_default_association_validation
<del> assert ActiveRecord::Reflection.create(:has_many, :clients, nil, {}, Firm).validate?
<add> assert_predicate ActiveRecord::Reflection.create(:has_many, :clients, nil, {}, Firm), :validate?
<ide>
<del> assert !ActiveRecord::Reflection.create(:has_one, :client, nil, {}, Firm).validate?
<del> assert !ActiveRecord::Reflection.create(:belongs_to, :client, nil, {}, Firm).validate?
<add> assert_not_predicate ActiveRecord::Reflection.create(:has_one, :client, nil, {}, Firm), :validate?
<add> assert_not_predicate ActiveRecord::Reflection.create(:belongs_to, :client, nil, {}, Firm), :validate?
<ide> end
<ide>
<ide> def test_always_validate_association_if_explicit
<del> assert ActiveRecord::Reflection.create(:has_one, :client, nil, { validate: true }, Firm).validate?
<del> assert ActiveRecord::Reflection.create(:belongs_to, :client, nil, { validate: true }, Firm).validate?
<del> assert ActiveRecord::Reflection.create(:has_many, :clients, nil, { validate: true }, Firm).validate?
<add> assert_predicate ActiveRecord::Reflection.create(:has_one, :client, nil, { validate: true }, Firm), :validate?
<add> assert_predicate ActiveRecord::Reflection.create(:belongs_to, :client, nil, { validate: true }, Firm), :validate?
<add> assert_predicate ActiveRecord::Reflection.create(:has_many, :clients, nil, { validate: true }, Firm), :validate?
<ide> end
<ide>
<ide> def test_validate_association_if_autosave
<del> assert ActiveRecord::Reflection.create(:has_one, :client, nil, { autosave: true }, Firm).validate?
<del> assert ActiveRecord::Reflection.create(:belongs_to, :client, nil, { autosave: true }, Firm).validate?
<del> assert ActiveRecord::Reflection.create(:has_many, :clients, nil, { autosave: true }, Firm).validate?
<add> assert_predicate ActiveRecord::Reflection.create(:has_one, :client, nil, { autosave: true }, Firm), :validate?
<add> assert_predicate ActiveRecord::Reflection.create(:belongs_to, :client, nil, { autosave: true }, Firm), :validate?
<add> assert_predicate ActiveRecord::Reflection.create(:has_many, :clients, nil, { autosave: true }, Firm), :validate?
<ide> end
<ide>
<ide> def test_never_validate_association_if_explicit
<del> assert !ActiveRecord::Reflection.create(:has_one, :client, nil, { autosave: true, validate: false }, Firm).validate?
<del> assert !ActiveRecord::Reflection.create(:belongs_to, :client, nil, { autosave: true, validate: false }, Firm).validate?
<del> assert !ActiveRecord::Reflection.create(:has_many, :clients, nil, { autosave: true, validate: false }, Firm).validate?
<add> assert_not_predicate ActiveRecord::Reflection.create(:has_one, :client, nil, { autosave: true, validate: false }, Firm), :validate?
<add> assert_not_predicate ActiveRecord::Reflection.create(:belongs_to, :client, nil, { autosave: true, validate: false }, Firm), :validate?
<add> assert_not_predicate ActiveRecord::Reflection.create(:has_many, :clients, nil, { autosave: true, validate: false }, Firm), :validate?
<ide> end
<ide>
<ide> def test_foreign_key
<ide><path>activerecord/test/cases/relation/merging_test.rb
<ide> def test_relation_merging_with_eager_load
<ide>
<ide> def test_relation_merging_with_locks
<ide> devs = Developer.lock.where("salary >= 80000").order("id DESC").merge(Developer.limit(2))
<del> assert devs.locked?
<add> assert_predicate devs, :locked?
<ide> end
<ide>
<ide> def test_relation_merging_with_preload
<ide> def test_merging_compares_symbols_and_strings_as_equal
<ide>
<ide> def test_merging_with_from_clause
<ide> relation = Post.all
<del> assert relation.from_clause.empty?
<add> assert_predicate relation.from_clause, :empty?
<ide> relation = relation.merge(Post.from("posts"))
<del> assert_not relation.from_clause.empty?
<add> assert_not_predicate relation.from_clause, :empty?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/relation/mutation_test.rb
<ide> class RelationMutationTest < ActiveRecord::TestCase
<ide> test "#order! with symbol prepends the table name" do
<ide> assert relation.order!(:name).equal?(relation)
<ide> node = relation.order_values.first
<del> assert node.ascending?
<add> assert_predicate node, :ascending?
<ide> assert_equal :name, node.expr.name
<ide> assert_equal "posts", node.expr.relation.name
<ide> end
<ide> class RelationMutationTest < ActiveRecord::TestCase
<ide> assert relation.reorder!(:name).equal?(relation)
<ide> node = relation.order_values.first
<ide>
<del> assert node.ascending?
<add> assert_predicate node, :ascending?
<ide> assert_equal :name, node.expr.name
<ide> assert_equal "posts", node.expr.relation.name
<ide> end
<ide><path>activerecord/test/cases/relation/where_clause_test.rb
<ide> class WhereClauseTest < ActiveRecord::TestCase
<ide> end
<ide>
<ide> test "a clause knows if it is empty" do
<del> assert WhereClause.empty.empty?
<del> assert_not WhereClause.new(["anything"]).empty?
<add> assert_predicate WhereClause.empty, :empty?
<add> assert_not_predicate WhereClause.new(["anything"]), :empty?
<ide> end
<ide>
<ide> test "invert cannot handle nil" do
<ide><path>activerecord/test/cases/relation_test.rb
<ide> def test_create_with_value_with_wheres
<ide>
<ide> def test_empty_scope
<ide> relation = Relation.new(Post)
<del> assert relation.empty_scope?
<add> assert_predicate relation, :empty_scope?
<ide>
<ide> relation.merge!(relation)
<del> assert relation.empty_scope?
<add> assert_predicate relation, :empty_scope?
<ide> end
<ide>
<ide> def test_bad_constants_raise_errors
<ide> def test_bad_constants_raise_errors
<ide>
<ide> def test_empty_eager_loading?
<ide> relation = Relation.new(FakeKlass)
<del> assert !relation.eager_loading?
<add> assert_not_predicate relation, :eager_loading?
<ide> end
<ide>
<ide> def test_eager_load_values
<ide> relation = Relation.new(FakeKlass)
<ide> relation.eager_load! :b
<del> assert relation.eager_loading?
<add> assert_predicate relation, :eager_loading?
<ide> end
<ide>
<ide> def test_references_values
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_loaded_all
<ide> 2.times { assert_equal 5, topics.to_a.size }
<ide> end
<ide>
<del> assert topics.loaded?
<add> assert_predicate topics, :loaded?
<ide> end
<ide>
<ide> def test_scoped_first
<ide> def test_scoped_first
<ide> 2.times { assert_equal "The First Topic", topics.first.title }
<ide> end
<ide>
<del> assert ! topics.loaded?
<add> assert_not_predicate topics, :loaded?
<ide> end
<ide>
<ide> def test_loaded_first
<ide> def test_loaded_first
<ide> assert_equal "The First Topic", topics.first.title
<ide> end
<ide>
<del> assert topics.loaded?
<add> assert_predicate topics, :loaded?
<ide> end
<ide>
<ide> def test_loaded_first_with_limit
<ide> def test_loaded_first_with_limit
<ide> "The Second Topic of the day"], topics.first(2).map(&:title)
<ide> end
<ide>
<del> assert topics.loaded?
<add> assert_predicate topics, :loaded?
<ide> end
<ide>
<ide> def test_first_get_more_than_available
<ide> def test_reload
<ide> 2.times { topics.to_a }
<ide> end
<ide>
<del> assert topics.loaded?
<add> assert_predicate topics, :loaded?
<ide>
<ide> original_size = topics.to_a.size
<ide> Topic.create! title: "fake"
<ide>
<ide> assert_queries(1) { topics.reload }
<ide> assert_equal original_size + 1, topics.size
<del> assert topics.loaded?
<add> assert_predicate topics, :loaded?
<ide> end
<ide>
<ide> def test_finding_with_subquery
<ide> def test_find_ids
<ide>
<ide> def test_find_in_empty_array
<ide> authors = Author.all.where(id: [])
<del> assert authors.to_a.blank?
<add> assert_predicate authors.to_a, :blank?
<ide> end
<ide>
<ide> def test_where_with_ar_object
<ide> def test_destroy_all
<ide>
<ide> # Force load
<ide> assert_equal [authors(:david)], davids.to_a
<del> assert davids.loaded?
<add> assert_predicate davids, :loaded?
<ide>
<ide> assert_difference("Author.count", -1) { davids.destroy_all }
<ide>
<ide> assert_equal [], davids.to_a
<del> assert davids.loaded?
<add> assert_predicate davids, :loaded?
<ide> end
<ide>
<ide> def test_delete_all
<ide> davids = Author.where(name: "David")
<ide>
<ide> assert_difference("Author.count", -1) { davids.delete_all }
<del> assert ! davids.loaded?
<add> assert_not_predicate davids, :loaded?
<ide> end
<ide>
<ide> def test_delete_all_loaded
<ide> davids = Author.where(name: "David")
<ide>
<ide> # Force load
<ide> assert_equal [authors(:david)], davids.to_a
<del> assert davids.loaded?
<add> assert_predicate davids, :loaded?
<ide>
<ide> assert_difference("Author.count", -1) { davids.delete_all }
<ide>
<ide> assert_equal [], davids.to_a
<del> assert davids.loaded?
<add> assert_predicate davids, :loaded?
<ide> end
<ide>
<ide> def test_delete_all_with_unpermitted_relation_raises_error
<ide> def test_select_with_aggregates
<ide>
<ide> assert_equal 11, posts.count(:all)
<ide> assert_equal 11, posts.size
<del> assert posts.any?
<del> assert posts.many?
<del> assert_not posts.empty?
<add> assert_predicate posts, :any?
<add> assert_predicate posts, :many?
<add> assert_not_predicate posts, :empty?
<ide> end
<ide>
<ide> def test_select_takes_a_variable_list_of_args
<ide> def test_count_on_association_relation
<ide> assert_equal author.posts.where(author_id: author.id).size, posts.count
<ide>
<ide> assert_equal 0, author.posts.where(author_id: another_author.id).size
<del> assert author.posts.where(author_id: another_author.id).empty?
<add> assert_predicate author.posts.where(author_id: another_author.id), :empty?
<ide> end
<ide>
<ide> def test_count_with_distinct
<ide> def test_size
<ide> posts = Post.all
<ide>
<ide> assert_queries(1) { assert_equal 11, posts.size }
<del> assert ! posts.loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> best_posts = posts.where(comments_count: 0)
<ide> best_posts.load # force load
<ide> def test_size_with_limit
<ide> posts = Post.limit(10)
<ide>
<ide> assert_queries(1) { assert_equal 10, posts.size }
<del> assert ! posts.loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> best_posts = posts.where(comments_count: 0)
<ide> best_posts.load # force load
<ide> def test_size_with_zero_limit
<ide> posts = Post.limit(0)
<ide>
<ide> assert_no_queries { assert_equal 0, posts.size }
<del> assert ! posts.loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> posts.load # force load
<ide> assert_no_queries { assert_equal 0, posts.size }
<ide> def test_empty_with_zero_limit
<ide> posts = Post.limit(0)
<ide>
<ide> assert_no_queries { assert_equal true, posts.empty? }
<del> assert ! posts.loaded?
<add> assert_not_predicate posts, :loaded?
<ide> end
<ide>
<ide> def test_count_complex_chained_relations
<ide> def test_empty
<ide> posts = Post.all
<ide>
<ide> assert_queries(1) { assert_equal false, posts.empty? }
<del> assert ! posts.loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> no_posts = posts.where(title: "")
<ide> assert_queries(1) { assert_equal true, no_posts.empty? }
<del> assert ! no_posts.loaded?
<add> assert_not_predicate no_posts, :loaded?
<ide>
<ide> best_posts = posts.where(comments_count: 0)
<ide> best_posts.load # force load
<ide> def test_empty_complex_chained_relations
<ide> posts = Post.select("comments_count").where("id is not null").group("author_id").where("comments_count > 0")
<ide>
<ide> assert_queries(1) { assert_equal false, posts.empty? }
<del> assert ! posts.loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> no_posts = posts.where(title: "")
<ide> assert_queries(1) { assert_equal true, no_posts.empty? }
<del> assert ! no_posts.loaded?
<add> assert_not_predicate no_posts, :loaded?
<ide> end
<ide>
<ide> def test_any
<ide> def test_any
<ide>
<ide> assert_queries(3) do
<ide> assert posts.any? # Uses COUNT()
<del> assert ! posts.where(id: nil).any?
<add> assert_not_predicate posts.where(id: nil), :any?
<ide>
<ide> assert posts.any? { |p| p.id > 0 }
<ide> assert ! posts.any? { |p| p.id <= 0 }
<ide> end
<ide>
<del> assert posts.loaded?
<add> assert_predicate posts, :loaded?
<ide> end
<ide>
<ide> def test_many
<ide> def test_many
<ide> assert ! posts.many? { |p| p.id < 2 }
<ide> end
<ide>
<del> assert posts.loaded?
<add> assert_predicate posts, :loaded?
<ide> end
<ide>
<ide> def test_many_with_limits
<ide> posts = Post.all
<ide>
<del> assert posts.many?
<del> assert ! posts.limit(1).many?
<add> assert_predicate posts, :many?
<add> assert_not_predicate posts.limit(1), :many?
<ide> end
<ide>
<ide> def test_none?
<ide> def test_none?
<ide> assert ! posts.none? # Uses COUNT()
<ide> end
<ide>
<del> assert ! posts.loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> assert_queries(1) do
<ide> assert posts.none? { |p| p.id < 0 }
<ide> assert ! posts.none? { |p| p.id == 1 }
<ide> end
<ide>
<del> assert posts.loaded?
<add> assert_predicate posts, :loaded?
<ide> end
<ide>
<ide> def test_one
<ide> def test_one
<ide> assert ! posts.one? # Uses COUNT()
<ide> end
<ide>
<del> assert ! posts.loaded?
<add> assert_not_predicate posts, :loaded?
<ide>
<ide> assert_queries(1) do
<ide> assert ! posts.one? { |p| p.id < 3 }
<ide> assert posts.one? { |p| p.id == 1 }
<ide> end
<ide>
<del> assert posts.loaded?
<add> assert_predicate posts, :loaded?
<ide> end
<ide>
<ide> def test_to_a_should_dup_target
<ide> def test_create
<ide>
<ide> sparrow = birds.create
<ide> assert_kind_of Bird, sparrow
<del> assert !sparrow.persisted?
<add> assert_not_predicate sparrow, :persisted?
<ide>
<ide> hen = birds.where(name: "hen").create
<del> assert hen.persisted?
<add> assert_predicate hen, :persisted?
<ide> assert_equal "hen", hen.name
<ide> end
<ide>
<ide> def test_create_bang
<ide>
<ide> hen = birds.where(name: "hen").create!
<ide> assert_kind_of Bird, hen
<del> assert hen.persisted?
<add> assert_predicate hen, :persisted?
<ide> assert_equal "hen", hen.name
<ide> end
<ide>
<ide> def test_create_with_polymorphic_association
<ide> def test_first_or_create
<ide> parrot = Bird.where(color: "green").first_or_create(name: "parrot")
<ide> assert_kind_of Bird, parrot
<del> assert parrot.persisted?
<add> assert_predicate parrot, :persisted?
<ide> assert_equal "parrot", parrot.name
<ide> assert_equal "green", parrot.color
<ide>
<ide> same_parrot = Bird.where(color: "green").first_or_create(name: "parakeet")
<ide> assert_kind_of Bird, same_parrot
<del> assert same_parrot.persisted?
<add> assert_predicate same_parrot, :persisted?
<ide> assert_equal parrot, same_parrot
<ide> end
<ide>
<ide> def test_first_or_create_with_no_parameters
<ide> parrot = Bird.where(color: "green").first_or_create
<ide> assert_kind_of Bird, parrot
<del> assert !parrot.persisted?
<add> assert_not_predicate parrot, :persisted?
<ide> assert_equal "green", parrot.color
<ide> end
<ide>
<ide> def test_first_or_create_with_block
<ide> parrot = Bird.where(color: "green").first_or_create { |bird| bird.name = "parrot" }
<ide> assert_kind_of Bird, parrot
<del> assert parrot.persisted?
<add> assert_predicate parrot, :persisted?
<ide> assert_equal "green", parrot.color
<ide> assert_equal "parrot", parrot.name
<ide>
<ide> def test_first_or_create_with_array
<ide> def test_first_or_create_bang_with_valid_options
<ide> parrot = Bird.where(color: "green").first_or_create!(name: "parrot")
<ide> assert_kind_of Bird, parrot
<del> assert parrot.persisted?
<add> assert_predicate parrot, :persisted?
<ide> assert_equal "parrot", parrot.name
<ide> assert_equal "green", parrot.color
<ide>
<ide> same_parrot = Bird.where(color: "green").first_or_create!(name: "parakeet")
<ide> assert_kind_of Bird, same_parrot
<del> assert same_parrot.persisted?
<add> assert_predicate same_parrot, :persisted?
<ide> assert_equal parrot, same_parrot
<ide> end
<ide>
<ide> def test_first_or_create_bang_with_no_parameters
<ide> def test_first_or_create_bang_with_valid_block
<ide> parrot = Bird.where(color: "green").first_or_create! { |bird| bird.name = "parrot" }
<ide> assert_kind_of Bird, parrot
<del> assert parrot.persisted?
<add> assert_predicate parrot, :persisted?
<ide> assert_equal "green", parrot.color
<ide> assert_equal "parrot", parrot.name
<ide>
<ide> def test_first_or_create_with_invalid_array
<ide> def test_first_or_initialize
<ide> parrot = Bird.where(color: "green").first_or_initialize(name: "parrot")
<ide> assert_kind_of Bird, parrot
<del> assert !parrot.persisted?
<del> assert parrot.valid?
<del> assert parrot.new_record?
<add> assert_not_predicate parrot, :persisted?
<add> assert_predicate parrot, :valid?
<add> assert_predicate parrot, :new_record?
<ide> assert_equal "parrot", parrot.name
<ide> assert_equal "green", parrot.color
<ide> end
<ide>
<ide> def test_first_or_initialize_with_no_parameters
<ide> parrot = Bird.where(color: "green").first_or_initialize
<ide> assert_kind_of Bird, parrot
<del> assert !parrot.persisted?
<del> assert !parrot.valid?
<del> assert parrot.new_record?
<add> assert_not_predicate parrot, :persisted?
<add> assert_not_predicate parrot, :valid?
<add> assert_predicate parrot, :new_record?
<ide> assert_equal "green", parrot.color
<ide> end
<ide>
<ide> def test_first_or_initialize_with_block
<ide> parrot = Bird.where(color: "green").first_or_initialize { |bird| bird.name = "parrot" }
<ide> assert_kind_of Bird, parrot
<del> assert !parrot.persisted?
<del> assert parrot.valid?
<del> assert parrot.new_record?
<add> assert_not_predicate parrot, :persisted?
<add> assert_predicate parrot, :valid?
<add> assert_predicate parrot, :new_record?
<ide> assert_equal "green", parrot.color
<ide> assert_equal "parrot", parrot.name
<ide> end
<ide> def test_find_or_create_by
<ide> assert_nil Bird.find_by(name: "bob")
<ide>
<ide> bird = Bird.find_or_create_by(name: "bob")
<del> assert bird.persisted?
<add> assert_predicate bird, :persisted?
<ide>
<ide> assert_equal bird, Bird.find_or_create_by(name: "bob")
<ide> end
<ide> def test_find_or_create_by_with_create_with
<ide> assert_nil Bird.find_by(name: "bob")
<ide>
<ide> bird = Bird.create_with(color: "green").find_or_create_by(name: "bob")
<del> assert bird.persisted?
<add> assert_predicate bird, :persisted?
<ide> assert_equal "green", bird.color
<ide>
<ide> assert_equal bird, Bird.create_with(color: "blue").find_or_create_by(name: "bob")
<ide> def test_find_or_initialize_by
<ide> assert_nil Bird.find_by(name: "bob")
<ide>
<ide> bird = Bird.find_or_initialize_by(name: "bob")
<del> assert bird.new_record?
<add> assert_predicate bird, :new_record?
<ide> bird.save!
<ide>
<ide> assert_equal bird, Bird.find_or_initialize_by(name: "bob")
<ide> def test_distinct
<ide>
<ide> def test_doesnt_add_having_values_if_options_are_blank
<ide> scope = Post.having("")
<del> assert scope.having_clause.empty?
<add> assert_predicate scope.having_clause, :empty?
<ide>
<ide> scope = Post.having([])
<del> assert scope.having_clause.empty?
<add> assert_predicate scope.having_clause, :empty?
<ide> end
<ide>
<ide> def test_having_with_binds_for_both_where_and_having
<ide> def test_grouping_by_column_with_reserved_name
<ide>
<ide> def test_references_triggers_eager_loading
<ide> scope = Post.includes(:comments)
<del> assert !scope.eager_loading?
<del> assert scope.references(:comments).eager_loading?
<add> assert_not_predicate scope, :eager_loading?
<add> assert_predicate scope.references(:comments), :eager_loading?
<ide> end
<ide>
<ide> def test_references_doesnt_trigger_eager_loading_if_reference_not_included
<ide> scope = Post.references(:comments)
<del> assert !scope.eager_loading?
<add> assert_not_predicate scope, :eager_loading?
<ide> end
<ide>
<ide> def test_automatically_added_where_references
<ide> def test_presence
<ide> # count always trigger the COUNT query.
<ide> assert_queries(1) { topics.count }
<ide>
<del> assert topics.loaded?
<add> assert_predicate topics, :loaded?
<ide> end
<ide>
<ide> test "find_by with hash conditions returns the first matching record" do
<ide> def test_unscope_specific_where_value
<ide>
<ide> def test_locked_should_not_build_arel
<ide> posts = Post.locked
<del> assert posts.locked?
<add> assert_predicate posts, :locked?
<ide> assert_nothing_raised { posts.lock!(false) }
<ide> end
<ide>
<ide><path>activerecord/test/cases/reserved_word_test.rb
<ide> def test_has_and_belongs_to_many
<ide> end
<ide>
<ide> def test_activerecord_introspection
<del> assert Group.table_exists?
<add> assert_predicate Group, :table_exists?
<ide> assert_equal ["id", "order", "select_id"], Group.columns.map(&:name).sort
<ide> end
<ide>
<ide><path>activerecord/test/cases/scoping/default_scoping_test.rb
<ide> def test_unscope_errors_with_non_symbol_or_hash_arguments
<ide>
<ide> def test_unscope_merging
<ide> merged = Developer.where(name: "Jamis").merge(Developer.unscope(:where))
<del> assert merged.where_clause.empty?
<del> assert !merged.where(name: "Jon").where_clause.empty?
<add> assert_predicate merged.where_clause, :empty?
<add> assert_not_predicate merged.where(name: "Jon").where_clause, :empty?
<ide> end
<ide>
<ide> def test_order_in_default_scope_should_not_prevail
<ide><path>activerecord/test/cases/scoping/named_scoping_test.rb
<ide> class NamedScopingTest < ActiveRecord::TestCase
<ide> fixtures :posts, :authors, :topics, :comments, :author_addresses
<ide>
<ide> def test_implements_enumerable
<del> assert !Topic.all.empty?
<add> assert_not_predicate Topic.all, :empty?
<ide>
<ide> assert_equal Topic.all.to_a, Topic.base
<ide> assert_equal Topic.all.to_a, Topic.base.to_a
<ide> def test_reload_expires_cache_of_found_items
<ide> end
<ide>
<ide> def test_delegates_finds_and_calculations_to_the_base_class
<del> assert !Topic.all.empty?
<add> assert_not_predicate Topic.all, :empty?
<ide>
<ide> assert_equal Topic.all.to_a, Topic.base.to_a
<ide> assert_equal Topic.first, Topic.base.first
<ide> def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy
<ide> end
<ide>
<ide> def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified
<del> assert !Topic.all.merge!(where: { approved: true }).to_a.empty?
<add> assert_not_predicate Topic.all.merge!(where: { approved: true }).to_a, :empty?
<ide>
<ide> assert_equal Topic.all.merge!(where: { approved: true }).to_a, Topic.approved
<ide> assert_equal Topic.where(approved: true).count, Topic.approved.count
<ide> def test_scopes_are_composable
<ide> assert_equal((approved = Topic.all.merge!(where: { approved: true }).to_a), Topic.approved)
<ide> assert_equal((replied = Topic.all.merge!(where: "replies_count > 0").to_a), Topic.replied)
<ide> assert !(approved == replied)
<del> assert !(approved & replied).empty?
<add> assert_not_predicate (approved & replied), :empty?
<ide>
<ide> assert_equal approved & replied, Topic.approved.replied
<ide> end
<ide> def test_scope_with_object
<ide>
<ide> def test_has_many_associations_have_access_to_scopes
<ide> assert_not_equal Post.containing_the_letter_a, authors(:david).posts
<del> assert !Post.containing_the_letter_a.empty?
<add> assert_not_predicate Post.containing_the_letter_a, :empty?
<ide>
<ide> expected = authors(:david).posts & Post.containing_the_letter_a
<ide> assert_equal expected.sort_by(&:id), authors(:david).posts.containing_the_letter_a.sort_by(&:id)
<ide> def test_scope_with_STI
<ide>
<ide> def test_has_many_through_associations_have_access_to_scopes
<ide> assert_not_equal Comment.containing_the_letter_e, authors(:david).comments
<del> assert !Comment.containing_the_letter_e.empty?
<add> assert_not_predicate Comment.containing_the_letter_e, :empty?
<ide>
<ide> expected = authors(:david).comments & Comment.containing_the_letter_e
<ide> assert_equal expected.sort_by(&:id), authors(:david).comments.containing_the_letter_e.sort_by(&:id)
<ide> end
<ide>
<ide> def test_scopes_honor_current_scopes_from_when_defined
<del> assert !Post.ranked_by_comments.limit_by(5).empty?
<del> assert !authors(:david).posts.ranked_by_comments.limit_by(5).empty?
<add> assert_not_predicate Post.ranked_by_comments.limit_by(5), :empty?
<add> assert_not_predicate authors(:david).posts.ranked_by_comments.limit_by(5), :empty?
<ide> assert_not_equal Post.ranked_by_comments.limit_by(5), authors(:david).posts.ranked_by_comments.limit_by(5)
<ide> assert_not_equal Post.top(5), authors(:david).posts.top(5)
<ide> # Oracle sometimes sorts differently if WHERE condition is changed
<ide> def test_scopes_name_is_relation_method
<ide> end
<ide>
<ide> def test_active_records_have_scope_named__all__
<del> assert !Topic.all.empty?
<add> assert_not_predicate Topic.all, :empty?
<ide>
<ide> assert_equal Topic.all.to_a, Topic.base
<ide> end
<ide>
<ide> def test_active_records_have_scope_named__scoped__
<ide> scope = Topic.where("content LIKE '%Have%'")
<del> assert !scope.empty?
<add> assert_not_predicate scope, :empty?
<ide>
<ide> assert_equal scope, Topic.all.merge!(where: "content LIKE '%Have%'")
<ide> end
<ide> def test_any_should_not_fire_query_if_scope_loaded
<ide> end
<ide>
<ide> def test_model_class_should_respond_to_any
<del> assert Topic.any?
<add> assert_predicate Topic, :any?
<ide> Topic.delete_all
<del> assert !Topic.any?
<add> assert_not_predicate Topic, :any?
<ide> end
<ide>
<ide> def test_many_should_not_load_results
<ide> def test_many_should_not_fire_query_if_scope_loaded
<ide>
<ide> def test_many_should_return_false_if_none_or_one
<ide> topics = Topic.base.where(id: 0)
<del> assert !topics.many?
<add> assert_not_predicate topics, :many?
<ide> topics = Topic.base.where(id: 1)
<del> assert !topics.many?
<add> assert_not_predicate topics, :many?
<ide> end
<ide>
<ide> def test_many_should_return_true_if_more_than_one
<del> assert Topic.base.many?
<add> assert_predicate Topic.base, :many?
<ide> end
<ide>
<ide> def test_model_class_should_respond_to_many
<ide> Topic.delete_all
<del> assert !Topic.many?
<add> assert_not_predicate Topic, :many?
<ide> Topic.create!
<del> assert !Topic.many?
<add> assert_not_predicate Topic, :many?
<ide> Topic.create!
<del> assert Topic.many?
<add> assert_predicate Topic, :many?
<ide> end
<ide>
<ide> def test_should_build_on_top_of_scope
<ide> def test_chaining_with_duplicate_joins
<ide>
<ide> def test_chaining_applies_last_conditions_when_creating
<ide> post = Topic.rejected.new
<del> assert !post.approved?
<add> assert_not_predicate post, :approved?
<ide>
<ide> post = Topic.rejected.approved.new
<del> assert post.approved?
<add> assert_predicate post, :approved?
<ide>
<ide> post = Topic.approved.rejected.new
<del> assert !post.approved?
<add> assert_not_predicate post, :approved?
<ide>
<ide> post = Topic.approved.rejected.approved.new
<del> assert post.approved?
<add> assert_predicate post, :approved?
<ide> end
<ide>
<ide> def test_chaining_combines_conditions_when_searching
<ide> def test_scopes_on_relations
<ide> def test_index_on_scope
<ide> approved = Topic.approved.order("id ASC")
<ide> assert_equal topics(:second), approved[0]
<del> assert approved.loaded?
<add> assert_predicate approved, :loaded?
<ide> end
<ide>
<ide> def test_nested_scopes_queries_size
<ide> def test_model_class_should_respond_to_extending
<ide> end
<ide>
<ide> def test_model_class_should_respond_to_none
<del> assert !Topic.none?
<add> assert_not_predicate Topic, :none?
<ide> Topic.delete_all
<del> assert Topic.none?
<add> assert_predicate Topic, :none?
<ide> end
<ide>
<ide> def test_model_class_should_respond_to_one
<del> assert !Topic.one?
<add> assert_not_predicate Topic, :one?
<ide> Topic.delete_all
<del> assert !Topic.one?
<add> assert_not_predicate Topic, :one?
<ide> Topic.create!
<del> assert Topic.one?
<add> assert_predicate Topic, :one?
<ide> end
<ide> end
<ide><path>activerecord/test/cases/scoping/relation_scoping_test.rb
<ide> def test_delete_all_default_scope_filters_on_joins
<ide>
<ide> def test_current_scope_does_not_pollute_sibling_subclasses
<ide> Comment.none.scoping do
<del> assert_not SpecialComment.all.any?
<del> assert_not VerySpecialComment.all.any?
<del> assert_not SubSpecialComment.all.any?
<add> assert_not_predicate SpecialComment.all, :any?
<add> assert_not_predicate VerySpecialComment.all, :any?
<add> assert_not_predicate SubSpecialComment.all, :any?
<ide> end
<ide>
<ide> SpecialComment.none.scoping do
<del> assert Comment.all.any?
<del> assert VerySpecialComment.all.any?
<del> assert_not SubSpecialComment.all.any?
<add> assert_predicate Comment.all, :any?
<add> assert_predicate VerySpecialComment.all, :any?
<add> assert_not_predicate SubSpecialComment.all, :any?
<ide> end
<ide>
<ide> SubSpecialComment.none.scoping do
<del> assert Comment.all.any?
<del> assert VerySpecialComment.all.any?
<del> assert SpecialComment.all.any?
<add> assert_predicate Comment.all, :any?
<add> assert_predicate VerySpecialComment.all, :any?
<add> assert_predicate SpecialComment.all, :any?
<ide> end
<ide> end
<ide>
<ide> def test_nested_scoped_create
<ide> def test_nested_exclusive_scope_for_create
<ide> comment = Comment.create_with(body: "Hey guys, nested scopes are broken. Please fix!").scoping do
<ide> Comment.unscoped.create_with(post_id: 1).scoping do
<del> assert Comment.new.body.blank?
<add> assert_predicate Comment.new.body, :blank?
<ide> Comment.create body: "Hey guys"
<ide> end
<ide> end
<ide><path>activerecord/test/cases/serialized_attribute_test.rb
<ide> def test_nil_is_not_changed_when_serialized_with_a_class
<ide>
<ide> topic = Topic.new(content: nil)
<ide>
<del> assert_not topic.content_changed?
<add> assert_not_predicate topic, :content_changed?
<ide> end
<ide>
<ide> def test_classes_without_no_arg_constructors_are_not_supported
<ide> def deserialize(value)
<ide>
<ide> topic = model.create!(foo: "bar")
<ide> topic.foo
<del> assert_not topic.changed?
<add> assert_not_predicate topic, :changed?
<ide> end
<ide>
<ide> def test_serialized_attribute_works_under_concurrent_initial_access
<ide><path>activerecord/test/cases/store_test.rb
<ide> class StoreTest < ActiveRecord::TestCase
<ide>
<ide> test "updating the store will mark it as changed" do
<ide> @john.color = "red"
<del> assert @john.settings_changed?
<add> assert_predicate @john, :settings_changed?
<ide> end
<ide>
<ide> test "updating the store populates the changed array correctly" do
<ide> class StoreTest < ActiveRecord::TestCase
<ide>
<ide> test "updating the store won't mark it as changed if an attribute isn't changed" do
<ide> @john.color = @john.color
<del> assert !@john.settings_changed?
<add> assert_not_predicate @john, :settings_changed?
<ide> end
<ide>
<ide> test "object initialization with not nullable column" do
<ide> class StoreTest < ActiveRecord::TestCase
<ide>
<ide> test "updating the store will mark it as changed encoded with JSON" do
<ide> @john.height = "short"
<del> assert @john.json_data_changed?
<add> assert_predicate @john, :json_data_changed?
<ide> end
<ide>
<ide> test "object initialization with not nullable column encoded with JSON" do
<ide><path>activerecord/test/cases/timestamp_test.rb
<ide> def test_touching_a_record_without_timestamps_is_unexceptional
<ide>
<ide> def test_touching_a_no_touching_object
<ide> Developer.no_touching do
<del> assert @developer.no_touching?
<del> assert !@owner.no_touching?
<add> assert_predicate @developer, :no_touching?
<add> assert_not_predicate @owner, :no_touching?
<ide> @developer.touch
<ide> end
<ide>
<del> assert !@developer.no_touching?
<del> assert !@owner.no_touching?
<add> assert_not_predicate @developer, :no_touching?
<add> assert_not_predicate @owner, :no_touching?
<ide> assert_equal @previously_updated_at, @developer.updated_at
<ide> end
<ide>
<ide> def test_touching_related_objects
<ide>
<ide> def test_global_no_touching
<ide> ActiveRecord::Base.no_touching do
<del> assert @developer.no_touching?
<del> assert @owner.no_touching?
<add> assert_predicate @developer, :no_touching?
<add> assert_predicate @owner, :no_touching?
<ide> @developer.touch
<ide> end
<ide>
<del> assert !@developer.no_touching?
<del> assert !@owner.no_touching?
<add> assert_not_predicate @developer, :no_touching?
<add> assert_not_predicate @owner, :no_touching?
<ide> assert_equal @previously_updated_at, @developer.updated_at
<ide> end
<ide>
<ide> def test_no_touching_threadsafe
<ide> Thread.new do
<ide> Developer.no_touching do
<del> assert @developer.no_touching?
<add> assert_predicate @developer, :no_touching?
<ide>
<ide> sleep(1)
<ide> end
<ide> end
<ide>
<del> assert !@developer.no_touching?
<add> assert_not_predicate @developer, :no_touching?
<ide> end
<ide>
<ide> def test_no_touching_with_callbacks
<ide> def self.name; "Owner"; end
<ide> pet = Pet.new(owner: klass.new)
<ide> pet.save!
<ide>
<del> assert pet.owner.new_record?
<add> assert_predicate pet.owner, :new_record?
<ide> end
<ide>
<ide> def test_saving_a_record_with_a_belongs_to_that_specifies_touching_a_specific_attribute_the_parent_should_update_that_attribute
<ide><path>activerecord/test/cases/touch_later_test.rb
<ide> class TouchLaterTest < ActiveRecord::TestCase
<ide> def test_touch_laster_raise_if_non_persisted
<ide> invoice = Invoice.new
<ide> Invoice.transaction do
<del> assert_not invoice.persisted?
<add> assert_not_predicate invoice, :persisted?
<ide> assert_raises(ActiveRecord::ActiveRecordError) do
<ide> invoice.touch_later
<ide> end
<ide> def test_touch_laster_raise_if_non_persisted
<ide> def test_touch_later_dont_set_dirty_attributes
<ide> invoice = Invoice.create!
<ide> invoice.touch_later
<del> assert_not invoice.changed?
<add> assert_not_predicate invoice, :changed?
<ide> end
<ide>
<ide> def test_touch_later_respects_no_touching_policy
<ide><path>activerecord/test/cases/transaction_callbacks_test.rb
<ide> def test_only_call_after_commit_on_update_after_transaction_commits_for_existing
<ide>
<ide> def test_only_call_after_commit_on_top_level_transactions
<ide> @first.after_commit_block { |r| r.history << :after_commit }
<del> assert @first.history.empty?
<add> assert_predicate @first.history, :empty?
<ide>
<ide> @first.transaction do
<ide> @first.transaction(requires_new: true) do
<ide> @first.touch
<ide> end
<del> assert @first.history.empty?
<add> assert_predicate @first.history, :empty?
<ide> end
<ide> assert_equal [:after_commit], @first.history
<ide> end
<ide> def test_commit_does_not_run_transactions_callbacks_without_enrollment
<ide> @topic.content = "foo"
<ide> @topic.save!
<ide> end
<del> assert @topic.history.empty?
<add> assert_predicate @topic.history, :empty?
<ide> end
<ide>
<ide> def test_commit_run_transactions_callbacks_with_explicit_enrollment
<ide> def test_rollback_does_not_run_transactions_callbacks_without_enrollment
<ide> @topic.save!
<ide> raise ActiveRecord::Rollback
<ide> end
<del> assert @topic.history.empty?
<add> assert_predicate @topic.history, :empty?
<ide> end
<ide>
<ide> def test_rollback_run_transactions_callbacks_with_explicit_enrollment
<ide><path>activerecord/test/cases/transactions_test.rb
<ide> def setup
<ide>
<ide> def test_persisted_in_a_model_with_custom_primary_key_after_failed_save
<ide> movie = Movie.create
<del> assert !movie.persisted?
<add> assert_not_predicate movie, :persisted?
<ide> end
<ide>
<ide> def test_raise_after_destroy
<del> assert_not @first.frozen?
<add> assert_not_predicate @first, :frozen?
<ide>
<ide> assert_raises(RuntimeError) {
<ide> Topic.transaction do
<ide> @first.destroy
<del> assert @first.frozen?
<add> assert_predicate @first, :frozen?
<ide> raise
<ide> end
<ide> }
<ide>
<ide> assert @first.reload
<del> assert_not @first.frozen?
<add> assert_not_predicate @first, :frozen?
<ide> end
<ide>
<ide> def test_successful
<ide> def @first.after_save_for_transaction
<ide> @first.approved = true
<ide> e = assert_raises(RuntimeError) { @first.save }
<ide> assert_equal "Make the transaction rollback", e.message
<del> assert !Topic.find(1).approved?
<add> assert_not_predicate Topic.find(1), :approved?
<ide> end
<ide>
<ide> def test_rolling_back_in_a_callback_rollbacks_before_save
<ide> def test_transaction_state_is_cleared_when_record_is_persisted
<ide> author = Author.create! name: "foo"
<ide> author.name = nil
<ide> assert_not author.save
<del> assert_not author.new_record?
<add> assert_not_predicate author, :new_record?
<ide> end
<ide>
<ide> def test_update_should_rollback_on_failure
<ide> def test_force_savepoint_in_nested_transaction
<ide> end
<ide> end
<ide>
<del> assert @first.reload.approved?
<del> assert !@second.reload.approved?
<add> assert_predicate @first.reload, :approved?
<add> assert_not_predicate @second.reload, :approved?
<ide> end if Topic.connection.supports_savepoints?
<ide>
<ide> def test_force_savepoint_on_instance
<ide> def test_force_savepoint_on_instance
<ide> end
<ide> end
<ide>
<del> assert @first.reload.approved?
<del> assert !@second.reload.approved?
<add> assert_predicate @first.reload, :approved?
<add> assert_not_predicate @second.reload, :approved?
<ide> end if Topic.connection.supports_savepoints?
<ide>
<ide> def test_no_savepoint_in_nested_transaction_without_force
<ide> def test_no_savepoint_in_nested_transaction_without_force
<ide> end
<ide> end
<ide>
<del> assert !@first.reload.approved?
<del> assert !@second.reload.approved?
<add> assert_not_predicate @first.reload, :approved?
<add> assert_not_predicate @second.reload, :approved?
<ide> end if Topic.connection.supports_savepoints?
<ide>
<ide> def test_many_savepoints
<ide> def test_using_named_savepoints
<ide> @first.approved = false
<ide> @first.save!
<ide> Topic.connection.rollback_to_savepoint("first")
<del> assert @first.reload.approved?
<add> assert_predicate @first.reload, :approved?
<ide>
<ide> @first.approved = false
<ide> @first.save!
<ide> Topic.connection.release_savepoint("first")
<del> assert_not @first.reload.approved?
<add> assert_not_predicate @first.reload, :approved?
<ide> end
<ide> end if Topic.connection.supports_savepoints?
<ide>
<ide> def test_restore_frozen_state_after_double_destroy
<ide> raise ActiveRecord::Rollback
<ide> end
<ide>
<del> assert_not reply.frozen?
<del> assert_not topic.frozen?
<add> assert_not_predicate reply, :frozen?
<add> assert_not_predicate topic, :frozen?
<ide> end
<ide>
<ide> def test_restore_id_after_rollback
<ide> def test_transactions_state_from_rollback
<ide> connection = Topic.connection
<ide> transaction = ActiveRecord::ConnectionAdapters::TransactionManager.new(connection).begin_transaction
<ide>
<del> assert transaction.open?
<del> assert !transaction.state.rolledback?
<del> assert !transaction.state.committed?
<add> assert_predicate transaction, :open?
<add> assert_not_predicate transaction.state, :rolledback?
<add> assert_not_predicate transaction.state, :committed?
<ide>
<ide> transaction.rollback
<ide>
<del> assert transaction.state.rolledback?
<del> assert !transaction.state.committed?
<add> assert_predicate transaction.state, :rolledback?
<add> assert_not_predicate transaction.state, :committed?
<ide> end
<ide>
<ide> def test_transactions_state_from_commit
<ide> connection = Topic.connection
<ide> transaction = ActiveRecord::ConnectionAdapters::TransactionManager.new(connection).begin_transaction
<ide>
<del> assert transaction.open?
<del> assert !transaction.state.rolledback?
<del> assert !transaction.state.committed?
<add> assert_predicate transaction, :open?
<add> assert_not_predicate transaction.state, :rolledback?
<add> assert_not_predicate transaction.state, :committed?
<ide>
<ide> transaction.commit
<ide>
<del> assert !transaction.state.rolledback?
<del> assert transaction.state.committed?
<add> assert_not_predicate transaction.state, :rolledback?
<add> assert_predicate transaction.state, :committed?
<ide> end
<ide>
<ide> def test_set_state_method_is_deprecated
<ide> def test_automatic_savepoint_in_outer_transaction
<ide> raise
<ide> end
<ide> rescue
<del> assert !@first.reload.approved?
<add> assert_not_predicate @first.reload, :approved?
<ide> end
<ide> end
<ide>
<ide> def test_no_automatic_savepoint_for_inner_transaction
<ide> end
<ide> end
<ide>
<del> assert !@first.reload.approved?
<add> assert_not_predicate @first.reload, :approved?
<ide> end
<ide> end if Topic.connection.supports_savepoints?
<ide>
<ide><path>activerecord/test/cases/type/string_test.rb
<ide> class StringTypeTest < ActiveRecord::TestCase
<ide> klass.table_name = "authors"
<ide>
<ide> author = klass.create!(name: "Sean")
<del> assert_not author.changed?
<add> assert_not_predicate author, :changed?
<ide>
<ide> author.name << " Griffin"
<del> assert author.name_changed?
<add> assert_predicate author, :name_changed?
<ide>
<ide> author.save!
<ide> author.reload
<ide>
<ide> assert_equal "Sean Griffin", author.name
<del> assert_not author.changed?
<add> assert_not_predicate author, :changed?
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/validations/absence_validation_test.rb
<ide> def self.name; "Boy" end
<ide> validates_absence_of :name
<ide> end
<ide>
<del> assert boy_klass.new.valid?
<del> assert_not boy_klass.new(name: "Alex").valid?
<add> assert_predicate boy_klass.new, :valid?
<add> assert_not_predicate boy_klass.new(name: "Alex"), :valid?
<ide> end
<ide>
<ide> def test_has_one_marked_for_destruction
<ide> def self.name; "Boy" end
<ide> assert_not boy.valid?, "should not be valid if has_many association is present"
<ide>
<ide> i2.mark_for_destruction
<del> assert boy.valid?
<add> assert_predicate boy, :valid?
<ide> end
<ide>
<ide> def test_does_not_call_to_a_on_associations
<ide> def test_validates_absence_of_virtual_attribute_on_model
<ide> Interest.validates_absence_of(:token)
<ide>
<ide> interest = Interest.create!(topic: "Thought Leadering")
<del> assert interest.valid?
<add> assert_predicate interest, :valid?
<ide>
<ide> interest.token = "tl"
<ide>
<del> assert interest.invalid?
<add> assert_predicate interest, :invalid?
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/validations/association_validation_test.rb
<ide> def test_validates_associated_many
<ide> Reply.validates_presence_of(:content)
<ide> t = Topic.create("title" => "uhohuhoh", "content" => "whatever")
<ide> t.replies << [r = Reply.new("title" => "A reply"), r2 = Reply.new("title" => "Another reply", "content" => "non-empty"), r3 = Reply.new("title" => "Yet another reply"), r4 = Reply.new("title" => "The last reply", "content" => "non-empty")]
<del> assert !t.valid?
<del> assert t.errors[:replies].any?
<add> assert_not_predicate t, :valid?
<add> assert_predicate t.errors[:replies], :any?
<ide> assert_equal 1, r.errors.count # make sure all associated objects have been validated
<ide> assert_equal 0, r2.errors.count
<ide> assert_equal 1, r3.errors.count
<ide> assert_equal 0, r4.errors.count
<ide> r.content = r3.content = "non-empty"
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_associated_one
<ide> Reply.validates :topic, associated: true
<ide> Topic.validates_presence_of(:content)
<ide> r = Reply.new("title" => "A reply", "content" => "with content!")
<ide> r.topic = Topic.create("title" => "uhohuhoh")
<del> assert !r.valid?
<del> assert r.errors[:topic].any?
<add> assert_not_predicate r, :valid?
<add> assert_predicate r.errors[:topic], :any?
<ide> r.topic.content = "non-empty"
<del> assert r.valid?
<add> assert_predicate r, :valid?
<ide> end
<ide>
<ide> def test_validates_associated_marked_for_destruction
<ide> Topic.validates_associated(:replies)
<ide> Reply.validates_presence_of(:content)
<ide> t = Topic.new
<ide> t.replies << Reply.new
<del> assert t.invalid?
<add> assert_predicate t, :invalid?
<ide> t.replies.first.mark_for_destruction
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_associated_without_marked_for_destruction
<ide> def valid?
<ide> Topic.validates_associated(:replies)
<ide> t = Topic.new
<ide> t.define_singleton_method(:replies) { [reply.new] }
<del> assert t.valid?
<add> assert_predicate t, :valid?
<ide> end
<ide>
<ide> def test_validates_associated_with_custom_message_using_quotes
<ide> def test_validates_associated_with_custom_message_using_quotes
<ide> def test_validates_associated_missing
<ide> Reply.validates_presence_of(:topic)
<ide> r = Reply.create("title" => "A reply", "content" => "with content!")
<del> assert !r.valid?
<del> assert r.errors[:topic].any?
<add> assert_not_predicate r, :valid?
<add> assert_predicate r.errors[:topic], :any?
<ide>
<ide> r.topic = Topic.first
<del> assert r.valid?
<add> assert_predicate r, :valid?
<ide> end
<ide>
<ide> def test_validates_presence_of_belongs_to_association__parent_is_new_record
<ide><path>activerecord/test/cases/validations/length_validation_test.rb
<ide> def test_validates_size_of_association
<ide> assert_nothing_raised { @owner.validates_size_of :pets, minimum: 1 }
<ide> o = @owner.new("name" => "nopets")
<ide> assert !o.save
<del> assert o.errors[:pets].any?
<add> assert_predicate o.errors[:pets], :any?
<ide> o.pets.build("name" => "apet")
<del> assert o.valid?
<add> assert_predicate o, :valid?
<ide> end
<ide>
<ide> def test_validates_size_of_association_using_within
<ide> assert_nothing_raised { @owner.validates_size_of :pets, within: 1..2 }
<ide> o = @owner.new("name" => "nopets")
<ide> assert !o.save
<del> assert o.errors[:pets].any?
<add> assert_predicate o.errors[:pets], :any?
<ide>
<ide> o.pets.build("name" => "apet")
<del> assert o.valid?
<add> assert_predicate o, :valid?
<ide>
<ide> 2.times { o.pets.build("name" => "apet") }
<ide> assert !o.save
<del> assert o.errors[:pets].any?
<add> assert_predicate o.errors[:pets], :any?
<ide> end
<ide>
<ide> def test_validates_size_of_association_utf8
<ide> @owner.validates_size_of :pets, minimum: 1
<ide> o = @owner.new("name" => "あいうえおかきくけこ")
<ide> assert !o.save
<del> assert o.errors[:pets].any?
<add> assert_predicate o.errors[:pets], :any?
<ide> o.pets.build("name" => "あいうえおかきくけこ")
<del> assert o.valid?
<add> assert_predicate o, :valid?
<ide> end
<ide>
<ide> def test_validates_size_of_respects_records_marked_for_destruction
<ide> @owner.validates_size_of :pets, minimum: 1
<ide> owner = @owner.new
<ide> assert_not owner.save
<del> assert owner.errors[:pets].any?
<add> assert_predicate owner.errors[:pets], :any?
<ide> pet = owner.pets.build
<del> assert owner.valid?
<add> assert_predicate owner, :valid?
<ide> assert owner.save
<ide>
<ide> pet_count = Pet.count
<ide> assert_not owner.update_attributes pets_attributes: [ { _destroy: 1, id: pet.id } ]
<del> assert_not owner.valid?
<del> assert owner.errors[:pets].any?
<add> assert_not_predicate owner, :valid?
<add> assert_predicate owner.errors[:pets], :any?
<ide> assert_equal pet_count, Pet.count
<ide> end
<ide>
<ide> def test_validates_length_of_virtual_attribute_on_model
<ide>
<ide> pet = Pet.create!(name: "Fancy Pants", nickname: "Fancy")
<ide>
<del> assert pet.valid?
<add> assert_predicate pet, :valid?
<ide>
<ide> pet.nickname = ""
<ide>
<del> assert pet.invalid?
<add> assert_predicate pet, :invalid?
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/validations/presence_validation_test.rb
<ide> class Boy < Man; end
<ide> def test_validates_presence_of_non_association
<ide> Boy.validates_presence_of(:name)
<ide> b = Boy.new
<del> assert b.invalid?
<add> assert_predicate b, :invalid?
<ide>
<ide> b.name = "Alex"
<del> assert b.valid?
<add> assert_predicate b, :valid?
<ide> end
<ide>
<ide> def test_validates_presence_of_has_one
<ide> def test_validates_presence_of_has_one_marked_for_destruction
<ide> b = Boy.new
<ide> f = Face.new
<ide> b.face = f
<del> assert b.valid?
<add> assert_predicate b, :valid?
<ide>
<ide> f.mark_for_destruction
<del> assert b.invalid?
<add> assert_predicate b, :invalid?
<ide> end
<ide>
<ide> def test_validates_presence_of_has_many_marked_for_destruction
<ide> Boy.validates_presence_of(:interests)
<ide> b = Boy.new
<ide> b.interests << [i1 = Interest.new, i2 = Interest.new]
<del> assert b.valid?
<add> assert_predicate b, :valid?
<ide>
<ide> i1.mark_for_destruction
<del> assert b.valid?
<add> assert_predicate b, :valid?
<ide>
<ide> i2.mark_for_destruction
<del> assert b.invalid?
<add> assert_predicate b, :invalid?
<ide> end
<ide>
<ide> def test_validates_presence_doesnt_convert_to_array
<ide> def test_validates_presence_of_virtual_attribute_on_model
<ide> Interest.validates_presence_of(:abbreviation)
<ide>
<ide> interest = Interest.create!(topic: "Thought Leadering", abbreviation: "tl")
<del> assert interest.valid?
<add> assert_predicate interest, :valid?
<ide>
<ide> interest.abbreviation = ""
<ide>
<del> assert interest.invalid?
<add> assert_predicate interest, :invalid?
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/validations/uniqueness_validation_test.rb
<ide> def test_validate_uniqueness_with_alias_attribute
<ide> Topic.validates_uniqueness_of(:new_title)
<ide>
<ide> topic = Topic.new(new_title: "abc")
<del> assert topic.valid?
<add> assert_predicate topic, :valid?
<ide> end
<ide>
<ide> def test_validates_uniqueness_with_nil_value
<ide> def test_validates_uniqueness_with_validates
<ide> Topic.create!("title" => "abc")
<ide>
<ide> t2 = Topic.new("title" => "abc")
<del> assert !t2.valid?
<add> assert_not_predicate t2, :valid?
<ide> assert t2.errors[:title]
<ide> end
<ide>
<ide> def test_validate_case_insensitive_uniqueness
<ide> t2 = Topic.new("title" => "I'm UNIQUE!", :parent_id => 1)
<ide> assert !t2.valid?, "Shouldn't be valid"
<ide> assert !t2.save, "Shouldn't save t2 as unique"
<del> assert t2.errors[:title].any?
<del> assert t2.errors[:parent_id].any?
<add> assert_predicate t2.errors[:title], :any?
<add> assert_predicate t2.errors[:parent_id], :any?
<ide> assert_equal ["has already been taken"], t2.errors[:title]
<ide>
<ide> t2.title = "I'm truly UNIQUE!"
<ide> assert !t2.valid?, "Shouldn't be valid"
<ide> assert !t2.save, "Shouldn't save t2 as unique"
<del> assert t2.errors[:title].empty?
<del> assert t2.errors[:parent_id].any?
<add> assert_predicate t2.errors[:title], :empty?
<add> assert_predicate t2.errors[:parent_id], :any?
<ide>
<ide> t2.parent_id = 4
<ide> assert t2.save, "Should now save t2 as unique"
<ide> def test_validate_case_sensitive_uniqueness
<ide> t2 = Topic.new("title" => "I'M UNIQUE!")
<ide> assert t2.valid?, "Should be valid"
<ide> assert t2.save, "Should save t2 as unique"
<del> assert t2.errors[:title].empty?
<del> assert t2.errors[:parent_id].empty?
<add> assert_predicate t2.errors[:title], :empty?
<add> assert_predicate t2.errors[:parent_id], :empty?
<ide> assert_not_equal ["has already been taken"], t2.errors[:title]
<ide>
<ide> t3 = Topic.new("title" => "I'M uNiQUe!")
<ide> assert t3.valid?, "Should be valid"
<ide> assert t3.save, "Should save t2 as unique"
<del> assert t3.errors[:title].empty?
<del> assert t3.errors[:parent_id].empty?
<add> assert_predicate t3.errors[:title], :empty?
<add> assert_predicate t3.errors[:parent_id], :empty?
<ide> assert_not_equal ["has already been taken"], t3.errors[:title]
<ide> end
<ide>
<ide> def test_validate_case_sensitive_uniqueness_with_attribute_passed_as_integer
<ide> Topic.create!("title" => 101)
<ide>
<ide> t2 = Topic.new("title" => 101)
<del> assert !t2.valid?
<add> assert_not_predicate t2, :valid?
<ide> assert t2.errors[:title]
<ide> end
<ide>
<ide> def test_validates_uniqueness_inside_scoping
<ide> t1 = Topic.new("title" => "I'm unique!", "author_name" => "Mary")
<ide> assert t1.save
<ide> t2 = Topic.new("title" => "I'm unique!", "author_name" => "David")
<del> assert !t2.valid?
<add> assert_not_predicate t2, :valid?
<ide> end
<ide> end
<ide>
<ide> def test_validate_uniqueness_with_non_callable_conditions_is_not_supported
<ide>
<ide> def test_validate_uniqueness_on_existing_relation
<ide> event = Event.create
<del> assert TopicWithUniqEvent.create(event: event).valid?
<add> assert_predicate TopicWithUniqEvent.create(event: event), :valid?
<ide>
<ide> topic = TopicWithUniqEvent.new(event: event)
<del> assert_not topic.valid?
<add> assert_not_predicate topic, :valid?
<ide> assert_equal ["has already been taken"], topic.errors[:event]
<ide> end
<ide>
<ide> def test_validate_uniqueness_on_empty_relation
<ide> topic = TopicWithUniqEvent.new
<del> assert topic.valid?
<add> assert_predicate topic, :valid?
<ide> end
<ide>
<ide> def test_validate_uniqueness_of_custom_primary_key
<ide> def self.name
<ide> key2 = klass.create!(key_number: 11)
<ide>
<ide> key2.key_number = 10
<del> assert_not key2.valid?
<add> assert_not_predicate key2, :valid?
<ide> end
<ide>
<ide> def test_validate_uniqueness_without_primary_key
<ide> def self.name; "Dashboard" end
<ide> end
<ide>
<ide> abc = klass.create!(dashboard_id: "abc")
<del> assert klass.new(dashboard_id: "xyz").valid?
<del> assert_not klass.new(dashboard_id: "abc").valid?
<add> assert_predicate klass.new(dashboard_id: "xyz"), :valid?
<add> assert_not_predicate klass.new(dashboard_id: "abc"), :valid?
<ide>
<ide> abc.dashboard_id = "def"
<ide>
<ide> def test_validate_uniqueness_with_after_create_performing_save
<ide> assert topic.author_name.start_with?("Title1")
<ide>
<ide> topic2 = TopicWithAfterCreate.new(title: "Title1")
<del> assert_not topic2.valid?
<add> assert_not_predicate topic2, :valid?
<ide> assert_equal(["has already been taken"], topic2.errors[:title])
<ide> end
<ide>
<ide> def test_validate_uniqueness_regular_id
<ide> assert_empty item.errors
<ide>
<ide> item2 = CoolTopic.new(id: item.id, title: "MyItem2")
<del> assert_not item2.valid?
<add> assert_not_predicate item2, :valid?
<ide>
<ide> assert_equal(["has already been taken"], item2.errors[:id])
<ide> end
<ide><path>activerecord/test/cases/validations_test.rb
<ide> class ValidationsTest < ActiveRecord::TestCase
<ide> def test_valid_uses_create_context_when_new
<ide> r = WrongReply.new
<ide> r.title = "Wrong Create"
<del> assert_not r.valid?
<add> assert_not_predicate r, :valid?
<ide> assert r.errors[:title].any?, "A reply with a bad title should mark that attribute as invalid"
<ide> assert_equal ["is Wrong Create"], r.errors[:title], "A reply with a bad content should contain an error"
<ide> end
<ide> def test_validates_acceptance_of_with_non_existent_table
<ide>
<ide> def test_throw_away_typing
<ide> d = Developer.new("name" => "David", "salary" => "100,000")
<del> assert !d.valid?
<add> assert_not_predicate d, :valid?
<ide> assert_equal 100, d.salary
<ide> assert_equal "100,000", d.salary_before_type_cast
<ide> end
<ide> def test_numericality_validation_with_mutation
<ide> topic = klass.new(wibble: "123-4567")
<ide> topic.wibble.gsub!("-", "")
<ide>
<del> assert topic.valid?
<add> assert_predicate topic, :valid?
<ide> end
<ide>
<ide> def test_numericality_validation_checks_against_raw_value
<ide> def self.model_name
<ide> validates_numericality_of :wibble, greater_than_or_equal_to: BigDecimal("97.18")
<ide> end
<ide>
<del> assert_not klass.new(wibble: "97.179").valid?
<del> assert_not klass.new(wibble: 97.179).valid?
<del> assert_not klass.new(wibble: BigDecimal("97.179")).valid?
<add> assert_not_predicate klass.new(wibble: "97.179"), :valid?
<add> assert_not_predicate klass.new(wibble: 97.179), :valid?
<add> assert_not_predicate klass.new(wibble: BigDecimal("97.179")), :valid?
<ide> end
<ide>
<ide> def test_acceptance_validator_doesnt_require_db_connection
<ide><path>activerecord/test/cases/yaml_serialization_test.rb
<ide> def test_a_yaml_version_is_provided_for_future_backwards_compat
<ide> def test_deserializing_rails_41_yaml
<ide> topic = YAML.load(yaml_fixture("rails_4_1"))
<ide>
<del> assert topic.new_record?
<add> assert_predicate topic, :new_record?
<ide> assert_nil topic.id
<ide> assert_equal "The First Topic", topic.title
<ide> assert_equal({ omg: :lol }, topic.content)
<ide> def test_deserializing_rails_41_yaml
<ide> def test_deserializing_rails_4_2_0_yaml
<ide> topic = YAML.load(yaml_fixture("rails_4_2_0"))
<ide>
<del> assert_not topic.new_record?
<add> assert_not_predicate topic, :new_record?
<ide> assert_equal 1, topic.id
<ide> assert_equal "The First Topic", topic.title
<ide> assert_equal("Have a nice day", topic.content)
<ide><path>activestorage/test/controllers/previews_controller_test.rb
<ide> class ActiveStorage::PreviewsControllerTest < ActionDispatch::IntegrationTest
<ide> signed_blob_id: @blob.signed_id,
<ide> variation_key: ActiveStorage::Variation.encode(resize: "100x100"))
<ide>
<del> assert @blob.preview_image.attached?
<add> assert_predicate @blob.preview_image, :attached?
<ide> assert_redirected_to(/report\.png\?.*disposition=inline/)
<ide>
<ide> image = read_image(@blob.preview_image.variant(resize: "100x100"))
<ide><path>activestorage/test/models/attachments_test.rb
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> end
<ide> end
<ide>
<del> assert user.avatar.attached?
<add> assert_predicate user.avatar, :attached?
<ide> assert_equal "funky.jpg", user.avatar.filename.to_s
<ide>
<ide> assert_difference -> { ActiveStorage::Attachment.count }, +1 do
<ide> user.save!
<ide> end
<ide>
<del> assert user.reload.avatar.attached?
<add> assert_predicate user.reload.avatar, :attached?
<ide> assert_equal "funky.jpg", user.avatar.filename.to_s
<ide> end
<ide>
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> @user = User.new(name: "Jason", avatar: { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpg" })
<ide> end
<ide>
<del> assert @user.new_record?
<del> assert @user.avatar.attached?
<add> assert_predicate @user, :new_record?
<add> assert_predicate @user.avatar, :attached?
<ide> assert_equal "town.jpg", @user.avatar.filename.to_s
<ide>
<ide> @user.save!
<del> assert @user.reload.avatar.attached?
<add> assert_predicate @user.reload.avatar, :attached?
<ide> assert_equal "town.jpg", @user.avatar.filename.to_s
<ide> end
<ide>
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> @user.avatar.attach(blob)
<ide>
<ide> assert_equal "image/jpeg", @user.avatar.reload.content_type
<del> assert @user.avatar.identified?
<add> assert_predicate @user.avatar, :identified?
<ide> end
<ide>
<ide> test "identify newly-attached blob only once" do
<ide> blob = create_file_blob
<del> assert blob.identified?
<add> assert_predicate blob, :identified?
<ide>
<ide> # The blob's backing file is a PNG image. Fudge its content type so we can tell if it's identified when we attach it.
<ide> blob.update! content_type: "application/octet-stream"
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> @user.avatar.attach blob
<ide> end
<ide>
<del> assert blob.reload.analyzed?
<add> assert_predicate blob.reload, :analyzed?
<ide>
<ide> @user.avatar.detach
<ide>
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> avatar_key = @user.avatar.key
<ide>
<ide> @user.avatar.detach
<del> assert_not @user.avatar.attached?
<add> assert_not_predicate @user.avatar, :attached?
<ide> assert ActiveStorage::Blob.exists?(avatar_blob_id)
<ide> assert ActiveStorage::Blob.service.exist?(avatar_key)
<ide> end
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> avatar_key = @user.avatar.key
<ide>
<ide> @user.avatar.purge
<del> assert_not @user.avatar.attached?
<add> assert_not_predicate @user.avatar, :attached?
<ide> assert_not ActiveStorage::Blob.service.exist?(avatar_key)
<ide> end
<ide>
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> end
<ide> end
<ide>
<del> assert user.highlights.attached?
<add> assert_predicate user.highlights, :attached?
<ide> assert_equal "town.jpg", user.highlights.first.filename.to_s
<ide> assert_equal "country.jpg", user.highlights.second.filename.to_s
<ide>
<ide> assert_difference -> { ActiveStorage::Attachment.count }, +2 do
<ide> user.save!
<ide> end
<ide>
<del> assert user.reload.highlights.attached?
<add> assert_predicate user.reload.highlights, :attached?
<ide> assert_equal "town.jpg", user.highlights.first.filename.to_s
<ide> assert_equal "country.jpg", user.highlights.second.filename.to_s
<ide> end
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> { io: StringIO.new("IT"), filename: "country.jpg", content_type: "image/jpg" }])
<ide> end
<ide>
<del> assert @user.new_record?
<del> assert @user.highlights.attached?
<add> assert_predicate @user, :new_record?
<add> assert_predicate @user.highlights, :attached?
<ide> assert_equal "town.jpg", @user.highlights.first.filename.to_s
<ide> assert_equal "country.jpg", @user.highlights.second.filename.to_s
<ide>
<ide> @user.save!
<del> assert @user.reload.highlights.attached?
<add> assert_predicate @user.reload.highlights, :attached?
<ide> assert_equal "town.jpg", @user.highlights.first.filename.to_s
<ide> assert_equal "country.jpg", @user.highlights.second.filename.to_s
<ide> end
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> highlight_keys = @user.highlights.collect(&:key)
<ide>
<ide> @user.highlights.detach
<del> assert_not @user.highlights.attached?
<add> assert_not_predicate @user.highlights, :attached?
<ide>
<ide> assert ActiveStorage::Blob.exists?(highlight_blob_ids.first)
<ide> assert ActiveStorage::Blob.exists?(highlight_blob_ids.second)
<ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
<ide> highlight_keys = @user.highlights.collect(&:key)
<ide>
<ide> @user.highlights.purge
<del> assert_not @user.highlights.attached?
<add> assert_not_predicate @user.highlights, :attached?
<ide> assert_not ActiveStorage::Blob.service.exist?(highlight_keys.first)
<ide> assert_not ActiveStorage::Blob.service.exist?(highlight_keys.second)
<ide> end
<ide><path>activestorage/test/models/blob_test.rb
<ide> class ActiveStorage::BlobTest < ActiveSupport::TestCase
<ide>
<ide> test "text?" do
<ide> blob = create_blob data: "Hello world!"
<del> assert blob.text?
<del> assert_not blob.audio?
<add> assert_predicate blob, :text?
<add> assert_not_predicate blob, :audio?
<ide> end
<ide>
<ide> test "download yields chunks" do
<ide><path>activestorage/test/models/preview_test.rb
<ide> class ActiveStorage::PreviewTest < ActiveSupport::TestCase
<ide> blob = create_file_blob(filename: "report.pdf", content_type: "application/pdf")
<ide> preview = blob.preview(resize: "640x280").processed
<ide>
<del> assert preview.image.attached?
<add> assert_predicate preview.image, :attached?
<ide> assert_equal "report.png", preview.image.filename.to_s
<ide> assert_equal "image/png", preview.image.content_type
<ide>
<ide> class ActiveStorage::PreviewTest < ActiveSupport::TestCase
<ide> blob = create_file_blob(filename: "video.mp4", content_type: "video/mp4")
<ide> preview = blob.preview(resize: "640x280").processed
<ide>
<del> assert preview.image.attached?
<add> assert_predicate preview.image, :attached?
<ide> assert_equal "video.png", preview.image.filename.to_s
<ide> assert_equal "image/png", preview.image.content_type
<ide>
<ide><path>activestorage/test/service/mirror_service_test.rb
<ide> def upload(data, to:)
<ide> SecureRandom.base58(24).tap do |key|
<ide> io = StringIO.new(data).tap(&:read)
<ide> @service.upload key, io, checksum: Digest::MD5.base64digest(data)
<del> assert io.eof?
<add> assert_predicate io, :eof?
<ide> end
<ide> end
<ide> end
<ide><path>activestorage/test/template/image_tag_test.rb
<ide> class ActiveStorage::ImageTagTest < ActionView::TestCase
<ide> test "error when attachment's empty" do
<ide> @user = User.create!(name: "DHH")
<ide>
<del> assert_not @user.avatar.attached?
<add> assert_not_predicate @user.avatar, :attached?
<ide> assert_raises(ArgumentError) { image_tag(@user.avatar) }
<ide> end
<ide>
<ide><path>activesupport/test/array_inquirer_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_individual
<del> assert @array_inquirer.mobile?
<del> assert @array_inquirer.tablet?
<del> assert_not @array_inquirer.desktop?
<add> assert_predicate @array_inquirer, :mobile?
<add> assert_predicate @array_inquirer, :tablet?
<add> assert_not_predicate @array_inquirer, :desktop?
<ide> end
<ide>
<ide> def test_any
<ide><path>activesupport/test/benchmarkable_test.rb
<ide> def setup
<ide>
<ide> def test_without_block
<ide> assert_raise(LocalJumpError) { benchmark }
<del> assert buffer.empty?
<add> assert_predicate buffer, :empty?
<ide> end
<ide>
<ide> def test_defaults
<ide><path>activesupport/test/cache/cache_store_logger_test.rb
<ide> def setup
<ide>
<ide> def test_logging
<ide> @cache.fetch("foo") { "bar" }
<del> assert @buffer.string.present?
<add> assert_predicate @buffer.string, :present?
<ide> end
<ide>
<ide> def test_log_with_string_namespace
<ide> def test_log_with_proc_namespace
<ide>
<ide> def test_mute_logging
<ide> @cache.mute { @cache.fetch("foo") { "bar" } }
<del> assert @buffer.string.blank?
<add> assert_predicate @buffer.string, :blank?
<ide> end
<ide> end
<ide><path>activesupport/test/cache/stores/file_store_test.rb
<ide> def test_delete_does_not_delete_empty_parent_dir
<ide> end
<ide> assert File.exist?(cache_dir), "Parent of top level cache dir was deleted!"
<ide> assert File.exist?(sub_cache_dir), "Top level cache dir was deleted!"
<del> assert Dir.entries(sub_cache_dir).reject { |f| ActiveSupport::Cache::FileStore::EXCLUDED_DIRS.include?(f) }.empty?
<add> assert_predicate Dir.entries(sub_cache_dir).reject { |f| ActiveSupport::Cache::FileStore::EXCLUDED_DIRS.include?(f) }, :empty?
<ide> end
<ide>
<ide> def test_log_exception_when_cache_read_fails
<ide> File.stub(:exist?, -> { raise StandardError.new("failed") }) do
<ide> @cache.send(:read_entry, "winston", {})
<del> assert @buffer.string.present?
<add> assert_predicate @buffer.string, :present?
<ide> end
<ide> end
<ide>
<ide><path>activesupport/test/callback_inheritance_test.rb
<ide> def test_crazy_mix_off
<ide> class DynamicInheritedCallbacks < ActiveSupport::TestCase
<ide> def test_callbacks_looks_to_the_superclass_before_running
<ide> child = EmptyChild.new.dispatch
<del> assert !child.performed?
<add> assert_not_predicate child, :performed?
<ide> EmptyParent.set_callback :dispatch, :before, :perform!
<ide> child = EmptyChild.new.dispatch
<del> assert child.performed?
<add> assert_predicate child, :performed?
<ide> end
<ide>
<ide> def test_callbacks_should_be_performed_once_in_child_class
<ide><path>activesupport/test/class_cache_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_empty?
<del> assert @cache.empty?
<add> assert_predicate @cache, :empty?
<ide> @cache.store(ClassCacheTest)
<del> assert !@cache.empty?
<add> assert_not_predicate @cache, :empty?
<ide> end
<ide>
<ide> def test_clear!
<del> assert @cache.empty?
<add> assert_predicate @cache, :empty?
<ide> @cache.store(ClassCacheTest)
<del> assert !@cache.empty?
<add> assert_not_predicate @cache, :empty?
<ide> @cache.clear!
<del> assert @cache.empty?
<add> assert_predicate @cache, :empty?
<ide> end
<ide>
<ide> def test_set_key
<ide> def test_get_with_name
<ide> end
<ide>
<ide> def test_get_constantizes
<del> assert @cache.empty?
<add> assert_predicate @cache, :empty?
<ide> assert_equal ClassCacheTest, @cache.get(ClassCacheTest.name)
<ide> end
<ide>
<ide> def test_get_constantizes_fails_on_invalid_names
<del> assert @cache.empty?
<add> assert_predicate @cache, :empty?
<ide> assert_raise NameError do
<ide> @cache.get("OmgTotallyInvalidConstantName")
<ide> end
<ide> end
<ide>
<ide> def test_get_alias
<del> assert @cache.empty?
<add> assert_predicate @cache, :empty?
<ide> assert_equal @cache[ClassCacheTest.name], @cache.get(ClassCacheTest.name)
<ide> end
<ide>
<ide> def test_safe_get_constantizes
<del> assert @cache.empty?
<add> assert_predicate @cache, :empty?
<ide> assert_equal ClassCacheTest, @cache.safe_get(ClassCacheTest.name)
<ide> end
<ide>
<ide> def test_safe_get_constantizes_doesnt_fail_on_invalid_names
<del> assert @cache.empty?
<add> assert_predicate @cache, :empty?
<ide> assert_nil @cache.safe_get("OmgTotallyInvalidConstantName")
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/date_and_time_behavior.rb
<ide> def test_sunday_with_default_beginning_of_week_set
<ide> end
<ide>
<ide> def test_on_weekend_on_saturday
<del> assert date_time_init(2015, 1, 3, 0, 0, 0).on_weekend?
<del> assert date_time_init(2015, 1, 3, 15, 15, 10).on_weekend?
<add> assert_predicate date_time_init(2015, 1, 3, 0, 0, 0), :on_weekend?
<add> assert_predicate date_time_init(2015, 1, 3, 15, 15, 10), :on_weekend?
<ide> end
<ide>
<ide> def test_on_weekend_on_sunday
<del> assert date_time_init(2015, 1, 4, 0, 0, 0).on_weekend?
<del> assert date_time_init(2015, 1, 4, 15, 15, 10).on_weekend?
<add> assert_predicate date_time_init(2015, 1, 4, 0, 0, 0), :on_weekend?
<add> assert_predicate date_time_init(2015, 1, 4, 15, 15, 10), :on_weekend?
<ide> end
<ide>
<ide> def test_on_weekend_on_monday
<del> assert_not date_time_init(2015, 1, 5, 0, 0, 0).on_weekend?
<del> assert_not date_time_init(2015, 1, 5, 15, 15, 10).on_weekend?
<add> assert_not_predicate date_time_init(2015, 1, 5, 0, 0, 0), :on_weekend?
<add> assert_not_predicate date_time_init(2015, 1, 5, 15, 15, 10), :on_weekend?
<ide> end
<ide>
<ide> def test_on_weekday_on_sunday
<del> assert_not date_time_init(2015, 1, 4, 0, 0, 0).on_weekday?
<del> assert_not date_time_init(2015, 1, 4, 15, 15, 10).on_weekday?
<add> assert_not_predicate date_time_init(2015, 1, 4, 0, 0, 0), :on_weekday?
<add> assert_not_predicate date_time_init(2015, 1, 4, 15, 15, 10), :on_weekday?
<ide> end
<ide>
<ide> def test_on_weekday_on_monday
<del> assert date_time_init(2015, 1, 5, 0, 0, 0).on_weekday?
<del> assert date_time_init(2015, 1, 5, 15, 15, 10).on_weekday?
<add> assert_predicate date_time_init(2015, 1, 5, 0, 0, 0), :on_weekday?
<add> assert_predicate date_time_init(2015, 1, 5, 15, 15, 10), :on_weekday?
<ide> end
<ide>
<ide> def with_bw_default(bw = :monday)
<ide><path>activesupport/test/core_ext/date_ext_test.rb
<ide> def test_date_advance_should_not_change_passed_options_hash
<ide>
<ide> class DateExtBehaviorTest < ActiveSupport::TestCase
<ide> def test_date_acts_like_date
<del> assert Date.new.acts_like_date?
<add> assert_predicate Date.new, :acts_like_date?
<ide> end
<ide>
<ide> def test_blank?
<del> assert_not Date.new.blank?
<add> assert_not_predicate Date.new, :blank?
<ide> end
<ide>
<ide> def test_freeze_doesnt_clobber_memoized_instance_methods
<ide><path>activesupport/test/core_ext/date_time_ext_test.rb
<ide> def test_current_with_time_zone
<ide> end
<ide>
<ide> def test_acts_like_date
<del> assert DateTime.new.acts_like_date?
<add> assert_predicate DateTime.new, :acts_like_date?
<ide> end
<ide>
<ide> def test_acts_like_time
<del> assert DateTime.new.acts_like_time?
<add> assert_predicate DateTime.new, :acts_like_time?
<ide> end
<ide>
<ide> def test_blank?
<del> assert_not DateTime.new.blank?
<add> assert_not_predicate DateTime.new, :blank?
<ide> end
<ide>
<ide> def test_utc?
<ide><path>activesupport/test/core_ext/hash_ext_test.rb
<ide> def test_datetime_xml_type_with_utc_time
<ide> </alert>
<ide> XML
<ide> alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
<del> assert alert_at.utc?
<add> assert_predicate alert_at, :utc?
<ide> assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
<ide> end
<ide>
<ide> def test_datetime_xml_type_with_non_utc_time
<ide> </alert>
<ide> XML
<ide> alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
<del> assert alert_at.utc?
<add> assert_predicate alert_at, :utc?
<ide> assert_equal Time.utc(2008, 2, 10, 15, 30, 45), alert_at
<ide> end
<ide>
<ide> def test_datetime_xml_type_with_far_future_date
<ide> </alert>
<ide> XML
<ide> alert_at = Hash.from_xml(alert_xml)["alert"]["alert_at"]
<del> assert alert_at.utc?
<add> assert_predicate alert_at, :utc?
<ide> assert_equal 2050, alert_at.year
<ide> assert_equal 2, alert_at.month
<ide> assert_equal 10, alert_at.day
<ide><path>activesupport/test/core_ext/module/anonymous_test.rb
<ide>
<ide> class AnonymousTest < ActiveSupport::TestCase
<ide> test "an anonymous class or module are anonymous" do
<del> assert Module.new.anonymous?
<del> assert Class.new.anonymous?
<add> assert_predicate Module.new, :anonymous?
<add> assert_predicate Class.new, :anonymous?
<ide> end
<ide>
<ide> test "a named class or module are not anonymous" do
<del> assert !Kernel.anonymous?
<del> assert !Object.anonymous?
<add> assert_not_predicate Kernel, :anonymous?
<add> assert_not_predicate Object, :anonymous?
<ide> end
<ide> end
<ide><path>activesupport/test/core_ext/module/attribute_aliasing_test.rb
<ide> class AttributeAliasingTest < ActiveSupport::TestCase
<ide> def test_attribute_alias
<ide> e = AttributeAliasing::Email.new
<ide>
<del> assert !e.subject?
<add> assert_not_predicate e, :subject?
<ide>
<ide> e.title = "Upgrade computer"
<ide> assert_equal "Upgrade computer", e.subject
<del> assert e.subject?
<add> assert_predicate e, :subject?
<ide>
<ide> e.subject = "We got a long way to go"
<ide> assert_equal "We got a long way to go", e.title
<del> assert e.title?
<add> assert_predicate e, :title?
<ide> end
<ide>
<ide> def test_aliasing_to_uppercase_attributes
<ide> def test_aliasing_to_uppercase_attributes
<ide> # to more sensible ones, everything goes *foof*.
<ide> e = AttributeAliasing::Email.new
<ide>
<del> assert !e.body?
<del> assert !e.Data?
<add> assert_not_predicate e, :body?
<add> assert_not_predicate e, :Data?
<ide>
<ide> e.body = "No, really, this is not a joke."
<ide> assert_equal "No, really, this is not a joke.", e.Data
<del> assert e.Data?
<add> assert_predicate e, :Data?
<ide>
<ide> e.Data = "Uppercased methods are the suck"
<ide> assert_equal "Uppercased methods are the suck", e.body
<del> assert e.body?
<add> assert_predicate e, :body?
<ide> end
<ide> end
<ide><path>activesupport/test/core_ext/module/reachable_test.rb
<ide> class AnonymousTest < ActiveSupport::TestCase
<ide> test "an anonymous class or module is not reachable" do
<ide> assert_deprecated do
<del> assert !Module.new.reachable?
<del> assert !Class.new.reachable?
<add> assert_not_predicate Module.new, :reachable?
<add> assert_not_predicate Class.new, :reachable?
<ide> end
<ide> end
<ide>
<ide> test "ordinary named classes or modules are reachable" do
<ide> assert_deprecated do
<del> assert Kernel.reachable?
<del> assert Object.reachable?
<add> assert_predicate Kernel, :reachable?
<add> assert_predicate Object, :reachable?
<ide> end
<ide> end
<ide>
<ide> class AnonymousTest < ActiveSupport::TestCase
<ide> self.class.send(:remove_const, :M)
<ide>
<ide> assert_deprecated do
<del> assert !c.reachable?
<del> assert !m.reachable?
<add> assert_not_predicate c, :reachable?
<add> assert_not_predicate m, :reachable?
<ide> end
<ide> end
<ide>
<ide> class AnonymousTest < ActiveSupport::TestCase
<ide> eval "module M; end"
<ide>
<ide> assert_deprecated do
<del> assert C.reachable?
<del> assert M.reachable?
<del> assert !c.reachable?
<del> assert !m.reachable?
<add> assert_predicate C, :reachable?
<add> assert_predicate M, :reachable?
<add> assert_not_predicate c, :reachable?
<add> assert_not_predicate m, :reachable?
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/test/core_ext/module_test.rb
<ide> def test_delegation_doesnt_mask_nested_no_method_error_on_nil_receiver
<ide>
<ide> def test_delegation_with_method_arguments
<ide> has_block = HasBlock.new(Block.new)
<del> assert has_block.hello?
<add> assert_predicate has_block, :hello?
<ide> end
<ide>
<ide> def test_delegate_missing_to_with_method
<ide><path>activesupport/test/core_ext/string_ext_test.rb
<ide> def test_string_squish
<ide> end
<ide>
<ide> def test_string_inquiry
<del> assert "production".inquiry.production?
<del> assert !"production".inquiry.development?
<add> assert_predicate "production".inquiry, :production?
<add> assert_not_predicate "production".inquiry, :development?
<ide> end
<ide>
<ide> def test_truncate
<ide> def test_truncate_multibyte
<ide> end
<ide>
<ide> def test_truncate_should_not_be_html_safe
<del> assert !"Hello World!".truncate(12).html_safe?
<add> assert_not_predicate "Hello World!".truncate(12), :html_safe?
<ide> end
<ide>
<ide> def test_remove
<ide> def test_string_to_date
<ide>
<ide> class StringBehaviourTest < ActiveSupport::TestCase
<ide> def test_acts_like_string
<del> assert "Bambi".acts_like_string?
<add> assert_predicate "Bambi", :acts_like_string?
<ide> end
<ide> end
<ide>
<ide> def test_core_ext_adds_mb_chars
<ide> end
<ide>
<ide> def test_string_should_recognize_utf8_strings
<del> assert UTF8_STRING.is_utf8?
<del> assert ASCII_STRING.is_utf8?
<del> assert !EUC_JP_STRING.is_utf8?
<del> assert !INVALID_UTF8_STRING.is_utf8?
<add> assert_predicate UTF8_STRING, :is_utf8?
<add> assert_predicate ASCII_STRING, :is_utf8?
<add> assert_not_predicate EUC_JP_STRING, :is_utf8?
<add> assert_not_predicate INVALID_UTF8_STRING, :is_utf8?
<ide> end
<ide>
<ide> def test_mb_chars_returns_instance_of_proxy_class
<ide> def to_s
<ide> end
<ide>
<ide> test "A string is unsafe by default" do
<del> assert !@string.html_safe?
<add> assert_not_predicate @string, :html_safe?
<ide> end
<ide>
<ide> test "A string can be marked safe" do
<ide> string = @string.html_safe
<del> assert string.html_safe?
<add> assert_predicate string, :html_safe?
<ide> end
<ide>
<ide> test "Marking a string safe returns the string" do
<ide> assert_equal @string, @string.html_safe
<ide> end
<ide>
<ide> test "An integer is safe by default" do
<del> assert 5.html_safe?
<add> assert_predicate 5, :html_safe?
<ide> end
<ide>
<ide> test "a float is safe by default" do
<del> assert 5.7.html_safe?
<add> assert_predicate 5.7, :html_safe?
<ide> end
<ide>
<ide> test "An object is unsafe by default" do
<del> assert !@object.html_safe?
<add> assert_not_predicate @object, :html_safe?
<ide> end
<ide>
<ide> test "Adding an object to a safe string returns a safe string" do
<ide> string = @string.html_safe
<ide> string << @object
<ide>
<ide> assert_equal "helloother", string
<del> assert string.html_safe?
<add> assert_predicate string, :html_safe?
<ide> end
<ide>
<ide> test "Adding a safe string to another safe string returns a safe string" do
<ide> def to_s
<ide> @combination = @other_string + string
<ide>
<ide> assert_equal "otherhello", @combination
<del> assert @combination.html_safe?
<add> assert_predicate @combination, :html_safe?
<ide> end
<ide>
<ide> test "Adding an unsafe string to a safe string escapes it and returns a safe string" do
<ide> def to_s
<ide> assert_equal "other<foo>", @combination
<ide> assert_equal "hello<foo>", @other_combination
<ide>
<del> assert @combination.html_safe?
<del> assert !@other_combination.html_safe?
<add> assert_predicate @combination, :html_safe?
<add> assert_not_predicate @other_combination, :html_safe?
<ide> end
<ide>
<ide> test "Prepending safe onto unsafe yields unsafe" do
<ide> @string.prepend "other".html_safe
<del> assert !@string.html_safe?
<add> assert_not_predicate @string, :html_safe?
<ide> assert_equal "otherhello", @string
<ide> end
<ide>
<ide> test "Prepending unsafe onto safe yields escaped safe" do
<ide> other = "other".html_safe
<ide> other.prepend "<foo>"
<del> assert other.html_safe?
<add> assert_predicate other, :html_safe?
<ide> assert_equal "<foo>other", other
<ide> end
<ide>
<ide> def to_s
<ide>
<ide> string = @string.html_safe
<ide> @other_string.concat(string)
<del> assert !@other_string.html_safe?
<add> assert_not_predicate @other_string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting unsafe onto safe yields escaped safe" do
<ide> @other_string = "other".html_safe
<ide> string = @other_string.concat("<foo>")
<ide> assert_equal "other<foo>", string
<del> assert string.html_safe?
<add> assert_predicate string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting safe onto safe yields safe" do
<ide> @other_string = "other".html_safe
<ide> string = @string.html_safe
<ide>
<ide> @other_string.concat(string)
<del> assert @other_string.html_safe?
<add> assert_predicate @other_string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting safe onto unsafe with << yields unsafe" do
<ide> @other_string = "other".dup
<ide> string = @string.html_safe
<ide>
<ide> @other_string << string
<del> assert !@other_string.html_safe?
<add> assert_not_predicate @other_string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting unsafe onto safe with << yields escaped safe" do
<ide> @other_string = "other".html_safe
<ide> string = @other_string << "<foo>"
<ide> assert_equal "other<foo>", string
<del> assert string.html_safe?
<add> assert_predicate string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting safe onto safe with << yields safe" do
<ide> @other_string = "other".html_safe
<ide> string = @string.html_safe
<ide>
<ide> @other_string << string
<del> assert @other_string.html_safe?
<add> assert_predicate @other_string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting safe onto unsafe with % yields unsafe" do
<ide> @other_string = "other%s"
<ide> string = @string.html_safe
<ide>
<ide> @other_string = @other_string % string
<del> assert !@other_string.html_safe?
<add> assert_not_predicate @other_string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting unsafe onto safe with % yields escaped safe" do
<ide> @other_string = "other%s".html_safe
<ide> string = @other_string % "<foo>"
<ide>
<ide> assert_equal "other<foo>", string
<del> assert string.html_safe?
<add> assert_predicate string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting safe onto safe with % yields safe" do
<ide> @other_string = "other%s".html_safe
<ide> string = @string.html_safe
<ide>
<ide> @other_string = @other_string % string
<del> assert @other_string.html_safe?
<add> assert_predicate @other_string, :html_safe?
<ide> end
<ide>
<ide> test "Concatting with % doesn't modify a string" do
<ide> def to_s
<ide> string = @string.html_safe
<ide> string = string.concat(13)
<ide> assert_equal "hello".dup.concat(13), string
<del> assert string.html_safe?
<add> assert_predicate string, :html_safe?
<ide> end
<ide>
<ide> test "emits normal string yaml" do
<ide> def to_s
<ide>
<ide> test "call to_param returns a normal string" do
<ide> string = @string.html_safe
<del> assert string.html_safe?
<del> assert !string.to_param.html_safe?
<add> assert_predicate string, :html_safe?
<add> assert_not_predicate string.to_param, :html_safe?
<ide> end
<ide>
<ide> test "ERB::Util.html_escape should escape unsafe characters" do
<ide><path>activesupport/test/core_ext/time_ext_test.rb
<ide> def test_future_with_time_current_as_time_with_zone
<ide> end
<ide>
<ide> def test_acts_like_time
<del> assert Time.new.acts_like_time?
<add> assert_predicate Time.new, :acts_like_time?
<ide> end
<ide>
<ide> def test_formatted_offset_with_utc
<ide> def test_time_created_with_local_constructor_cannot_represent_times_during_hour_
<ide> # On Apr 2 2006 at 2:00AM in US, clocks were moved forward to 3:00AM.
<ide> # Therefore, 2AM EST doesn't exist for this date; Time.local fails over to 3:00AM EDT
<ide> assert_equal Time.local(2006, 4, 2, 3), Time.local(2006, 4, 2, 2)
<del> assert Time.local(2006, 4, 2, 2).dst?
<add> assert_predicate Time.local(2006, 4, 2, 2), :dst?
<ide> end
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/time_with_zone_test.rb
<ide> def test_to_datetime
<ide> end
<ide>
<ide> def test_acts_like_time
<del> assert @twz.acts_like_time?
<add> assert_predicate @twz, :acts_like_time?
<ide> assert @twz.acts_like?(:time)
<ide> assert ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone).acts_like?(:time)
<ide> end
<ide> def test_acts_like_date
<ide> end
<ide>
<ide> def test_blank?
<del> assert_not @twz.blank?
<add> assert_not_predicate @twz, :blank?
<ide> end
<ide>
<ide> def test_is_a
<ide> def test_marshal_dump_and_load
<ide> marshal_str = Marshal.dump(@twz)
<ide> mtime = Marshal.load(marshal_str)
<ide> assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
<del> assert mtime.utc.utc?
<add> assert_predicate mtime.utc, :utc?
<ide> assert_equal ActiveSupport::TimeZone["Eastern Time (US & Canada)"], mtime.time_zone
<ide> assert_equal Time.utc(1999, 12, 31, 19), mtime.time
<del> assert mtime.time.utc?
<add> assert_predicate mtime.time, :utc?
<ide> assert_equal @twz.inspect, mtime.inspect
<ide> end
<ide>
<ide> def test_marshal_dump_and_load_with_tzinfo_identifier
<ide> marshal_str = Marshal.dump(twz)
<ide> mtime = Marshal.load(marshal_str)
<ide> assert_equal Time.utc(2000, 1, 1, 0), mtime.utc
<del> assert mtime.utc.utc?
<add> assert_predicate mtime.utc, :utc?
<ide> assert_equal "America/New_York", mtime.time_zone.name
<ide> assert_equal Time.utc(1999, 12, 31, 19), mtime.time
<del> assert mtime.time.utc?
<add> assert_predicate mtime.time, :utc?
<ide> assert_equal @twz.inspect, mtime.inspect
<ide> end
<ide>
<ide> def test_freeze
<ide> @twz.freeze
<del> assert @twz.frozen?
<add> assert_predicate @twz, :frozen?
<ide> end
<ide>
<ide> def test_freeze_preloads_instance_variables
<ide><path>activesupport/test/deprecation_test.rb
<ide> def test_default_silence_behavior
<ide> stderr_output = capture(:stderr) {
<ide> assert_nil behavior.call("Some error!", ["call stack!"], "horizon", "gem")
<ide> }
<del> assert stderr_output.empty?
<add> assert_predicate stderr_output, :empty?
<ide> end
<ide>
<ide> def test_default_notify_behavior
<ide><path>activesupport/test/descendants_tracker_test_cases.rb
<ide> def test_clear
<ide> mark_as_autoloaded(*ALL) do
<ide> ActiveSupport::DescendantsTracker.clear
<ide> ALL.each do |k|
<del> assert ActiveSupport::DescendantsTracker.descendants(k).empty?
<add> assert_predicate ActiveSupport::DescendantsTracker.descendants(k), :empty?
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/test/descendants_tracker_with_autoloading_test.rb
<ide> def test_clear_with_autoloaded_parent_children_and_grandchildren
<ide> mark_as_autoloaded(*ALL) do
<ide> ActiveSupport::DescendantsTracker.clear
<ide> ALL.each do |k|
<del> assert ActiveSupport::DescendantsTracker.descendants(k).empty?
<add> assert_predicate ActiveSupport::DescendantsTracker.descendants(k), :empty?
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/test/evented_file_update_checker_test.rb
<ide> def touch(files)
<ide> FileUtils.touch(tmpfiles)
<ide>
<ide> checker = new_checker(tmpfiles) {}
<del> assert !checker.updated?
<add> assert_not_predicate checker, :updated?
<ide>
<ide> # Pipes used for flow control across fork.
<ide> boot_reader, boot_writer = IO.pipe
<ide> touch_reader, touch_writer = IO.pipe
<ide>
<ide> pid = fork do
<del> assert checker.updated?
<add> assert_predicate checker, :updated?
<ide>
<ide> # Clear previous check value.
<ide> checker.execute
<del> assert !checker.updated?
<add> assert_not_predicate checker, :updated?
<ide>
<ide> # Fork is booted, ready for file to be touched
<ide> # notify parent process.
<ide> def touch(files)
<ide> # has been touched.
<ide> IO.select([touch_reader])
<ide>
<del> assert checker.updated?
<add> assert_predicate checker, :updated?
<ide> end
<ide>
<ide> assert pid
<ide> def touch(files)
<ide> # Notify fork that files have been touched.
<ide> touch_writer.write("touched")
<ide>
<del> assert checker.updated?
<add> assert_predicate checker, :updated?
<ide>
<ide> Process.wait(pid)
<ide> end
<ide><path>activesupport/test/file_update_checker_shared_tests.rb
<ide> def run(*args)
<ide> i = 0
<ide>
<ide> checker = new_checker(tmpfiles) { i += 1 }
<del> assert !checker.updated?
<add> assert_not_predicate checker, :updated?
<ide>
<ide> touch(tmpfiles)
<ide> wait
<ide>
<del> assert checker.updated?
<add> assert_predicate checker, :updated?
<ide> end
<ide>
<ide> test "updated should become true when watched files are modified" do
<ide> def run(*args)
<ide> FileUtils.touch(tmpfiles)
<ide>
<ide> checker = new_checker(tmpfiles) { i += 1 }
<del> assert !checker.updated?
<add> assert_not_predicate checker, :updated?
<ide>
<ide> touch(tmpfiles)
<ide> wait
<ide>
<del> assert checker.updated?
<add> assert_predicate checker, :updated?
<ide> end
<ide>
<ide> test "updated should become true when watched files are deleted" do
<ide> def run(*args)
<ide> FileUtils.touch(tmpfiles)
<ide>
<ide> checker = new_checker(tmpfiles) { i += 1 }
<del> assert !checker.updated?
<add> assert_not_predicate checker, :updated?
<ide>
<ide> rm_f(tmpfiles)
<ide> wait
<ide>
<del> assert checker.updated?
<add> assert_predicate checker, :updated?
<ide> end
<ide>
<ide> test "should be robust to handle files with wrong modified time" do
<ide> def run(*args)
<ide> i = 0
<ide>
<ide> checker = new_checker(tmpfiles) { i += 1 }
<del> assert !checker.updated?
<add> assert_not_predicate checker, :updated?
<ide>
<ide> touch(tmpfiles)
<ide> wait
<ide>
<del> assert checker.updated?
<add> assert_predicate checker, :updated?
<ide> checker.execute
<del> assert !checker.updated?
<add> assert_not_predicate checker, :updated?
<ide> end
<ide>
<ide> test "should execute the block if files change in a watched directory one extension" do
<ide><path>activesupport/test/inflector_test.rb
<ide> def test_inflector_locality
<ide>
<ide> ActiveSupport::Inflector.inflections(:es) { |inflect| inflect.clear }
<ide>
<del> assert ActiveSupport::Inflector.inflections(:es).plurals.empty?
<del> assert ActiveSupport::Inflector.inflections(:es).singulars.empty?
<del> assert ActiveSupport::Inflector.inflections(:es).uncountables.empty?
<del> assert !ActiveSupport::Inflector.inflections.plurals.empty?
<del> assert !ActiveSupport::Inflector.inflections.singulars.empty?
<del> assert !ActiveSupport::Inflector.inflections.uncountables.empty?
<add> assert_predicate ActiveSupport::Inflector.inflections(:es).plurals, :empty?
<add> assert_predicate ActiveSupport::Inflector.inflections(:es).singulars, :empty?
<add> assert_predicate ActiveSupport::Inflector.inflections(:es).uncountables, :empty?
<add> assert_not_predicate ActiveSupport::Inflector.inflections.plurals, :empty?
<add> assert_not_predicate ActiveSupport::Inflector.inflections.singulars, :empty?
<add> assert_not_predicate ActiveSupport::Inflector.inflections.uncountables, :empty?
<ide> end
<ide>
<ide> def test_clear_all
<ide> def test_clear_all
<ide>
<ide> inflect.clear :all
<ide>
<del> assert inflect.plurals.empty?
<del> assert inflect.singulars.empty?
<del> assert inflect.uncountables.empty?
<del> assert inflect.humans.empty?
<add> assert_predicate inflect.plurals, :empty?
<add> assert_predicate inflect.singulars, :empty?
<add> assert_predicate inflect.uncountables, :empty?
<add> assert_predicate inflect.humans, :empty?
<ide> end
<ide> end
<ide>
<ide> def test_clear_with_default
<ide>
<ide> inflect.clear
<ide>
<del> assert inflect.plurals.empty?
<del> assert inflect.singulars.empty?
<del> assert inflect.uncountables.empty?
<del> assert inflect.humans.empty?
<add> assert_predicate inflect.plurals, :empty?
<add> assert_predicate inflect.singulars, :empty?
<add> assert_predicate inflect.uncountables, :empty?
<add> assert_predicate inflect.humans, :empty?
<ide> end
<ide> end
<ide>
<ide><path>activesupport/test/multibyte_chars_test.rb
<ide> def test_method_works_for_proxyed_methods
<ide> end
<ide>
<ide> def test_acts_like_string
<del> assert "Bambi".mb_chars.acts_like_string?
<add> assert_predicate "Bambi".mb_chars, :acts_like_string?
<ide> end
<ide> end
<ide>
<ide><path>activesupport/test/safe_buffer_test.rb
<ide> def test_titleize
<ide> end
<ide>
<ide> test "Should be considered safe" do
<del> assert @buffer.html_safe?
<add> assert_predicate @buffer, :html_safe?
<ide> end
<ide>
<ide> test "Should return a safe buffer when calling to_s" do
<ide> def test_titleize
<ide> test "Should not return safe buffer from gsub" do
<ide> altered_buffer = @buffer.gsub("", "asdf")
<ide> assert_equal "asdf", altered_buffer
<del> assert !altered_buffer.html_safe?
<add> assert_not_predicate altered_buffer, :html_safe?
<ide> end
<ide>
<ide> test "Should not return safe buffer from gsub!" do
<ide> @buffer.gsub!("", "asdf")
<ide> assert_equal "asdf", @buffer
<del> assert !@buffer.html_safe?
<add> assert_not_predicate @buffer, :html_safe?
<ide> end
<ide>
<ide> test "Should escape dirty buffers on add" do
<ide> def test_titleize
<ide>
<ide> test "Should preserve html_safe? status on copy" do
<ide> @buffer.gsub!("", "<>")
<del> assert !@buffer.dup.html_safe?
<add> assert_not_predicate @buffer.dup, :html_safe?
<ide> end
<ide>
<ide> test "Should return safe buffer when added with another safe buffer" do
<ide> clean = "<script>".html_safe
<ide> result_buffer = @buffer + clean
<del> assert result_buffer.html_safe?
<add> assert_predicate result_buffer, :html_safe?
<ide> assert_equal "<script>", result_buffer
<ide> end
<ide>
<ide> def test_titleize
<ide> end
<ide>
<ide> test "clone_empty keeps the original dirtyness" do
<del> assert @buffer.clone_empty.html_safe?
<del> assert !@buffer.gsub!("", "").clone_empty.html_safe?
<add> assert_predicate @buffer.clone_empty, :html_safe?
<add> assert_not_predicate @buffer.gsub!("", "").clone_empty, :html_safe?
<ide> end
<ide>
<ide> test "Should be safe when sliced if original value was safe" do
<ide><path>activesupport/test/string_inquirer_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_match
<del> assert @string_inquirer.production?
<add> assert_predicate @string_inquirer, :production?
<ide> end
<ide>
<ide> def test_miss
<del> assert_not @string_inquirer.development?
<add> assert_not_predicate @string_inquirer, :development?
<ide> end
<ide>
<ide> def test_missing_question_mark
<ide><path>railties/test/application/configuration_test.rb
<ide> def restore_default_config
<ide>
<ide> with_rails_env "development" do
<ide> app "development"
<del> assert Rails.application.config.log_tags.blank?
<add> assert_predicate Rails.application.config.log_tags, :blank?
<ide> end
<ide> end
<ide>
<ide><path>railties/test/application/initializers/frameworks_test.rb
<ide> def show
<ide> ActiveRecord::Base.connection
<ide> RUBY
<ide> require "#{app_path}/config/environment"
<del> assert !ActiveRecord::Base.connection_pool.active_connection?
<add> assert_not_predicate ActiveRecord::Base.connection_pool, :active_connection?
<ide> end
<ide> end
<ide> end
<ide><path>railties/test/application/loading_test.rb
<ide> def show
<ide> def test_initialize_can_be_called_at_any_time
<ide> require "#{app_path}/config/application"
<ide>
<del> assert !Rails.initialized?
<del> assert !Rails.application.initialized?
<add> assert_not_predicate Rails, :initialized?
<add> assert_not_predicate Rails.application, :initialized?
<ide> Rails.initialize!
<del> assert Rails.initialized?
<del> assert Rails.application.initialized?
<add> assert_predicate Rails, :initialized?
<add> assert_predicate Rails.application, :initialized?
<ide> end
<ide>
<ide> private
<ide><path>railties/test/application/mailer_previews_test.rb
<ide> def foo
<ide> test "mailer preview not found" do
<ide> app("development")
<ide> get "/rails/mailers/notifier"
<del> assert last_response.not_found?
<add> assert_predicate last_response, :not_found?
<ide> assert_match "Mailer preview 'notifier' not found", last_response.body
<ide> end
<ide>
<ide> def foo
<ide> app("development")
<ide>
<ide> get "/rails/mailers/notifier/bar"
<del> assert last_response.not_found?
<add> assert_predicate last_response, :not_found?
<ide> assert_match "Email 'bar' not found in NotifierPreview", last_response.body
<ide> end
<ide>
<ide> def foo
<ide> app("development")
<ide>
<ide> get "/rails/mailers/notifier/foo?part=text%2Fhtml"
<del> assert last_response.not_found?
<add> assert_predicate last_response, :not_found?
<ide> assert_match "Email part 'text/html' not found in NotifierPreview#foo", last_response.body
<ide> end
<ide>
<ide><path>railties/test/application/runner_test.rb
<ide> def test_default_environment
<ide>
<ide> def test_runner_detects_syntax_errors
<ide> output = rails("runner", "puts 'hello world", allow_failure: true)
<del> assert_not $?.success?
<add> assert_not_predicate $?, :success?
<ide> assert_match "unterminated string meets end of file", output
<ide> end
<ide>
<ide> def test_runner_detects_bad_script_name
<ide> output = rails("runner", "iuiqwiourowe", allow_failure: true)
<del> assert_not $?.success?
<add> assert_not_predicate $?, :success?
<ide> assert_match "undefined local variable or method `iuiqwiourowe' for", output
<ide> end
<ide>
<ide><path>railties/test/commands/console_test.rb
<ide> def self.start
<ide>
<ide> def test_sandbox_option
<ide> console = Rails::Console.new(app, parse_arguments(["--sandbox"]))
<del> assert console.sandbox?
<add> assert_predicate console, :sandbox?
<ide> end
<ide>
<ide> def test_short_version_of_sandbox_option
<ide> console = Rails::Console.new(app, parse_arguments(["-s"]))
<del> assert console.sandbox?
<add> assert_predicate console, :sandbox?
<ide> end
<ide>
<ide> def test_no_options
<ide> console = Rails::Console.new(app, parse_arguments([]))
<del> assert !console.sandbox?
<add> assert_not_predicate console, :sandbox?
<ide> end
<ide>
<ide> def test_start
<ide> start
<ide>
<del> assert app.console.started?
<add> assert_predicate app.console, :started?
<ide> assert_match(/Loading \w+ environment \(Rails/, output)
<ide> end
<ide>
<ide> def test_start_with_sandbox
<ide> start ["--sandbox"]
<ide>
<del> assert app.console.started?
<add> assert_predicate app.console, :started?
<ide> assert app.sandbox
<ide> assert_match(/Loading \w+ environment in sandbox \(Rails/, output)
<ide> end
<ide><path>railties/test/engine_test.rb
<ide> def initialize(*args)
<ide> end
<ide> end
<ide>
<del> assert !engine.routes?
<add> assert_not_predicate engine, :routes?
<ide> end
<ide>
<ide> def test_application_can_be_subclassed
<ide><path>railties/test/generators/create_migration_test.rb
<ide> def test_invoke_when_exists_identical
<ide> create_migration
<ide>
<ide> assert_match(/identical db\/migrate\/1_create_articles\.rb\n/, invoke!)
<del> assert @migration.identical?
<add> assert_predicate @migration, :identical?
<ide> end
<ide>
<ide> def test_invoke_when_exists_not_identical
<ide><path>railties/test/generators/generated_attribute_test.rb
<ide> def test_human_name
<ide>
<ide> def test_reference_is_true
<ide> %w(references belongs_to).each do |attribute_type|
<del> assert create_generated_attribute(attribute_type).reference?
<add> assert_predicate create_generated_attribute(attribute_type), :reference?
<ide> end
<ide> end
<ide>
<ide> def test_reference_is_false
<ide> %w(foo bar baz).each do |attribute_type|
<del> assert !create_generated_attribute(attribute_type).reference?
<add> assert_not_predicate create_generated_attribute(attribute_type), :reference?
<ide> end
<ide> end
<ide>
<ide> def test_polymorphic_reference_is_true
<ide> %w(references belongs_to).each do |attribute_type|
<del> assert create_generated_attribute("#{attribute_type}{polymorphic}").polymorphic?
<add> assert_predicate create_generated_attribute("#{attribute_type}{polymorphic}"), :polymorphic?
<ide> end
<ide> end
<ide>
<ide> def test_polymorphic_reference_is_false
<ide> %w(foo bar baz).each do |attribute_type|
<del> assert !create_generated_attribute("#{attribute_type}{polymorphic}").polymorphic?
<add> assert_not_predicate create_generated_attribute("#{attribute_type}{polymorphic}"), :polymorphic?
<ide> end
<ide> end
<ide>
<ide> def test_parse_required_attribute_with_index
<ide> att = Rails::Generators::GeneratedAttribute.parse("supplier:references{required}:index")
<ide> assert_equal "supplier", att.name
<ide> assert_equal :references, att.type
<del> assert att.has_index?
<del> assert att.required?
<add> assert_predicate att, :has_index?
<add> assert_predicate att, :required?
<ide> end
<ide> end
<ide><path>railties/test/generators_test.rb
<ide> def test_should_give_higher_preference_to_rails_generators
<ide> assert File.exist?(File.join(@path, "generators", "model_generator.rb"))
<ide> assert_called_with(Rails::Generators::ModelGenerator, :start, [["Account"], {}]) do
<ide> warnings = capture(:stderr) { Rails::Generators.invoke :model, ["Account"] }
<del> assert warnings.empty?
<add> assert_predicate warnings, :empty?
<ide> end
<ide> end
<ide>
<ide><path>railties/test/paths_test.rb
<ide> def setup
<ide> File.stub(:exist?, true) do
<ide> @root.add "app", with: "/app"
<ide> @root["app"].autoload_once!
<del> assert @root["app"].autoload_once?
<add> assert_predicate @root["app"], :autoload_once?
<ide> assert_includes @root.autoload_once, @root["app"].expanded.first
<ide> end
<ide> end
<ide>
<ide> test "it is possible to remove a path that should be autoloaded only once" do
<ide> @root["app"] = "/app"
<ide> @root["app"].autoload_once!
<del> assert @root["app"].autoload_once?
<add> assert_predicate @root["app"], :autoload_once?
<ide>
<ide> @root["app"].skip_autoload_once!
<del> assert !@root["app"].autoload_once?
<add> assert_not_predicate @root["app"], :autoload_once?
<ide> assert_not_includes @root.autoload_once, @root["app"].expanded.first
<ide> end
<ide>
<ide> test "it is possible to add a path without assignment and specify it should be loaded only once" do
<ide> File.stub(:exist?, true) do
<ide> @root.add "app", with: "/app", autoload_once: true
<del> assert @root["app"].autoload_once?
<add> assert_predicate @root["app"], :autoload_once?
<ide> assert_includes @root.autoload_once, "/app"
<ide> end
<ide> end
<ide>
<ide> test "it is possible to add multiple paths without assignment and specify it should be loaded only once" do
<ide> File.stub(:exist?, true) do
<ide> @root.add "app", with: ["/app", "/app2"], autoload_once: true
<del> assert @root["app"].autoload_once?
<add> assert_predicate @root["app"], :autoload_once?
<ide> assert_includes @root.autoload_once, "/app"
<ide> assert_includes @root.autoload_once, "/app2"
<ide> end
<ide> def setup
<ide> File.stub(:exist?, true) do
<ide> @root["app"] = "/app"
<ide> @root["app"].eager_load!
<del> assert @root["app"].eager_load?
<add> assert_predicate @root["app"], :eager_load?
<ide> assert_includes @root.eager_load, @root["app"].to_a.first
<ide> end
<ide> end
<ide>
<ide> test "it is possible to skip a path from eager loading" do
<ide> @root["app"] = "/app"
<ide> @root["app"].eager_load!
<del> assert @root["app"].eager_load?
<add> assert_predicate @root["app"], :eager_load?
<ide>
<ide> @root["app"].skip_eager_load!
<del> assert !@root["app"].eager_load?
<add> assert_not_predicate @root["app"], :eager_load?
<ide> assert_not_includes @root.eager_load, @root["app"].to_a.first
<ide> end
<ide>
<ide> test "it is possible to add a path without assignment and mark it as eager" do
<ide> File.stub(:exist?, true) do
<ide> @root.add "app", with: "/app", eager_load: true
<del> assert @root["app"].eager_load?
<add> assert_predicate @root["app"], :eager_load?
<ide> assert_includes @root.eager_load, "/app"
<ide> end
<ide> end
<ide>
<ide> test "it is possible to add multiple paths without assignment and mark them as eager" do
<ide> File.stub(:exist?, true) do
<ide> @root.add "app", with: ["/app", "/app2"], eager_load: true
<del> assert @root["app"].eager_load?
<add> assert_predicate @root["app"], :eager_load?
<ide> assert_includes @root.eager_load, "/app"
<ide> assert_includes @root.eager_load, "/app2"
<ide> end
<ide> def setup
<ide> test "it is possible to create a path without assignment and mark it both as eager and load once" do
<ide> File.stub(:exist?, true) do
<ide> @root.add "app", with: "/app", eager_load: true, autoload_once: true
<del> assert @root["app"].eager_load?
<del> assert @root["app"].autoload_once?
<add> assert_predicate @root["app"], :eager_load?
<add> assert_predicate @root["app"], :autoload_once?
<ide> assert_includes @root.eager_load, "/app"
<ide> assert_includes @root.autoload_once, "/app"
<ide> end
<ide> def setup
<ide> test "a path can be added to the load path on creation" do
<ide> File.stub(:exist?, true) do
<ide> @root.add "app", with: "/app", load_path: true
<del> assert @root["app"].load_path?
<add> assert_predicate @root["app"], :load_path?
<ide> assert_equal ["/app"], @root.load_paths
<ide> end
<ide> end
<ide> def setup
<ide> test "a path can be marked as autoload on creation" do
<ide> File.stub(:exist?, true) do
<ide> @root.add "app", with: "/app", autoload: true
<del> assert @root["app"].autoload?
<add> assert_predicate @root["app"], :autoload?
<ide> assert_equal ["/app"], @root.autoload_paths
<ide> end
<ide> end | 209 |
Text | Text | replace u+2018 and u+2019 with u+0027 in manpages | 19c43a69156ba70c5fa11a7cc55ecbd82f8d9421 | <ide><path>man/docker-events.1.md
<ide> Docker networks report the following events:
<ide>
<ide> The `--since` and `--until` parameters can be Unix timestamps, date formatted
<ide> timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed
<del>relative to the client machine’s time. If you do not provide the `--since` option,
<add>relative to the client machine's time. If you do not provide the `--since` option,
<ide> the command returns only new and/or live events. Supported formats for date
<ide> formatted time stamps include RFC3339Nano, RFC3339, `2006-01-02T15:04:05`,
<ide> `2006-01-02T15:04:05.999999999`, `2006-01-02Z07:00`, and `2006-01-02`. The local
<ide><path>man/docker-logs.1.md
<ide> any logs at the time you execute docker logs).
<ide>
<ide> The **docker logs --follow** command combines commands **docker logs** and
<ide> **docker attach**. It will first return all logs from the beginning and
<del>then continue streaming new output from the container’s stdout and stderr.
<add>then continue streaming new output from the container's stdout and stderr.
<ide>
<ide> **Warning**: This command works only for the **json-file** or **journald**
<ide> logging drivers.
<ide> logging drivers.
<ide> Output the specified number of lines at the end of logs (defaults to all logs)
<ide>
<ide> The `--since` option can be Unix timestamps, date formatted timestamps, or Go
<del>duration strings (e.g. `10m`, `1h30m`) computed relative to the client machine’s
<add>duration strings (e.g. `10m`, `1h30m`) computed relative to the client machine's
<ide> time. Supported formats for date formatted time stamps include RFC3339Nano,
<ide> RFC3339, `2006-01-02T15:04:05`, `2006-01-02T15:04:05.999999999`,
<ide> `2006-01-02Z07:00`, and `2006-01-02`. The local timezone on the client will be
<ide><path>man/docker-run.1.md
<ide> pull** IMAGE, before it starts the container from that image.
<ide>
<ide> In foreground mode (the default when **-d**
<ide> is not specified), **docker run** can start the process in the container
<del>and attach the console to the process’s standard input, output, and standard
<add>and attach the console to the process's standard input, output, and standard
<ide> error. It can even pretend to be a TTY (this is what most commandline
<ide> executables expect) and pass along signals. The **-a** option can be set for
<ide> each of stdin, stdout, and stderr.
<ide> This should list the message sent to logger.
<ide>
<ide> If you do not specify -a then Docker will attach everything (stdin,stdout,stderr)
<ide> . You can specify to which of the three standard streams (stdin, stdout, stderr)
<del>you’d like to connect instead, as in:
<add>you'd like to connect instead, as in:
<ide>
<ide> # docker run -a stdin -a stdout -i -t fedora /bin/bash
<ide>
<ide> If a container is connected to the default bridge network and `linked`
<ide> with other containers, then the container's `/etc/hosts` file is updated
<ide> with the linked container's name.
<ide>
<del>> **Note** Since Docker may live update the container’s `/etc/hosts` file, there
<add>> **Note** Since Docker may live update the container's `/etc/hosts` file, there
<ide> may be situations when processes inside the container can end up reading an
<ide> empty or incomplete `/etc/hosts` file. In most cases, retrying the read again
<ide> should fix the problem. | 3 |
Javascript | Javascript | change the execution order | 41173de77b04ec9b659dc59d6b448556147a410e | <ide><path>benchmark/compare.js
<ide> if (benchmarks.length === 0) {
<ide> // Create queue from the benchmarks list such both node versions are tested
<ide> // `runs` amount of times each.
<ide> const queue = [];
<del>for (let iter = 0; iter < runs; iter++) {
<del> for (const filename of benchmarks) {
<add>for (const filename of benchmarks) {
<add> for (let iter = 0; iter < runs; iter++) {
<ide> for (const binary of binaries) {
<ide> queue.push({ binary, filename, iter });
<ide> } | 1 |
PHP | PHP | rename a few things | 75393db929a43a6b56a85bdc65a4f607f77efcd8 | <ide><path>app/Http/Controllers/Auth/AuthController.php
<ide> <?php namespace App\Http\Controllers\Auth;
<ide>
<del>use Illuminate\Contracts\Auth\Authenticator;
<add>use Illuminate\Contracts\Auth\Guard;
<ide>
<ide> use App\Http\Requests\Auth\LoginRequest;
<ide> use App\Http\Requests\Auth\RegisterRequest;
<ide> class AuthController {
<ide>
<ide> /**
<del> * The authenticator implementation.
<add> * The Guard implementation.
<ide> *
<del> * @var Authenticator
<add> * @var Guard
<ide> */
<ide> protected $auth;
<ide>
<ide> /**
<ide> * Create a new authentication controller instance.
<ide> *
<del> * @param Authenticator $auth
<add> * @param Guard $auth
<ide> * @return void
<ide> */
<del> public function __construct(Authenticator $auth)
<add> public function __construct(Guard $auth)
<ide> {
<ide> $this->auth = $auth;
<ide> }
<ide><path>app/Http/Middleware/AuthMiddleware.php
<ide> <?php namespace App\Http\Middleware;
<ide>
<ide> use Closure;
<del>use Illuminate\Contracts\Auth\Authenticator;
<add>use Illuminate\Contracts\Auth\Guard;
<ide> use Illuminate\Contracts\Routing\Middleware;
<ide> use Illuminate\Contracts\Routing\ResponseFactory;
<ide>
<ide> class AuthMiddleware implements Middleware {
<ide>
<ide> /**
<del> * The authenticator implementation.
<add> * The Guard implementation.
<ide> *
<del> * @var Authenticator
<add> * @var Guard
<ide> */
<ide> protected $auth;
<ide>
<ide> class AuthMiddleware implements Middleware {
<ide> /**
<ide> * Create a new filter instance.
<ide> *
<del> * @param Authenticator $auth
<add> * @param Guard $auth
<ide> * @param ResponseFactory $response
<ide> * @return void
<ide> */
<del> public function __construct(Authenticator $auth,
<add> public function __construct(Guard $auth,
<ide> ResponseFactory $response)
<ide> {
<ide> $this->auth = $auth;
<ide><path>app/Http/Middleware/BasicAuthMiddleware.php
<ide> <?php namespace App\Http\Middleware;
<ide>
<ide> use Closure;
<add>use Illuminate\Contracts\Auth\Guard;
<ide> use Illuminate\Contracts\Routing\Middleware;
<del>use Illuminate\Contracts\Auth\Authenticator;
<ide>
<ide> class BasicAuthMiddleware implements Middleware {
<ide>
<ide> /**
<del> * The authenticator implementation.
<add> * The Guard implementation.
<ide> *
<del> * @var Authenticator
<add> * @var Guard
<ide> */
<ide> protected $auth;
<ide>
<ide> /**
<ide> * Create a new filter instance.
<ide> *
<del> * @param Authenticator $auth
<add> * @param Guard $auth
<ide> * @return void
<ide> */
<del> public function __construct(Authenticator $auth)
<add> public function __construct(Guard $auth)
<ide> {
<ide> $this->auth = $auth;
<ide> }
<ide><path>app/Http/Middleware/GuestMiddleware.php
<ide> <?php namespace App\Http\Middleware;
<ide>
<ide> use Closure;
<add>use Illuminate\Contracts\Auth\Guard;
<ide> use Illuminate\Http\RedirectResponse;
<del>use Illuminate\Contracts\Auth\Authenticator;
<ide> use Illuminate\Contracts\Routing\Middleware;
<ide>
<ide> class GuestMiddleware implements Middleware {
<ide>
<ide> /**
<del> * The authenticator implementation.
<add> * The Guard implementation.
<ide> *
<del> * @var Authenticator
<add> * @var Guard
<ide> */
<ide> protected $auth;
<ide>
<ide> /**
<ide> * Create a new filter instance.
<ide> *
<del> * @param Authenticator $auth
<add> * @param Guard $auth
<ide> * @return void
<ide> */
<del> public function __construct(Authenticator $auth)
<add> public function __construct(Guard $auth)
<ide> {
<ide> $this->auth = $auth;
<ide> } | 4 |
Javascript | Javascript | improve sentence flow | bdbe4fd34aecdfdbace0541be58d05ea4cffba6b | <ide><path>src/Angular.js
<ide> function getNgAttribute(element, ngAttr) {
<ide> * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
<ide> *
<ide> * You can specify an **AngularJS module** to be used as the root module for the application. This
<del> * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
<add> * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
<ide> * should contain the application code needed or have dependencies on other modules that will
<ide> * contain the code. See {@link angular.module} for more information.
<ide> * | 1 |
Python | Python | add attribute caching for flattened_layers | fffa6a80ca04738dfd66ea5f54cd6e1471e7b73f | <ide><path>keras/models.py
<ide> def __init__(self, layers=[], name=None):
<ide> self.inbound_nodes = []
<ide> self.outbound_nodes = []
<ide> self.built = False
<add> self._flattened_layers = None
<ide>
<ide> if not name:
<ide> prefix = 'sequential_'
<ide> def add(self, layer):
<ide>
<ide> self.layers.append(layer)
<ide> self.built = False
<add> self._flattened_layers = None
<ide>
<ide> def call(self, x, mask=None):
<ide> if not self.built:
<ide> def uses_learning_phase(self):
<ide>
<ide> @property
<ide> def flattened_layers(self):
<add> if self._flattened_layers is not None:
<add> return self._flattened_layers
<ide> layers = []
<ide> if self.layers[0].__class__.__name__ == 'Merge':
<ide> merge = self.layers[0]
<ide> def flattened_layers(self):
<ide> for layer in self.layers[1:]:
<ide> if layer not in layers:
<ide> layers.append(layer)
<add> self._flattened_layers = layers
<ide> return layers
<ide>
<ide> def _gather_list_attr(self, attr): | 1 |
Go | Go | set a timeout on the netlink handle sockets | 763f0fa1daed048384f02dba79907f16da486c7f | <ide><path>libnetwork/drivers/overlay/ov_network.go
<ide> func populateVNITbl() {
<ide> }
<ide> defer nlh.Delete()
<ide>
<add> err = nlh.SetSocketTimeout(soTimeout)
<add> if err != nil {
<add> logrus.Warnf("Failed to set the timeout on the netlink handle sockets for vni table population: %v", err)
<add> }
<add>
<ide> links, err := nlh.LinkList()
<ide> if err != nil {
<ide> logrus.Errorf("Failed to list interfaces during vni population for ns %s: %v", path, err)
<ide><path>libnetwork/drivers/overlay/ov_utils.go
<ide> import (
<ide> "github.com/vishvananda/netns"
<ide> )
<ide>
<add>var soTimeout = ns.NetlinkSocketsTimeout
<add>
<ide> func validateID(nid, eid string) error {
<ide> if nid == "" {
<ide> return fmt.Errorf("invalid network id")
<ide> func deleteVxlanByVNI(path string, vni uint32) error {
<ide> return fmt.Errorf("failed to get netlink handle for ns %s: %v", path, err)
<ide> }
<ide> defer nlh.Delete()
<add> err = nlh.SetSocketTimeout(soTimeout)
<add> if err != nil {
<add> logrus.Warnf("Failed to set the timeout on the netlink handle sockets for vxlan deletion: %v", err)
<add> }
<ide> }
<ide>
<ide> links, err := nlh.LinkList()
<ide><path>libnetwork/ns/init_linux.go
<ide> import (
<ide> "strings"
<ide> "sync"
<ide> "syscall"
<add> "time"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/vishvananda/netlink"
<ide> var (
<ide> initNs netns.NsHandle
<ide> initNl *netlink.Handle
<ide> initOnce sync.Once
<add> // NetlinkSocketsTimeout represents the default timeout duration for the sockets
<add> NetlinkSocketsTimeout = 3 * time.Second
<ide> )
<ide>
<ide> // Init initializes a new network namespace
<ide> func Init() {
<ide> if err != nil {
<ide> logrus.Errorf("could not create netlink handle on initial namespace: %v", err)
<ide> }
<add> err = initNl.SetSocketTimeout(NetlinkSocketsTimeout)
<add> if err != nil {
<add> logrus.Warnf("Failed to set the timeout on the default netlink handle sockets: %v", err)
<add> }
<ide> }
<ide>
<ide> // SetNamespace sets the initial namespace handler
<ide><path>libnetwork/osl/namespace_linux.go
<ide> func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) {
<ide> return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
<ide> }
<ide>
<add> err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout)
<add> if err != nil {
<add> logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err)
<add> }
<add>
<ide> if err = n.loopbackUp(); err != nil {
<ide> n.nlHandle.Delete()
<ide> return nil, err
<ide> func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) {
<ide> return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
<ide> }
<ide>
<add> err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout)
<add> if err != nil {
<add> logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err)
<add> }
<add>
<ide> if err = n.loopbackUp(); err != nil {
<ide> n.nlHandle.Delete()
<ide> return nil, err | 4 |
Javascript | Javascript | remove non-htmlbars template path | ed06f9ecc7af2e2191c319162630303540593c52 | <ide><path>packages/ember-views/lib/views/view.js
<ide> var View = CoreView.extend(
<ide> var template = get(this, 'template');
<ide>
<ide> if (template) {
<del> if (template.isHTMLBars) {
<del> return template.render(context, options, { contextualElement: morph.contextualElement }).fragment;
<del> } else {
<del> return template(context, options);
<del> }
<add> return template.render(context, options, { contextualElement: morph.contextualElement }).fragment;
<ide> }
<ide> },
<ide> | 1 |
Python | Python | fix undefined function and add integer divisions | e2726316605ab15e94500a78cf2f58e42fa83dd4 | <ide><path>numpy/numarray/functions.py
<ide> def fromfile(infile, type=None, shape=None, sizing=STRICT,
<ide> ##file whose size may be determined before allocation, should be
<ide> ##quick -- only one allocation will be needed.
<ide>
<del> recsize = dtype.itemsize * np.product([i for i in shape if i != -1])
<del> blocksize = max(_BLOCKSIZE/recsize, 1)*recsize
<add> recsize = int(dtype.itemsize * np.product([i for i in shape if i != -1]))
<add> blocksize = max(_BLOCKSIZE//recsize, 1)*recsize
<ide>
<ide> ##try to estimate file size
<ide> try:
<ide> def fromfile(infile, type=None, shape=None, sizing=STRICT,
<ide> except (AttributeError, IOError):
<ide> initsize=blocksize
<ide> else:
<del> initsize=max(1,(endpos-curpos)/recsize)*recsize
<add> initsize=max(1,(endpos-curpos)//recsize)*recsize
<ide>
<ide> buf = np.newbuffer(initsize)
<ide>
<ide> def fromfile(infile, type=None, shape=None, sizing=STRICT,
<ide> except IOError:
<ide> _warnings.warn("Could not rewind (IOError in seek)",
<ide> FileSeekWarning)
<del> datasize = (len(data)/recsize) * recsize
<add> datasize = (len(data)//recsize) * recsize
<ide> if len(buf) != bytesread+datasize:
<ide> buf=_resizebuf(buf,bytesread+datasize)
<ide> buf[bytesread:bytesread+datasize]=data[:datasize]
<ide> ##deduce shape from len(buf)
<ide> shape = list(shape)
<ide> uidx = shape.index(-1)
<del> shape[uidx]=len(buf) / recsize
<add> shape[uidx]=len(buf) // recsize
<ide>
<ide> a = np.ndarray(shape=shape, dtype=type, buffer=buf)
<ide> if a.dtype.char == '?':
<ide> np.not_equal(a, 0, a)
<ide> return a
<ide>
<add>
<add># this function is referenced in the code above but not defined. adding
<add># it back. - phensley
<add>def _resizebuf(buf,newsize):
<add> "Return a copy of BUF of size NEWSIZE."
<add> newbuf = np.newbuffer(newsize)
<add> if newsize > len(buf):
<add> newbuf[:len(buf)]=buf
<add> else:
<add> newbuf[:]=buf[:len(newbuf)]
<add> return newbuf
<add>
<add>
<ide> def fromstring(datastring, type=None, shape=None, typecode=None, dtype=None):
<ide> dtype = type2dtype(typecode, type, dtype, True)
<ide> if shape is None: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.