Remove everything, rewrite of AMS starts here

This commit is contained in:
Santiago Pastorino
2013-09-16 17:11:30 -03:00
parent 919bb38401
commit 14f51f2ea9
36 changed files with 0 additions and 5836 deletions

View File

@@ -1,85 +0,0 @@
require "test_helper"
require "test_fakes"
class ArraySerializerTest < ActiveModel::TestCase
# serialize different typed objects
def test_array_serializer
model = Model.new
user = User.new
comments = Comment.new(title: "Comment1", id: 1)
array = [model, user, comments]
serializer = array.active_model_serializer.new(array, scope: { scope: true })
assert_equal([
{ model: "Model" },
{ last_name: "Valim", ok: true, first_name: "Jose", scope: true },
{ title: "Comment1" }
], serializer.as_json)
end
def test_array_serializer_with_root
comment1 = Comment.new(title: "Comment1", id: 1)
comment2 = Comment.new(title: "Comment2", id: 2)
array = [ comment1, comment2 ]
serializer = array.active_model_serializer.new(array, root: :comments)
assert_equal({ comments: [
{ title: "Comment1" },
{ title: "Comment2" }
]}, serializer.as_json)
end
def test_active_model_with_root
comment1 = ModelWithActiveModelSerializer.new(title: "Comment1")
comment2 = ModelWithActiveModelSerializer.new(title: "Comment2")
array = [ comment1, comment2 ]
serializer = array.active_model_serializer.new(array, root: :comments)
assert_equal({ comments: [
{ title: "Comment1" },
{ title: "Comment2" }
]}, serializer.as_json)
end
def test_array_serializer_with_hash
hash = { value: "something" }
array = [hash]
serializer = array.active_model_serializer.new(array, root: :items)
assert_equal({ items: [hash.as_json] }, serializer.as_json)
end
def test_array_serializer_with_specified_serializer
post1 = Post.new(title: "Post1", author: "Author1", id: 1)
post2 = Post.new(title: "Post2", author: "Author2", id: 2)
array = [ post1, post2 ]
serializer = array.active_model_serializer.new array, each_serializer: CustomPostSerializer
assert_equal([
{ title: "Post1" },
{ title: "Post2" }
], serializer.as_json)
end
def test_array_serializer_using_default_serializer
hash = { "value" => "something" }
class << hash
def active_model_serializer
nil
end
end
array = [hash]
serializer = array.active_model_serializer.new array
assert_equal([
{ "value" => "something" }
], serializer.as_json)
end
end

View File

@@ -1,592 +0,0 @@
require "test_helper"
class AssociationTest < ActiveModel::TestCase
def def_serializer(&block)
Class.new(ActiveModel::Serializer, &block)
end
class Model
def initialize(hash={})
@attributes = hash
end
def read_attribute_for_serialization(name)
@attributes[name]
end
def as_json(*)
{ model: "Model" }
end
def method_missing(meth, *args)
if meth.to_s =~ /^(.*)=$/
@attributes[$1.to_sym] = args[0]
elsif @attributes.key?(meth)
@attributes[meth]
else
super
end
end
end
def setup
@hash = {}
@root_hash = {}
@post = Model.new(title: "New Post", body: "Body")
@comment = Model.new(id: 1, external_id: "COMM001", body: "ZOMG A COMMENT")
@post.comments = [ @comment ]
@post.comment = @comment
@comment_serializer_class = def_serializer do
attributes :id, :external_id, :body
end
@post_serializer_class = def_serializer do
attributes :title, :body
end
@post_serializer = @post_serializer_class.new(@post, hash: @root_hash)
end
def include!(key, options={})
@post_serializer.include! key, {
embed: :ids,
include: true,
node: @hash,
serializer: @comment_serializer_class
}.merge(options)
end
def include_bare!(key, options={})
@post_serializer.include! key, {
node: @hash,
serializer: @comment_serializer_class
}.merge(options)
end
class NoDefaults < AssociationTest
def test_include_bang_has_many_associations
include! :comments, value: @post.comments
assert_equal({
comment_ids: [ 1 ]
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_include_bang_with_embed_false
include! :comments, value: @post.comments, embed: false
assert_equal({}, @hash)
assert_equal({}, @root_hash)
end
def test_include_bang_with_embed_ids_include_false
include! :comments, value: @post.comments, embed: :ids, include: false
assert_equal({
comment_ids: [ 1 ]
}, @hash)
assert_equal({}, @root_hash)
end
def test_include_bang_has_one_associations
include! :comment, value: @post.comment
assert_equal({
comment_id: 1
}, @hash)
assert_equal({
comments: [{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }]
}, @root_hash)
end
end
class DefaultsTest < AssociationTest
def test_with_default_has_many
@post_serializer_class.class_eval do
has_many :comments
end
include! :comments
assert_equal({
comment_ids: [ 1 ]
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_with_default_has_one
@post_serializer_class.class_eval do
has_one :comment
end
include! :comment
assert_equal({
comment_id: 1
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_with_default_has_many_with_custom_key
@post_serializer_class.class_eval do
has_many :comments, key: :custom_comments
end
include! :comments
assert_equal({
custom_comments: [ 1 ]
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_with_default_has_one_with_custom_key
@post_serializer_class.class_eval do
has_one :comment, key: :custom_comment_id
end
include! :comment
assert_equal({
custom_comment_id: 1
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_with_default_has_many_with_custom_embed_key
@post_serializer_class.class_eval do
has_many :comments, embed_key: :external_id
end
include! :comments
assert_equal({
comment_ids: [ "COMM001" ]
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_with_default_has_one_with_custom_embed_key
@post_serializer_class.class_eval do
has_one :comment, embed_key: :external_id
end
include! :comment
assert_equal({
comment_id: "COMM001"
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_with_default_has_many_with_custom_key_and_custom_embed_key
@post_serializer_class.class_eval do
has_many :comments, key: :custom_comments, embed_key: :external_id
end
include! :comments
assert_equal({
custom_comments: [ "COMM001" ]
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_with_default_has_one_with_custom_key_and_custom_embed_key
@post_serializer_class.class_eval do
has_one :comment, key: :custom_comment, embed_key: :external_id
end
include! :comment
assert_equal({
custom_comment: "COMM001"
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_embed_objects_for_has_many_associations
@post_serializer_class.class_eval do
has_many :comments, embed: :objects
end
include_bare! :comments
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @hash)
assert_equal({}, @root_hash)
end
def test_embed_ids_for_has_many_associations
@post_serializer_class.class_eval do
has_many :comments, embed: :ids
end
include_bare! :comments
assert_equal({
comment_ids: [ 1 ]
}, @hash)
assert_equal({}, @root_hash)
end
def test_embed_false_for_has_many_associations
@post_serializer_class.class_eval do
has_many :comments, embed: false
end
include_bare! :comments
assert_equal({}, @hash)
assert_equal({}, @root_hash)
end
def test_embed_ids_include_true_for_has_many_associations
@post_serializer_class.class_eval do
has_many :comments, embed: :ids, include: true
end
include_bare! :comments
assert_equal({
comment_ids: [ 1 ]
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_embed_ids_for_has_one_associations
@post_serializer_class.class_eval do
has_one :comment, embed: :ids
end
include_bare! :comment
assert_equal({
comment_id: 1
}, @hash)
assert_equal({}, @root_hash)
end
def test_embed_false_for_has_one_associations
@post_serializer_class.class_eval do
has_one :comment, embed: false
end
include_bare! :comment
assert_equal({}, @hash)
assert_equal({}, @root_hash)
end
def test_embed_ids_include_true_for_has_one_associations
@post_serializer_class.class_eval do
has_one :comment, embed: :ids, include: true
end
include_bare! :comment
assert_equal({
comment_id: 1
}, @hash)
assert_equal({
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, @root_hash)
end
def test_embed_ids_include_true_does_not_serialize_multiple_times
@post.recent_comment = @comment
@post_serializer_class.class_eval do
has_one :comment, embed: :ids, include: true
has_one :recent_comment, embed: :ids, include: true, root: :comments
end
# Count how often the @comment record is serialized.
serialized_times = 0
@comment.class_eval do
define_method :read_attribute_for_serialization, lambda { |name|
serialized_times += 1 if name == :body
super(name)
}
end
include_bare! :comment
include_bare! :recent_comment
assert_equal 1, serialized_times
end
def test_include_with_read_association_id_for_serialization_hook
@post_serializer_class.class_eval do
has_one :comment, embed: :ids, include: true
end
association_name = nil
@post.class_eval do
define_method :read_attribute_for_serialization, lambda { |name|
association_name = name
send(name)
}
define_method :comment_id, lambda {
@attributes[:comment].id
}
end
include_bare! :comment
assert_equal({
comment_id: 1
}, @hash)
end
def test_include_with_read_association_ids_for_serialization_hook
@post_serializer_class.class_eval do
has_many :comments, embed: :ids, include: false
end
association_name = nil
@post.class_eval do
define_method :read_attribute_for_serialization, lambda { |name|
association_name = name
send(name)
}
define_method :comment_ids, lambda {
@attributes[:comments].map(&:id)
}
end
include_bare! :comments
assert_equal({
comment_ids: [1]
}, @hash)
end
end
class RecursiveTest < AssociationTest
class BarSerializer < ActiveModel::Serializer; end
class FooSerializer < ActiveModel::Serializer
root :foos
attributes :id
has_many :bars, serializer: BarSerializer, root: :bars, embed: :ids, include: true
end
class BarSerializer < ActiveModel::Serializer
root :bars
attributes :id
has_many :foos, serializer: FooSerializer, root: :foos, embed: :ids, include: true
end
class Foo < Model
def active_model_serializer; FooSerializer; end
end
class Bar < Model
def active_model_serializer; BarSerializer; end
end
def setup
super
foo = Foo.new(id: 1)
bar = Bar.new(id: 2)
foo.bars = [ bar ]
bar.foos = [ foo ]
collection = [ foo ]
@serializer = collection.active_model_serializer.new(collection, root: :foos)
end
def test_mutual_relation_result
assert_equal({
foos: [{
bar_ids: [ 2 ],
id: 1
}],
bars: [{
foo_ids: [ 1 ],
id: 2
}]
}, @serializer.as_json)
end
def test_mutual_relation_does_not_raise_error
assert_nothing_raised SystemStackError, 'stack level too deep' do
@serializer.as_json
end
end
end
class InclusionTest < AssociationTest
def setup
super
comment_serializer_class = @comment_serializer_class
@post_serializer_class.class_eval do
root :post
embed :ids, include: true
has_many :comments, serializer: comment_serializer_class
end
end
def test_when_it_is_included
post_serializer = @post_serializer_class.new(
@post, include: [:comments]
)
json = post_serializer.as_json
assert_equal({
post: {
title: "New Post",
body: "Body",
comment_ids: [ 1 ]
},
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, json)
end
def test_when_it_is_not_included
post_serializer = @post_serializer_class.new(
@post, include: []
)
json = post_serializer.as_json
assert_equal({
post: {
title: "New Post",
body: "Body",
comment_ids: [ 1 ]
}
}, json)
end
def test_when_it_is_excluded
post_serializer = @post_serializer_class.new(
@post, exclude: [:comments]
)
json = post_serializer.as_json
assert_equal({
post: {
title: "New Post",
body: "Body",
comment_ids: [ 1 ]
}
}, json)
end
def test_when_it_is_not_excluded
post_serializer = @post_serializer_class.new(
@post, exclude: []
)
json = post_serializer.as_json
assert_equal({
post: {
title: "New Post",
body: "Body",
comment_ids: [ 1 ]
},
comments: [
{ id: 1, external_id: "COMM001", body: "ZOMG A COMMENT" }
]
}, json)
end
end
class StringSerializerOption < AssociationTest
class StringSerializer < ActiveModel::Serializer
attributes :id, :body
end
def test_specifying_serializer_class_as_string
@post_serializer_class.class_eval do
has_many :comments, embed: :objects
end
include_bare! :comments, serializer: "AssociationTest::StringSerializerOption::StringSerializer"
assert_equal({
comments: [
{ id: 1, body: "ZOMG A COMMENT" }
]
}, @hash)
assert_equal({}, @root_hash)
end
end
end

View File

@@ -1,96 +0,0 @@
require "test_helper"
class CachingTest < ActiveModel::TestCase
class NullStore
def fetch(key)
return store[key] if store[key]
store[key] = yield
end
def clear
store.clear
end
def store
@store ||= {}
end
def read(key)
store[key]
end
end
class Programmer
def name
'Adam'
end
def skills
%w(ruby)
end
def read_attribute_for_serialization(name)
send name
end
end
def test_serializers_have_a_cache_store
ActiveModel::Serializer.cache = NullStore.new
assert_kind_of NullStore, ActiveModel::Serializer.cache
end
def test_serializers_can_enable_caching
serializer = Class.new(ActiveModel::Serializer) do
cached true
end
assert serializer.perform_caching
end
def test_serializers_use_cache
serializer = Class.new(ActiveModel::Serializer) do
cached true
attributes :name, :skills
def self.to_s
'serializer'
end
def cache_key
object.name
end
end
serializer.cache = NullStore.new
instance = serializer.new Programmer.new
instance.to_json
assert_equal(instance.serializable_hash, serializer.cache.read('serializer/Adam/serialize'))
assert_equal(instance.to_json, serializer.cache.read('serializer/Adam/to-json'))
end
def test_array_serializer_uses_cache
serializer = Class.new(ActiveModel::ArraySerializer) do
cached true
def self.to_s
'array_serializer'
end
def cache_key
'cache-key'
end
end
serializer.cache = NullStore.new
instance = serializer.new [Programmer.new]
instance.to_json
assert_equal instance.serializable_array, serializer.cache.read('array_serializer/cache-key/serialize')
assert_equal instance.to_json, serializer.cache.read('array_serializer/cache-key/to-json')
end
end

View File

@@ -1,73 +0,0 @@
require 'test_helper'
class Foo < Rails::Application
if Rails.version.to_s.start_with? '4'
config.eager_load = false
config.secret_key_base = 'abc123'
end
end
Rails.application.load_generators
require 'generators/serializer/serializer_generator'
class SerializerGeneratorTest < Rails::Generators::TestCase
destination File.expand_path("../tmp", __FILE__)
setup :prepare_destination
tests Rails::Generators::SerializerGenerator
arguments %w(account name:string description:text business:references)
def test_generates_a_serializer
run_generator
assert_file "app/serializers/account_serializer.rb", /class AccountSerializer < ActiveModel::Serializer/
end
def test_generates_a_namespaced_serializer
run_generator ["admin/account"]
assert_file "app/serializers/admin/account_serializer.rb", /class Admin::AccountSerializer < ActiveModel::Serializer/
end
def test_uses_application_serializer_if_one_exists
Object.const_set(:ApplicationSerializer, Class.new)
run_generator
assert_file "app/serializers/account_serializer.rb", /class AccountSerializer < ApplicationSerializer/
ensure
Object.send :remove_const, :ApplicationSerializer
end
# def test_uses_namespace_application_serializer_if_one_exists
# Object.const_set(:SerializerNamespace, Module.new)
# SerializerNamespace.const_set(:ApplicationSerializer, Class.new)
# Rails::Generators.namespace = SerializerNamespace
# run_generator
# assert_file "app/serializers/serializer_namespace/account_serializer.rb",
# /module SerializerNamespace\n class AccountSerializer < ApplicationSerializer/
# ensure
# Object.send :remove_const, :SerializerNamespace
# Rails::Generators.namespace = nil
# end
def test_uses_given_parent
Object.const_set(:ApplicationSerializer, Class.new)
run_generator ["Account", "--parent=MySerializer"]
assert_file "app/serializers/account_serializer.rb", /class AccountSerializer < MySerializer/
ensure
Object.send :remove_const, :ApplicationSerializer
end
def test_generates_attributes_and_associations
run_generator
assert_file "app/serializers/account_serializer.rb" do |serializer|
assert_match(/^ attributes :id, :name, :description$/, serializer)
assert_match(/^ has_one :business$/, serializer)
end
end
def test_with_no_attributes_does_not_add_extra_space
run_generator ["account"]
assert_file "app/serializers/account_serializer.rb" do |content|
assert_no_match /\n\nend/, content
end
end
end

View File

@@ -1,34 +0,0 @@
require "test_helper"
class NoSerializationScopeTest < ActionController::TestCase
class ScopeSerializer
def initialize(object, options)
@object, @options = object, options
end
def as_json(*)
{ scope: @options[:scope].as_json }
end
end
class ScopeSerializable
def active_model_serializer
ScopeSerializer
end
end
class NoSerializationScopeController < ActionController::Base
serialization_scope nil
def index
render json: ScopeSerializable.new
end
end
tests NoSerializationScopeController
def test_disabled_serialization_scope
get :index, format: :json
assert_equal '{"scope":null}', @response.body
end
end

View File

@@ -1,99 +0,0 @@
require 'test_helper'
require 'pathname'
class DefaultScopeNameTest < ActionController::TestCase
TestUser = Struct.new(:name, :admin)
class UserSerializer < ActiveModel::Serializer
attributes :admin?
def admin?
current_user.admin
end
end
class UserTestController < ActionController::Base
protect_from_forgery
before_filter { request.format = :json }
def current_user
TestUser.new('Pete', false)
end
def render_new_user
render json: TestUser.new('pete', false), serializer: UserSerializer
end
end
tests UserTestController
def test_default_scope_name
get :render_new_user
assert_equal '{"user":{"admin":false}}', @response.body
end
end
class SerializationScopeNameTest < ActionController::TestCase
TestUser = Struct.new(:name, :admin)
class AdminUserSerializer < ActiveModel::Serializer
attributes :admin?
def admin?
current_admin.admin
end
end
class AdminUserTestController < ActionController::Base
protect_from_forgery
serialization_scope :current_admin
before_filter { request.format = :json }
def current_admin
TestUser.new('Bob', true)
end
def render_new_user
render json: TestUser.new('pete', false), serializer: AdminUserSerializer
end
end
tests AdminUserTestController
def test_override_scope_name_with_controller
get :render_new_user
assert_equal '{"admin_user":{"admin":true}}', @response.body
end
end
class SerializationActionScopeOverrideTest < ActionController::TestCase
TestUser = Struct.new(:name, :admin)
class AdminUserSerializer < ActiveModel::Serializer
attributes :admin?
def admin?
current_admin.admin
end
end
class AdminUserTestController < ActionController::Base
protect_from_forgery
before_filter { request.format = :json }
def current_admin
TestUser.new('Bob', true)
end
def render_new_user
render json: TestUser.new('pete', false), serializer: AdminUserSerializer, scope: current_admin, scope_name: :current_admin
end
end
tests AdminUserTestController
def test_override_scope_name_with_controller
get :render_new_user
assert_equal '{"admin_user":{"admin":true}}', @response.body
end
end

View File

@@ -1,394 +0,0 @@
require 'test_helper'
require 'pathname'
class RenderJsonTest < ActionController::TestCase
class JsonRenderable
def as_json(options={})
hash = { a: :b, c: :d, e: :f }
hash.except!(*options[:except]) if options[:except]
hash
end
def to_json(options = {})
super except: [:c, :e]
end
end
class JsonSerializer
def initialize(object, options={})
@object, @options = object, options
end
def as_json(*)
hash = { object: serializable_hash, scope: @options[:scope].as_json }
hash.merge!(options: true) if @options[:options]
hash.merge!(check_defaults: true) if @options[:check_defaults]
hash
end
def serializable_hash
@object.as_json
end
end
class JsonSerializable
def initialize(skip=false)
@skip = skip
end
def active_model_serializer
JsonSerializer unless @skip
end
def as_json(*)
{ serializable_object: true }
end
end
class CustomSerializer
def initialize(*)
end
def as_json(*)
{ hello: true }
end
end
class AnotherCustomSerializer
def initialize(*)
end
def as_json(*)
{ rails: 'rocks' }
end
end
class DummyCustomSerializer < ActiveModel::Serializer
attributes :id
end
class HypermediaSerializable
def active_model_serializer
HypermediaSerializer
end
end
class HypermediaSerializer < ActiveModel::Serializer
def as_json(*)
{ link: hypermedia_url }
end
end
class CustomArraySerializer < ActiveModel::ArraySerializer
self.root = "items"
end
class TestController < ActionController::Base
protect_from_forgery
serialization_scope :current_user
attr_reader :current_user
def self.controller_path
'test'
end
def render_json_nil
render json: nil
end
def render_json_render_to_string
render text: render_to_string(json: '[]')
end
def render_json_hello_world
render json: ActiveSupport::JSON.encode(hello: 'world')
end
def render_json_hello_world_with_status
render json: ActiveSupport::JSON.encode(hello: 'world'), status: 401
end
def render_json_hello_world_with_callback
render json: ActiveSupport::JSON.encode(hello: 'world'), callback: 'alert'
end
def render_json_with_custom_content_type
render json: ActiveSupport::JSON.encode(hello: 'world'), content_type: 'text/javascript'
end
def render_symbol_json
render json: ActiveSupport::JSON.encode(hello: 'world')
end
def render_json_nil_with_custom_serializer
render json: nil, serializer: DummyCustomSerializer
end
def render_json_with_extra_options
render json: JsonRenderable.new, except: [:c, :e]
end
def render_json_without_options
render json: JsonRenderable.new
end
def render_json_with_serializer
@current_user = Struct.new(:as_json).new(current_user: true)
render json: JsonSerializable.new
end
def render_json_with_serializer_and_implicit_root
@current_user = Struct.new(:as_json).new(current_user: true)
render json: [JsonSerializable.new]
end
def render_json_with_serializer_and_options
@current_user = Struct.new(:as_json).new(current_user: true)
render json: JsonSerializable.new, options: true
end
def render_json_with_serializer_and_scope_option
@current_user = Struct.new(:as_json).new(current_user: true)
scope = Struct.new(:as_json).new(current_user: false)
render json: JsonSerializable.new, scope: scope
end
def render_json_with_serializer_api_but_without_serializer
@current_user = Struct.new(:as_json).new(current_user: true)
render json: JsonSerializable.new(true)
end
# To specify a custom serializer for an object, use :serializer.
def render_json_with_custom_serializer
render json: Object.new, serializer: CustomSerializer
end
# To specify a custom serializer for each item in the Array, use :each_serializer.
def render_json_array_with_custom_serializer
render json: [Object.new], each_serializer: CustomSerializer
end
def render_json_array_with_wrong_option
render json: [Object.new], serializer: CustomSerializer
end
def render_json_with_links
render json: HypermediaSerializable.new
end
def render_json_array_with_no_root
render json: [], root: false
end
def render_json_empty_array
render json: []
end
def render_json_array_with_custom_array_serializer
render json: [], serializer: CustomArraySerializer
end
private
def default_serializer_options
defaults = {}
defaults.merge!(check_defaults: true) if params[:check_defaults]
defaults.merge!(root: :awesome) if params[:check_default_root]
defaults.merge!(scope: :current_admin) if params[:check_default_scope]
defaults.merge!(serializer: AnotherCustomSerializer) if params[:check_default_serializer]
defaults.merge!(each_serializer: AnotherCustomSerializer) if params[:check_default_each_serializer]
defaults
end
end
tests TestController
def setup
# enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
# a more accurate simulation of what happens in "real life".
super
@controller.logger = Logger.new(nil)
@request.host = "www.nextangle.com"
end
def test_render_json_nil
get :render_json_nil
assert_equal 'null', @response.body
assert_equal 'application/json', @response.content_type
end
def test_render_json_render_to_string
get :render_json_render_to_string
assert_equal '[]', @response.body
end
def test_render_json_nil_with_custom_serializer
get :render_json_nil_with_custom_serializer
assert_equal "{\"dummy_custom\":null}", @response.body
end
def test_render_json
get :render_json_hello_world
assert_equal '{"hello":"world"}', @response.body
assert_equal 'application/json', @response.content_type
end
def test_render_json_with_status
get :render_json_hello_world_with_status
assert_equal '{"hello":"world"}', @response.body
assert_equal 401, @response.status
end
def test_render_json_with_callback
get :render_json_hello_world_with_callback
assert_equal 'alert({"hello":"world"})', @response.body
# For JSONP, Rails 3 uses application/json, but Rails 4 uses text/javascript
assert_match %r(application/json|text/javascript), @response.content_type.to_s
end
def test_render_json_with_custom_content_type
get :render_json_with_custom_content_type
assert_equal '{"hello":"world"}', @response.body
assert_equal 'text/javascript', @response.content_type
end
def test_render_symbol_json
get :render_symbol_json
assert_equal '{"hello":"world"}', @response.body
assert_equal 'application/json', @response.content_type
end
def test_render_json_forwards_extra_options
get :render_json_with_extra_options
assert_equal '{"a":"b"}', @response.body
assert_equal 'application/json', @response.content_type
end
def test_render_json_calls_to_json_from_object
get :render_json_without_options
assert_equal '{"a":"b"}', @response.body
end
def test_render_json_with_serializer
get :render_json_with_serializer
assert_match '"scope":{"current_user":true}', @response.body
assert_match '"object":{"serializable_object":true}', @response.body
end
def test_render_json_with_serializer_checking_defaults
get :render_json_with_serializer, check_defaults: true
assert_match '"scope":{"current_user":true}', @response.body
assert_match '"object":{"serializable_object":true}', @response.body
assert_match '"check_defaults":true', @response.body
end
def test_render_json_with_serializer_checking_default_serailizer
get :render_json_with_serializer, check_default_serializer: true
assert_match '{"rails":"rocks"}', @response.body
end
def test_render_json_with_serializer_checking_default_scope
get :render_json_with_serializer, check_default_scope: true
assert_match '"scope":"current_admin"', @response.body
end
def test_render_json_with_serializer_and_implicit_root
get :render_json_with_serializer_and_implicit_root
assert_match '"test":[{"serializable_object":true}]', @response.body
end
def test_render_json_with_serializer_and_implicit_root_checking_default_each_serailizer
get :render_json_with_serializer_and_implicit_root, check_default_each_serializer: true
assert_match '"test":[{"rails":"rocks"}]', @response.body
end
def test_render_json_with_serializer_and_options
get :render_json_with_serializer_and_options
assert_match '"scope":{"current_user":true}', @response.body
assert_match '"object":{"serializable_object":true}', @response.body
assert_match '"options":true', @response.body
end
def test_render_json_with_serializer_and_scope_option
get :render_json_with_serializer_and_scope_option
assert_match '"scope":{"current_user":false}', @response.body
end
def test_render_json_with_serializer_and_scope_option_checking_default_scope
get :render_json_with_serializer_and_scope_option, check_default_scope: true
assert_match '"scope":{"current_user":false}', @response.body
end
def test_render_json_with_serializer_api_but_without_serializer
get :render_json_with_serializer_api_but_without_serializer
assert_match '{"serializable_object":true}', @response.body
end
def test_render_json_with_custom_serializer
get :render_json_with_custom_serializer
assert_match '{"hello":true}', @response.body
end
def test_render_json_with_custom_serializer_checking_default_serailizer
get :render_json_with_custom_serializer, check_default_serializer: true
assert_match '{"hello":true}', @response.body
end
def test_render_json_array_with_custom_serializer
get :render_json_array_with_custom_serializer
assert_match '{"test":[{"hello":true}]}', @response.body
end
def test_render_json_array_with_wrong_option
assert_raise ArgumentError do
get :render_json_array_with_wrong_option
end
end
def test_render_json_array_with_custom_serializer_checking_default_each_serailizer
get :render_json_array_with_custom_serializer, check_default_each_serializer: true
assert_match '{"test":[{"hello":true}]}', @response.body
end
def test_render_json_with_links
get :render_json_with_links
assert_match '{"link":"http://www.nextangle.com/hypermedia"}', @response.body
end
def test_render_json_array_with_no_root
get :render_json_array_with_no_root
assert_equal '[]', @response.body
end
def test_render_json_array_with_no_root_checking_default_root
get :render_json_array_with_no_root, check_default_root: true
assert_equal '[]', @response.body
end
def test_render_json_empty_array
get :render_json_empty_array
assert_equal '{"test":[]}', @response.body
end
def test_render_json_empty_array_checking_default_root
get :render_json_empty_array, check_default_root: true
assert_equal '{"awesome":[]}', @response.body
end
def test_render_json_empty_array_with_array_serializer_root_false
ActiveModel::ArraySerializer.root = false
get :render_json_empty_array
assert_equal '[]', @response.body
ensure # teardown
ActiveModel::ArraySerializer.root = nil
end
def test_render_json_array_with_custom_array_serializer
get :render_json_array_with_custom_array_serializer
assert_equal '{"items":[]}', @response.body
end
end

View File

@@ -1,51 +0,0 @@
require "test_helper"
class RandomModel
include ActiveModel::SerializerSupport
end
class OtherRandomModel
include ActiveModel::SerializerSupport
end
class OtherRandomModelSerializer
end
class RandomModelCollection
include ActiveModel::ArraySerializerSupport
end
module ActiveRecord
class Relation
end
end
module Mongoid
class Criteria
end
end
class SerializerSupportTest < ActiveModel::TestCase
test "it returns nil if no serializer exists" do
assert_equal nil, RandomModel.new.active_model_serializer
end
test "it returns a deducted serializer if it exists exists" do
assert_equal OtherRandomModelSerializer, OtherRandomModel.new.active_model_serializer
end
test "it returns ArraySerializer for a collection" do
assert_equal ActiveModel::ArraySerializer, RandomModelCollection.new.active_model_serializer
end
test "it automatically includes array_serializer in active_record/relation" do
ActiveSupport.run_load_hooks(:active_record)
assert_equal ActiveModel::ArraySerializer, ActiveRecord::Relation.new.active_model_serializer
end
test "it automatically includes array_serializer in mongoid/criteria" do
ActiveSupport.run_load_hooks(:mongoid)
assert_equal ActiveModel::ArraySerializer, Mongoid::Criteria.new.active_model_serializer
end
end

File diff suppressed because it is too large Load Diff

View File

@@ -1,202 +0,0 @@
class Model
def initialize(hash={})
@attributes = hash
end
def read_attribute_for_serialization(name)
@attributes[name]
end
def as_json(*)
{ model: "Model" }
end
end
class ModelWithActiveModelSerializer < Model
include ActiveModel::Serializers::JSON
attr_accessor :attributes
def read_attribute_for_serialization(name)
@attributes[name]
end
end
class User
include ActiveModel::SerializerSupport
attr_accessor :superuser
def initialize(hash={})
@attributes = hash.merge(first_name: "Jose", last_name: "Valim", password: "oh noes yugive my password")
end
def read_attribute_for_serialization(name)
@attributes[name]
end
def super_user?
@superuser
end
end
class Post < Model
def initialize(attributes)
super(attributes)
self.comments ||= []
self.comments_disabled = false
self.author = nil
end
attr_accessor :comments, :comments_disabled, :author
def active_model_serializer; PostSerializer; end
end
class Comment < Model
def active_model_serializer; CommentSerializer; end
end
class UserSerializer < ActiveModel::Serializer
attributes :first_name, :last_name
def serializable_hash
attributes.merge(ok: true).merge(options[:scope])
end
end
class UserAttributesWithKeySerializer < ActiveModel::Serializer
attributes first_name: :f_name, last_name: :l_name
def serializable_hash
attributes.merge(ok: true).merge(options[:scope])
end
end
class UserAttributesWithSomeKeySerializer < ActiveModel::Serializer
attributes :first_name, last_name: :l_name
def serializable_hash
attributes.merge(ok: true).merge(options[:scope])
end
end
class UserAttributesWithUnsymbolizableKeySerializer < ActiveModel::Serializer
attributes :first_name, last_name: :"last-name"
def serializable_hash
attributes.merge(ok: true).merge(options[:scope])
end
end
class DefaultUserSerializer < ActiveModel::Serializer
attributes :first_name, :last_name
end
class MyUserSerializer < ActiveModel::Serializer
attributes :first_name, :last_name
def serializable_hash
hash = attributes
hash = hash.merge(super_user: true) if object.super_user?
hash
end
end
class CommentSerializer
def initialize(comment, options={})
@object = comment
end
attr_reader :object
def serializable_hash
{ title: @object.read_attribute_for_serialization(:title) }
end
def as_json(options=nil)
options ||= {}
if options[:root] == false
serializable_hash
else
{ comment: serializable_hash }
end
end
end
class PostSerializer < ActiveModel::Serializer
attributes :title, :body
has_many :comments, serializer: CommentSerializer
end
class PostWithConditionalCommentsSerializer < ActiveModel::Serializer
root :post
attributes :title, :body
has_many :comments, serializer: CommentSerializer
def include_associations!
include! :comments unless object.comments_disabled
end
end
class PostWithMultipleConditionalsSerializer < ActiveModel::Serializer
root :post
attributes :title, :body, :author
has_many :comments, serializer: CommentSerializer
def include_comments?
!object.comments_disabled
end
def include_author?
scope.super_user?
end
end
class Blog < Model
attr_accessor :author
end
class AuthorSerializer < ActiveModel::Serializer
attributes :first_name, :last_name
end
class BlogSerializer < ActiveModel::Serializer
has_one :author, serializer: AuthorSerializer
end
class BlogWithRootSerializer < BlogSerializer
root true
end
class CustomPostSerializer < ActiveModel::Serializer
attributes :title
end
class CustomBlog < Blog
attr_accessor :public_posts, :public_user
end
class CustomBlogSerializer < ActiveModel::Serializer
has_many :public_posts, key: :posts, serializer: PostSerializer
has_one :public_user, key: :user, serializer: UserSerializer
end
class SomeSerializer < ActiveModel::Serializer
attributes :some
end
class SomeObject < Struct.new(:some)
end
# Set up some classes for polymorphic testing
class Attachment < Model
def attachable
@attributes[:attachable]
end
def readable
@attributes[:readable]
end
def edible
@attributes[:edible]
end
end

View File

@@ -1,41 +0,0 @@
require "rubygems"
require "bundler/setup"
require 'simplecov'
SimpleCov.start do
add_group "lib", "lib"
add_group "spec", "spec"
end
require 'coveralls'
Coveralls.wear!
require "pry"
require "active_model_serializers"
require "active_support/json"
require "minitest/autorun"
require 'rails'
module TestHelper
Routes = ActionDispatch::Routing::RouteSet.new
Routes.draw do
resource :hypermedia
get ':controller(/:action(/:id))'
get ':controller(/:action)'
end
ActionController::Base.send :include, Routes.url_helpers
ActiveModel::Serializer.send :include, Routes.url_helpers
end
ActiveSupport::TestCase.class_eval do
setup do
@routes = ::TestHelper::Routes
end
end
class Object
undef_method :id if respond_to?(:id)
end