Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated isolated tests to assert correct behavior. #2010

Merged
merged 10 commits into from
Dec 25, 2016
Merged

Conversation

akshah123
Copy link
Contributor

Updated isolated tests to assert correct behavior and removed a test case that wasn't really testing anything.

Purpose

Tighten up some test cases

Changes

Fixed assertion criteria for test cases to look for correct behavior

Caveats

Removed test isn't really needed

Related GitHub issues

N/A

Additional helpful information

Removed a test case that wasn't really testing anything.
@mention-bot
Copy link

@akshah123, thanks for your PR! By analyzing the history of the files in this pull request, we identified @remear and @dubadub to be potential reviewers.

@bf4
Copy link
Member

bf4 commented Dec 21, 2016

rubocop

test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:21:37: C: Style/SpaceInsideHashLiteralBraces: Space inside { missing. (https://github.com/bbatsov/ruby-style-guide#spaces-operators)
      render jsonapi: post, fields: {posts: ['title']}
                                    ^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:21:54: C: Style/SpaceInsideHashLiteralBraces: Space inside } missing. (https://github.com/bbatsov/ruby-style-guide#spaces-operators)
      render jsonapi: post, fields: {posts: ['title']}
                                                     ^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:104:18: C: Style/SpaceInsideHashLiteralBraces: Space inside { missing. (https://github.com/bbatsov/ruby-style-guide#spaces-operators)
      expected = {'name' => 'Johnny Rico'}
                 ^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:104:42: C: Style/SpaceInsideHashLiteralBraces: Space inside } missing. (https://github.com/bbatsov/ruby-style-guide#spaces-operators)
      expected = {'name' => 'Johnny Rico'}
                                         ^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:109:56: C: Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols. (https://github.com/bbatsov/ruby-style-guide#consistent-string-literals)
      assert_equal expected, JSON.parse(response.body)["data"]["attributes"] 
                                                       ^^^^^^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:109:64: C: Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols. (https://github.com/bbatsov/ruby-style-guide#consistent-string-literals)
      assert_equal expected, JSON.parse(response.body)["data"]["attributes"] 
                                                               ^^^^^^^^^^^^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:109:77: C: Style/TrailingWhitespace: Trailing whitespace detected. (https://github.com/bbatsov/ruby-style-guide#no-trailing-whitespace)
      assert_equal expected, JSON.parse(response.body)["data"]["attributes"] 
                                                                            ^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:113:18: C: Style/SpaceInsideHashLiteralBraces: Space inside { missing. (https://github.com/bbatsov/ruby-style-guide#spaces-operators)
      expected = {'title'  => 'This is a test' }
                 ^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:113:28: C: Style/SpaceAroundOperators: Operator => should be surrounded by a single space. (https://github.com/bbatsov/ruby-style-guide#spaces-operators)
      expected = {'title'  => 'This is a test' }
                           ^^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:117:56: C: Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols. (https://github.com/bbatsov/ruby-style-guide#consistent-string-literals)
      assert_equal expected, JSON.parse(response.body)["data"]["attributes"]
                                                       ^^^^^^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:117:64: C: Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols. (https://github.com/bbatsov/ruby-style-guide#consistent-string-literals)
      assert_equal expected, JSON.parse(response.body)["data"]["attributes"]
                                                               ^^^^^^^^^^^^

Copy link
Member

@bf4 bf4 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, I think you almost got it.

payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_renderer', params: payload, headers: headers
assert expected, response.body
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so, this should have raised an exception when hitting render_with_jsonapi_renderer which calls render jsonapi: json but there's no jsonapi renderer registered. good test to have

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the problem is that it raises an exception while trying to create a new author since params are not parsed correctly without this. So, I can setup another api method.

I think i have a way to change controller to test this case. Let me take a shot.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bf4 i can't get the test controller to return the actual exception. I tried using rescue_from but i think since the error is with render it just returns 500 with blank body.

I think for now, I am just going to assert that response.status = 500

payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_renderer', params: payload, headers: headers
assert expected, response.body
assert_equal expected, JSON.parse(response.body)["data"]["attributes"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not just assert_equal expected, JSON.parse(respond.body)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was because actual response has tons of other things added to it like meta, relationships which was not part of this test and would break anytime a new element is added.

payload = '{"data": {"attributes": {"title": "This is a test","body": "Of an emergency alert system."}, "type": "posts"},"fields": { "posts" : ["title"] } }'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_fields?fields[posts][]=title', params: payload, headers: headers
assert_equal expected, JSON.parse(response.body)["data"]["attributes"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this test belongs here. (typo in name as well). This test appears to be testing usage of the jsonapi renderer, where all this file is doing is testing registering it, which is why it's isolated

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point. I will remove it.

@akshah123
Copy link
Contributor Author

@bf4 I made requested changes. Let me know what you think about failure check.

@bf4
Copy link
Member

bf4 commented Dec 22, 2016

@akshah123

test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:63:7: W: Lint/UselessAssignment: Useless assignment to variable - expected. (https://github.com/bbatsov/ruby-style-guide#underscore-unused-vars)
      expected = {
      ^^^^^^^^
test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:68:9: C: Style/AlignHash: Align the elements of a hash literal if they span more than one line.
        'type' => 'authors'

:( did you check the CI failures?

Copy link
Member

@bf4 bf4 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Almost there! I just need some help understanding some of the changes that, on the surface, don't look related to fixing the expectation.

@@ -12,7 +12,8 @@ class << self
end

def render_with_jsonapi_renderer
author = Author.new(params[:data][:attributes])
attributes = params[:data].present? ? params[:data][:attributes] : {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why? how could this not be set and why would we want that fallback if not set?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is because when adapter is not set as jsonapi, params are not set. This is there so that it fails on render and not on trying to set Author object. Since we use the same controller in case where it should succeed and fail, I wanted to make sure this part doesn't cause a failure.

@@ -64,13 +65,13 @@ def test_jsonapi_renderer_not_registered
'attributes' => {
'name' => 'Johnny Rico'
},
'type' => 'users'
'type' => 'authors'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why? type looks correct to me

Copy link
Contributor Author

@akshah123 akshah123 Dec 22, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just wanted it to match what was being returned from controller. I don't have an issue with changing it back to "users" just thought that this way it would match.

payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_renderer', params: payload, headers: headers
assert expected, response.body
assert_equal expected, JSON.parse(response.body)['data']['attributes']
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why only checking part of response. did this fail when changing assert to assert_equal? perhaps should have be expected.to_json

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it did fail. The problem is that response.body contains a lot of stuff then just data.attributes and type. It includes relationships, id and other things.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here is the actual response.body

{
    "data": {
        "id": "author",
        "type": "authors",
        "attributes": {
            "name": "Johnny Rico"
        },
        "relationships": {
            "posts": {
                "data": null
            },
            "roles": {
                "data": null
            },
            "bio": {
                "data": null
            }
        }
    }
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, this is because of the PORO Author having relationships that are explicit now, whereas before they were sort of squishy...

Fix is we should be explicit what our model and serializer are:

class JsonApiRendererTest < ActionDispatch::IntegrationTest
  include ActiveSupport::Testing::Isolation
  class Author < ::Model
    attributes :name
  end
  class AuthorSerializer < ActiveModel::Serializer
    type: 'users'
    attribute :id
    attribute :name
  end

I think that's a better expectation, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think so. But I can't get your code to work. The dependency required is getting a bit too much. For now, i have updated expected object to include all relationships so that we check for exact output.

}
}
payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_renderer', params: payload, headers: headers
assert expected, response.body
assert_equal 500, response.status
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we make an assertion about the nature of the failure by matching on the response.body?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't get response.body to show the exception. It kept returning empty body. I think this probably has something to do with it failing on render.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good.

can you add an assertion for the empty body?

If you know what the exception actually, was, would love for you to paste it and stack trace here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actual exception message:

Missing template json_api_renderer_test/test/render_with_jsonapi_renderer with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby]}. Searched in:

backtrace

["test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:19:in `render_with_jsonapi_renderer'",
 "test/active_model_serializers/register_jsonapi_renderer_test_isolated.rb:68:in `test_jsonapi_renderer_not_registered'"]

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awesome! thanks!

@akshah123
Copy link
Contributor Author

@bf4 i have made some changes so that the tests pass. It took a while since i ran into issues with different versions of rails and had a hard time trying to reproduce the failing tests locally. I also made modification to check for exact exception when that information is available.

Copy link
Member

@bf4 bf4 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for much for your attention to this! A few small changes to make it a little more confident and less 'timid', as Avdi would say.

payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_renderer', params: payload, headers: headers
assert expected, response.body
assert_equal 500, response.status
assert response.request.env['action_dispatch.exception'].is_a?(ActionView::MissingTemplate) if response.request.present?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when is response.request.present? not true?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From what I can tell, it changes on a specific rails version. At some 4.x version, we start getting response.request but we dont' have that for 4.1.

}
}
payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_renderer', params: payload, headers: headers
assert expected, response.body
assert_equal 500, response.status
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good.

can you add an assertion for the empty body?

If you know what the exception actually, was, would love for you to paste it and stack trace here.

payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_renderer', params: payload, headers: headers
assert expected, response.body
assert_equal expected, JSON.parse(response.body)['data']['attributes']
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, this is because of the PORO Author having relationships that are explicit now, whereas before they were sort of squishy...

Fix is we should be explicit what our model and serializer are:

class JsonApiRendererTest < ActionDispatch::IntegrationTest
  include ActiveSupport::Testing::Isolation
  class Author < ::Model
    attributes :name
  end
  class AuthorSerializer < ActiveModel::Serializer
    type: 'users'
    attribute :id
    attribute :name
  end

I think that's a better expectation, no?

@@ -12,7 +12,9 @@ class << self
end

def render_with_jsonapi_renderer
author = Author.new(params[:data][:attributes])
unlocked_params = Rails::VERSION::MAJOR >= 5 ? params.to_unsafe_h : params
attributes = unlocked_params[:data].present? ? unlocked_params[:data][:attributes] : {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, I gather Author.new(params[:data][:attributes]) is failing for some reason. perhaps we should instead author = Author.new(params.require(:data).require(:attributes))? I'm not sure what the need is to cast the ActionController::Parameters or when data wouldn't be present.

In actual usage I would use the JsonApi deserializer here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right that params[:data] is not set at all and the reason is that app doesn't know how to parse provided data.

.require will not help since it doesn't see data at all. Also, require will cause problem when jsonapi is not registered since it doesn't see the actual value.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, so params is {} ? Then that's probably still a good failure :)

@akshah123
Copy link
Contributor Author

@bf4 made some suggested changes. However, now the build is failing for something unrelated to my code. I can't reproduce this failure locally even with travis-ci's docker image. Do you have any idea on what I can do to get it passing?

@bf4
Copy link
Member

bf4 commented Dec 25, 2016

@akshah123 re: #2010 (comment) these failures are resolved on master. If you rebase, they should go away.

Copy link
Member

@bf4 bf4 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You've been working on this PR a while now, and the main goal of it is done. Thanks! I can do some of the other things I'd like in a followup :)

@@ -12,7 +12,9 @@ class << self
end

def render_with_jsonapi_renderer
author = Author.new(params[:data][:attributes])
unlocked_params = Rails::VERSION::MAJOR >= 5 ? params.to_unsafe_h : params
attributes = unlocked_params[:data].present? ? unlocked_params[:data][:attributes] : {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, so params is {} ? Then that's probably still a good failure :)

'posts' => { 'data' => nil },
'roles' => { 'data' => nil },
'bio' => { 'data' => nil }
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}
}
payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
headers = { 'CONTENT_TYPE' => 'application/vnd.api+json' }
post '/render_with_jsonapi_renderer', params: payload, headers: headers
assert expected, response.body
assert_equal 500, response.status
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awesome! thanks!

}
}

payload = '{"data": {"attributes": {"name": "Johnny Rico"}, "type": "authors"}}'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we should include a uuid here. how about "id": ""36c9c04e-86b1-4636-a5b0-8616672d1765" will make the expectation simpler. JSON API recommends that if a client wants to create an id on post, to use a uuid.

You've been working on this PR a while now, and the main goal of it is done. Thanks! I can do some of the other things I'd like in a followup :)

@bf4 bf4 merged commit f246741 into rails-api:master Dec 25, 2016
bf4 pushed a commit that referenced this pull request Jan 6, 2017
* Updated isolated tests to assert correct behavior.
* Added check to get unsafe params if rails version is great than 5
bf4 pushed a commit that referenced this pull request Jan 7, 2017
* Updated isolated tests to assert correct behavior.
* Added check to get unsafe params if rails version is great than 5
bf4 added a commit that referenced this pull request Jan 10, 2017
* Merge pull request #1990 from mxie/mx-result-typo

Fix typos and capitalization in Relationship Links docs [ci skip]

* Merge pull request #1992 from ojiry/bump_ruby_versions

Run tests by Ruby 2.2.6 and 2.3.3

* Merge pull request #1994 from bf4/promote_architecture

Promote important architecture description that answers a lot of questions we get
Conflicts:
	docs/ARCHITECTURE.md

* Merge pull request #1999 from bf4/typos

Fix typos [ci skip]

* Merge pull request #2000 from berfarah/patch-1

Link to 0.10.3 tag instead of `master` branch

* Merge pull request #2007 from bf4/check_ci

Test was failing due to change in JSON exception message when parsing empty string

* Swap out KeyTransform for CaseTransform (#1993)

* delete KeyTransform, use CaseTransform

* added changelog

Conflicts:
	CHANGELOG.md

* Merge pull request #2005 from kofronpi/support-ruby-2.4

Update jsonapi runtime dependency to 0.1.1.beta6

* Bump to v0.10.4

* Merge pull request #2018 from rails-api/bump_version

Bump to v0.10.4 [ci skip]
Conflicts:
	CHANGELOG.md

* Merge pull request #2019 from bf4/fix_method_redefined_warning

Fix AMS warnings

* Merge pull request #2020 from bf4/silence_grape_warnings

Silence Grape warnings

* Merge pull request #2017 from bf4/remove_warnings

Fix mt6 assert_nil warnings

* Updated isolated tests to assert correct behavior. (#2010)

* Updated isolated tests to assert correct behavior.
* Added check to get unsafe params if rails version is great than 5

* Merge pull request #2012 from bf4/cleanup_isolated_jsonapi_renderer_tests_a_bit

Cleanup assertions in isolated jsonapi renderer tests a bit

* Add Model#attributes helper; make test attributes explicit

* Fix model attributes accessors

* Fix typos

* Randomize testing of compatibility layer against regressions

* Test bugfix

* Add CHANGELOG

* Merge pull request #1981 from groyoh/link_doc

Fix relationship links doc
Conflicts:
	CHANGELOG.md
GregPK pushed a commit to GregPK/active_model_serializers that referenced this pull request Apr 25, 2017
* Updated isolated tests to assert correct behavior.
* Added check to get unsafe params if rails version is great than 5
GregPK pushed a commit to GregPK/active_model_serializers that referenced this pull request Apr 25, 2017
* Merge pull request rails-api#1990 from mxie/mx-result-typo

Fix typos and capitalization in Relationship Links docs [ci skip]

* Merge pull request rails-api#1992 from ojiry/bump_ruby_versions

Run tests by Ruby 2.2.6 and 2.3.3

* Merge pull request rails-api#1994 from bf4/promote_architecture

Promote important architecture description that answers a lot of questions we get
Conflicts:
	docs/ARCHITECTURE.md

* Merge pull request rails-api#1999 from bf4/typos

Fix typos [ci skip]

* Merge pull request rails-api#2000 from berfarah/patch-1

Link to 0.10.3 tag instead of `master` branch

* Merge pull request rails-api#2007 from bf4/check_ci

Test was failing due to change in JSON exception message when parsing empty string

* Swap out KeyTransform for CaseTransform (rails-api#1993)

* delete KeyTransform, use CaseTransform

* added changelog

Conflicts:
	CHANGELOG.md

* Merge pull request rails-api#2005 from kofronpi/support-ruby-2.4

Update jsonapi runtime dependency to 0.1.1.beta6

* Bump to v0.10.4

* Merge pull request rails-api#2018 from rails-api/bump_version

Bump to v0.10.4 [ci skip]
Conflicts:
	CHANGELOG.md

* Merge pull request rails-api#2019 from bf4/fix_method_redefined_warning

Fix AMS warnings

* Merge pull request rails-api#2020 from bf4/silence_grape_warnings

Silence Grape warnings

* Merge pull request rails-api#2017 from bf4/remove_warnings

Fix mt6 assert_nil warnings

* Updated isolated tests to assert correct behavior. (rails-api#2010)

* Updated isolated tests to assert correct behavior.
* Added check to get unsafe params if rails version is great than 5

* Merge pull request rails-api#2012 from bf4/cleanup_isolated_jsonapi_renderer_tests_a_bit

Cleanup assertions in isolated jsonapi renderer tests a bit

* Add Model#attributes helper; make test attributes explicit

* Fix model attributes accessors

* Fix typos

* Randomize testing of compatibility layer against regressions

* Test bugfix

* Add CHANGELOG

* Merge pull request rails-api#1981 from groyoh/link_doc

Fix relationship links doc
Conflicts:
	CHANGELOG.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants