1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
|
require 'test_helper'
class RepresentableTest < Minitest::Spec
class Band
include Representable::Hash
property :name
attr_accessor :name
end
class PunkBand < Band
property :street_cred
attr_accessor :street_cred
end
module BandRepresentation
include Representable
property :name
end
module PunkBandRepresentation
include Representable
include BandRepresentation
property :street_cred
end
describe "#representable_attrs" do
describe "in module" do
it "allows including the concrete representer module later" do
vd = class VD
attr_accessor :name, :street_cred
include Representable::JSON
include PunkBandRepresentation
end.new
vd.name = "Vention Dention"
vd.street_cred = 1
assert_json "{\"name\":\"Vention Dention\",\"street_cred\":1}", vd.to_json
end
#it "allows including the concrete representer module only" do
# require 'representable/json'
# module RockBandRepresentation
# include Representable::JSON
# property :name
# end
# vd = class VH
# include RockBandRepresentation
# end.new
# vd.name = "Van Halen"
# assert_equal "{\"name\":\"Van Halen\"}", vd.to_json
#end
end
end
describe "inheritance" do
class CoverSong < OpenStruct
end
module SongRepresenter
include Representable::Hash
property :name
end
module CoverSongRepresenter
include Representable::Hash
include SongRepresenter
property :by
end
it "merges properties from all ancestors" do
props = {"name"=>"The Brews", "by"=>"Nofx"}
assert_equal(props, CoverSong.new(props).extend(CoverSongRepresenter).to_hash)
end
it "allows mixing in multiple representers" do
class Bodyjar
include Representable::XML
include Representable::JSON
include PunkBandRepresentation
self.representation_wrap = "band"
attr_accessor :name, :street_cred
end
band = Bodyjar.new
band.name = "Bodyjar"
assert_json "{\"band\":{\"name\":\"Bodyjar\"}}", band.to_json
assert_xml_equal "<band><name>Bodyjar</name></band>", band.to_xml
end
it "allows extending with different representers subsequentially" do
module SongXmlRepresenter
include Representable::XML
property :name, :as => "name", :attribute => true
end
module SongJsonRepresenter
include Representable::JSON
property :name
end
@song = Song.new("Days Go By")
assert_xml_equal "<song name=\"Days Go By\"/>", @song.extend(SongXmlRepresenter).to_xml
assert_json "{\"name\":\"Days Go By\"}", @song.extend(SongJsonRepresenter).to_json
end
# test if we call super in
# ::inherited
# ::included
# ::extended
module Representer
include Representable # overrides ::inherited.
end
class BaseClass
def self.inherited(subclass)
super
subclass.instance_eval { def other; end }
end
include Representable # overrides ::inherited.
include Representer
end
class SubClass < BaseClass # triggers Representable::inherited, then OtherModule::inherited.
end
# test ::inherited.
it do
BaseClass.respond_to?(:other).must_equal false
SubClass.respond_to?(:other).must_equal true
end
module DifferentIncluded
def included(includer)
includer.instance_eval { def different; end }
end
end
module CombinedIncluded
extend DifferentIncluded # defines ::included.
include Representable # overrides ::included.
end
class IncludingClass
include Representable
include CombinedIncluded
end
# test ::included.
it do
IncludingClass.respond_to?(:representable_attrs) # from Representable
IncludingClass.respond_to?(:different)
end
end
describe "#property" do
it "doesn't modify options hash" do
options = {}
representer.property(:title, options)
options.must_equal({})
end
representer! {}
it "returns the Definition instance" do
representer.property(:name).must_be_kind_of Representable::Definition
end
end
describe "#collection" do
class RockBand < Band
collection :albums
end
it "creates correct Definition" do
assert_equal "albums", RockBand.representable_attrs.get(:albums).name
assert RockBand.representable_attrs.get(:albums).array?
end
end
describe "#hash" do
it "also responds to the original method" do
assert_kind_of Integer, BandRepresentation.hash
end
end
class Hometown
attr_accessor :name
end
module HometownRepresentable
include Representable::JSON
property :name
end
# DISCUSS: i don't like the JSON requirement here, what about some generic test module?
class PopBand
include Representable::JSON
property :name
property :groupies
property :hometown, class: Hometown, extend: HometownRepresentable
attr_accessor :name, :groupies, :hometown
end
describe "#update_properties_from" do
before do
@band = PopBand.new
end
it "copies values from document to object" do
@band.from_hash({"name"=>"No One's Choice", "groupies"=>2})
assert_equal "No One's Choice", @band.name
assert_equal 2, @band.groupies
end
it "ignores non-writeable properties" do
@band = Class.new(Band) { property :name; collection :founders, :writeable => false; attr_accessor :founders }.new
@band.from_hash("name" => "Iron Maiden", "groupies" => 2, "founders" => ["Steve Harris"])
assert_equal "Iron Maiden", @band.name
assert_nil @band.founders
end
it "always returns the represented" do
assert_equal @band, @band.from_hash({"name"=>"Nofx"})
end
it "includes false attributes" do
@band.from_hash({"groupies"=>false})
assert_equal false, @band.groupies
end
it "ignores properties not present in the incoming document" do
@band.instance_eval do
def name=(*); raise "I should never be called!"; end
end
@band.from_hash({})
end
# FIXME: do we need this test with XML _and_ JSON?
it "ignores (no-default) properties not present in the incoming document" do
{ Representable::Hash => [:from_hash, {}],
Representable::XML => [:from_xml, xml(%{<band/>}).to_s]
}.each do |format, config|
nested_repr = Module.new do # this module is never applied. # FIXME: can we make that a simpler test?
include format
property :created_at
end
repr = Module.new do
include format
property :name, :class => Object, :extend => nested_repr
end
@band = Band.new.extend(repr)
@band.send(config.first, config.last)
assert_nil @band.name, "Failed in #{format}"
end
end
describe "passing options" do
module TrackRepresenter
include Representable::Hash
end
representer! do
property :track, class: OpenStruct do
property :nr
property :length, class: OpenStruct do
def to_hash(options)
{seconds: options[:user_options][:nr]}
end
def from_hash(hash, options)
super.tap do
self.seconds = options[:user_options][:nr]
end
end
end
def to_hash(options)
super.merge({"nr" => options[:user_options][:nr]})
end
def from_hash(data, options)
super.tap do
self.nr = options[:user_options][:nr]
end
end
end
end
it "#to_hash propagates to nested objects" do
OpenStruct.new(track: OpenStruct.new(nr: 1, length: OpenStruct.new(seconds: nil))).extend(representer).extend(Representable::Debug).
to_hash(user_options: {nr: 9}).must_equal({"track"=>{"nr"=>9, "length"=>{seconds: 9}}})
end
it "#from_hash propagates to nested objects" do
song = OpenStruct.new.extend(representer).from_hash({"track"=>{"nr" => "replace me", "length"=>{"seconds"=>"replacing"}}}, user_options: {nr: 9})
song.track.nr.must_equal 9
song.track.length.seconds.must_equal 9
end
end
end
describe "#create_representation_with" do
before do
@band = PopBand.new
@band.name = "No One's Choice"
@band.groupies = 2
end
it "compiles document from properties in object" do
assert_equal({"name"=>"No One's Choice", "groupies"=>2}, @band.to_hash)
end
it "ignores non-readable properties" do
@band = Class.new(Band) { property :name; collection :founder_ids, :readable => false; attr_accessor :founder_ids }.new
@band.name = "Iron Maiden"
@band.founder_ids = [1,2,3]
hash = @band.to_hash
assert_equal({"name" => "Iron Maiden"}, hash)
end
it "does not write nil attributes" do
@band.groupies = nil
assert_equal({"name"=>"No One's Choice"}, @band.to_hash)
end
it "writes false attributes" do
@band.groupies = false
assert_equal({"name"=>"No One's Choice","groupies"=>false}, @band.to_hash)
end
end
describe ":extend and :class" do
module UpcaseRepresenter
include Representable
def to_hash(*); upcase; end
def from_hash(hsh, *args); replace hsh.upcase; end # DISCUSS: from_hash must return self.
end
module DowncaseRepresenter
include Representable
def to_hash(*); downcase; end
def from_hash(hsh, *args); replace hsh.downcase; end
end
class UpcaseString < String; end
describe "lambda blocks" do
representer! do
property :name, :extend => lambda { |name, *| compute_representer(name) }
end
it "executes lambda in represented instance context" do
Song.new("Carnage").instance_eval do
def compute_representer(name)
UpcaseRepresenter
end
self
end.extend(representer).to_hash.must_equal({"name" => "CARNAGE"})
end
end
describe ":instance" do
obj = String.new("Fate")
mod = Module.new { include Representable; def from_hash(*); self; end }
representer! do
property :name, :extend => mod, :instance => lambda { |*| obj }
end
it "uses object from :instance but still extends it" do
song = Song.new.extend(representer).from_hash("name" => "Eric's Had A Bad Day")
song.name.must_equal obj
song.name.must_be_kind_of mod
end
end
describe "property with :extend" do
representer! do
property :name, :extend => lambda { |options| options[:input].is_a?(UpcaseString) ? UpcaseRepresenter : DowncaseRepresenter }, :class => String
end
it "uses lambda when rendering" do
assert_equal({"name" => "you make me thick"}, Song.new("You Make Me Thick").extend(representer).to_hash )
assert_equal({"name" => "STEPSTRANGER"}, Song.new(UpcaseString.new "Stepstranger").extend(representer).to_hash )
end
it "uses lambda when parsing" do
Song.new.extend(representer).from_hash({"name" => "You Make Me Thick"}).name.must_equal "you make me thick"
Song.new.extend(representer).from_hash({"name" => "Stepstranger"}).name.must_equal "stepstranger" # DISCUSS: we compare "".is_a?(UpcaseString)
end
describe "with :class lambda" do
representer! do
property :name, :extend => lambda { |options| options[:input].is_a?(UpcaseString) ? UpcaseRepresenter : DowncaseRepresenter },
:class => lambda { |options| options[:fragment] == "Still Failing?" ? String : UpcaseString }
end
it "creates instance from :class lambda when parsing" do
song = OpenStruct.new.extend(representer).from_hash({"name" => "Quitters Never Win"})
song.name.must_be_kind_of UpcaseString
song.name.must_equal "QUITTERS NEVER WIN"
song = OpenStruct.new.extend(representer).from_hash({"name" => "Still Failing?"})
song.name.must_be_kind_of String
song.name.must_equal "still failing?"
end
end
end
describe "collection with :extend" do
representer! do
collection :songs, :extend => lambda { |options| options[:input].is_a?(UpcaseString) ? UpcaseRepresenter : DowncaseRepresenter }, :class => String
end
it "uses lambda for each item when rendering" do
Album.new([UpcaseString.new("Dean Martin"), "Charlie Still Smirks"]).extend(representer).to_hash.must_equal("songs"=>["DEAN MARTIN", "charlie still smirks"])
end
it "uses lambda for each item when parsing" do
album = Album.new.extend(representer).from_hash("songs"=>["DEAN MARTIN", "charlie still smirks"])
album.songs.must_equal ["dean martin", "charlie still smirks"] # DISCUSS: we compare "".is_a?(UpcaseString)
end
describe "with :class lambda" do
representer! do
collection :songs, :extend => lambda { |options| options[:input].is_a?(UpcaseString) ? UpcaseRepresenter : DowncaseRepresenter },
:class => lambda { |options| options[:input] == "Still Failing?" ? String : UpcaseString }
end
it "creates instance from :class lambda for each item when parsing" do
album = Album.new.extend(representer).from_hash("songs"=>["Still Failing?", "charlie still smirks"])
album.songs.must_equal ["still failing?", "CHARLIE STILL SMIRKS"]
end
end
end
describe ":decorator" do
let(:extend_rpr) { Module.new { include Representable::Hash; collection :songs, :extend => SongRepresenter } }
let(:decorator_rpr) { Module.new { include Representable::Hash; collection :songs, :decorator => SongRepresenter } }
let(:songs) { [Song.new("Bloody Mary")] }
it "is aliased to :extend" do
Album.new(songs).extend(extend_rpr).to_hash.must_equal Album.new(songs).extend(decorator_rpr).to_hash
end
end
# TODO: Move to global place since it's used twice.
class SongRepresentation < Representable::Decorator
include Representable::JSON
property :name
end
class AlbumRepresentation < Representable::Decorator
include Representable::JSON
collection :songs, :class => Song, :extend => SongRepresentation
end
describe "::prepare" do
let(:song) { Song.new("Still Friends In The End") }
let(:album) { Album.new([song]) }
describe "module including Representable" do
it "uses :extend strategy" do
album_rpr = Module.new { include Representable::Hash; collection :songs, :class => Song, :extend => SongRepresenter}
album_rpr.prepare(album).to_hash.must_equal({"songs"=>[{"name"=>"Still Friends In The End"}]})
album.must_respond_to :to_hash
end
end
describe "Decorator subclass" do
it "uses :decorate strategy" do
AlbumRepresentation.prepare(album).to_hash.must_equal({"songs"=>[{"name"=>"Still Friends In The End"}]})
album.wont_respond_to :to_hash
end
end
end
end
end
|